November 20, 2008, 12:06:35 pm *
News:
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: .QL: How to add a method to an existing type?  (Read 5951 times)
KirillOsenkov
Newbie
*
Posts: 11


« on: June 07, 2007, 03:36:04 pm »

Hi, another newbie question.

I just started typing "from Class c..." and then I tried to look for something like c.getNumberOfLinesOfCode() but couldn't find it. What's the correct way to find the total lines of code occupied by a class?

And the generalization of the previous question: is it possible to add custom methods to the Class class? I mean, I'd like to declare my custom getNumberOfLinesOfCode() on the Class class so that the following query makes sense:
from Class c
where c.getNumberOfLinesOfCode() > 120
select c.Name
How is this possible? If this is currently not possible, what are the alternatives? It looks like extension methods from C# 3.0 could come in handy here.

Thanks a lot!
Logged
Semmle Coders
Newbie
*
Posts: 13


« Reply #1 on: June 08, 2007, 11:25:00 am »

Hi Kirill,

the answer to your second question is YES, you can easily add methods to the existing classes. The existing classes are all defined in the default.ql file that comes with the plugin. To open it, you need to select "Open library" menu item in one of the plugin view's pull down menu.

Now to answer your first question, here is an example of a custom class with the function that you wanted to define:

Code:
class MyClass extends Class {
   int getNumberOfLinesOfCode() {
      result = this.getLocation().getNumberOfLines()
   }
}

from MyClass c
where c.getNumberOfLinesOfCode() > 120
select c.getName(), c.getNumberOfLinesOfCode()

If you would rather like to have the function getNumberOfLinesOfCode() in the Class class itself, feel free to move its definition to the Class class in the default.ql file. More information on this topic can be found in the tutorial.

Semmle Coders
Logged
Oege de Moor
Newbie
*
Posts: 30


« Reply #2 on: June 08, 2007, 11:52:51 am »

As a side-remark, the method getNumberOfLines is already defined in MetricRefType, which is a subclass of RefType. So in fact you could also have written

Code:
from MetricRefType t
where t.getNumberOfLines()>120
select t, t.getNumberOfLines()

That gives you all reference types, whether classes or interfaces. If you just want real classes, add the conjunct "and t instanceof Class" to the where-clause.


Logged
KirillOsenkov
Newbie
*
Posts: 11


« Reply #3 on: June 14, 2007, 04:12:18 pm »

Wow, this is really cool. .QL is very powerful!

Thanks,
Kirill Osenkov
Logged
Pages: [1]
  Print  
 
Jump to: