• Home
  • Events
  • About
  • Effective Groovy with CodeNarc 0.12

    January 25th, 2011

    The new release of everyone’s favorite static anaylsis engine for Groovy is here. Time to download CodeNarc 0.12 while it’s hot. And in case this is your first time, CodeNarc analyzes your Groovy code and looks for potential problems and errors, creating a nice report or flagging the problem in your IDE. It’s like FindBugs, Lint, or PMD, but for Groovy.

    So what’s new in 0.12? Performance improvements, 35 new analysis rules, and a new logo. It’s supposed to be an armadillo, but no one can tell. We’re calling it the CodeNarc Grue, as in “You are in a maze of twisty little groovy scripts, all alike.” Anyway, here’s the rundown:

    Effective Groovy

    A big focus of 0.12 is making sure you write groovy Groovy. Time to unlearn your Java and discover a new way of coding. Before reading the rules, you may want to take the quiz and see if you can spot what can be improved.

    UnnecessaryCallForLastElement – Java developers get the last element of a list like this: “list.get(list.size()-1)”. In Groovy you can just call “list.last()” or “list[-1]”.

    UnnecessaryCollectCall – The collect method is useful, but once you learn the spread operator then you use it a lot less. Constructs list “list.collect { it.toString() }” are better written as “list*.toString()”.

    UnnecessaryGetter – Simple getters can be written as property access. So “strings.getProperty()” becomes “strings.property”

    UnnecessaryNullCheck – One of my favorites. Null checks can be replaced with the null safe dereference. So the code “(prop != null && prop.isValid())” can be rewritten as “(prop?.isValid())”.

    ConfusingTernary – Groovy’s conciseness means ternary and elvis operators fit better into the language, and feel more natural. The format is “condition ? true-clause : false-clause”. If your condition is a negative expression, then the ternary is pointlessly confusing. For instance, prefer “(prop.isActive() ? ‘alive’: ‘dead’)” to the backwards construct “(!prop.isActive() ? ‘dead’: ‘alive’)”.

    One last quiz before we go. Spot the error?

    UnnecessaryObjectReferences – Yep, long strings of setters and getters is standard Java. You don’t need to follow suit in Groovy. This code:

    Is better written as:

    I See (More) Dead Code

    The previous version introduced dead code analysis: flagging code that is meaningless or cannot be reached. It’s been expanded in three directions with version 0.13. Before reading on, you may want to take the Dead Code Quiz and see how you do.

    UnnecessaryCatchBlock – If your catch block does nothing but throw the original exception, then you should delete the catch block. This happens when you either forget to add an error logging statement or forget to back out some temporary testing code.

    UnnecessaryNullCheckBeforeInstanceOf – An instanceof check on null always returns false. So constructs like “if (x != null && x instanceof Class)” can always be simplified to just “if (x instanceof Class)”.

    UnusedPrivateMethodParameter – If a method parameter to a private method is not referenced from the body of the method, then you should delete it and clean up the API.

    Cleaner Junit Tests

    Some new rules were introduced to make your JUnit (ie. GroovyTestCase) based tests cleaner and conciser. Take the quiz or just read on.

    UseAssertFalseInsteadOfNegation – The code “assertEquals(false, property)” should be rewritten as “assertFalse(property)”. It’s clearer that way.

    UseAssertTrueInsteadOfNegation – The inverse of the previous rule… rewrite “assertEquals(true, property)” as “assertTrue(property)”

    JUnitTestMethodWithoutAssert – Ever write a test method and forget to make asserts? I have. A test method without assertions

    Better Designed Objects

    I read somewhere that there are 13 different distinct types of OO inheritence. Different books promote different ones as best practices. Should you use abstract classes? abstract methods? final classes? Our should you bag it all and learn to program functionally? If you’re stuck in OO, then these rules might help you write better obejcts.

    AbstractClassWithoutAbstractMethod What’s the point of an abstract class without an abstract method? You could just give the object a protected constructor instead, which mostly achieves the same thing. Some people love this rule. Go figure.

    EmptyMethodInAbstractClass – What a sec… you wrote an empty method in an abstract class? It’s clearer to make the class abstract because an empty method pretty much guarantees that the contract of the method is undiscoverable from the type of the object. Again, it’s your choice to use this rule or not.

    ConstantsOnlyInterface rule – Interfaces are not a good place to put a bag of constants. Put them in a class and use static imports instead of subclassing to bring them in scope.

    FinalClassWithProtectedMember – A final class cannot be subclasses. A protected method can be subclassed. It’s pointless to mix the two. Make the method @PackageScope or make the class non-final

    Logging

    Logging shouldn’t be hard. Yet a whole gaggle of frameworks exist to help you with it. CodeNarc 0.13 makes sure you do logging correctly with 4 new rules. Take the test or just read on.

    LoggerForDifferentClass – You typically instantiate a logger using the enclosing Class name. This rule triggers if you refer to a different class, which is usually a copy and past error.

    LoggerWithWrongModifiers – Loggers should be private, static, and final. If it’s not then you’ll get a nice little warning

    LoggingSwallowsStacktrace – Passing an Exception object to a Logger.error(Object) method typically does not log a stack trace. Did you know that? CodeNarc will remind you.

    MultipleLoggers – A class with two loggers is usually a copy and paste error

    Unnecessary Instantiations

    In Groovy, there is typically no need to directly instantiate BigDecimal, Double, Float, or Integer types. 0.12 has several new rules to make sure you remember. Plus this gem:

    UnnecessaryInstantiationToGetClass There is no need to create an instance if you just want the Class reference. Replace code like this: “new MyObject().getClass()” with the literal “MyObject.class”

    Common Errors

    And now the leftovers. These new rules find common errors that catch out Groovy beginners. Don’t get caught out!

    MissingNewInThrowStatement – The Groovy syntax lets you throw things that don’t compile in Java, like: “throw RuntimeException()” Hey, where is the new keyword? You forgot it, but CodeNarc won’t.

    SimpleDateFormatMissingLocale – If you need to use SimpleDateFormat then specify a Locale in the constructor. It’s a best practice darn it!

    CompareToWithoutComparable – If you implement a compareTo method, but don’t implement the Comparable interface, then you get funny results for the == operator in some versions of Groovy. If you implement compareTo then implement Comparable as well

    CloseWithoutCloseable – Dude, please implement Closeable if you have a close method. It’s a pain if you don’t for us Java developers.

    RequiredString – Every class is required to have a certain String present. For instance: a copyright statement. This rule has proven useful many times to me.

    ExplicitGarbageCollection – Don’t call garbage collection explicitly. ‘Nuff said.

    CatchArrayIndexOutOfBoundsException Why are you catching ArrayIndexOutOfBoundsException? Surely you can change the code to not rely on exceptions being thrown and instead proeprly use an index variable.

    CatchIndexOutOfBoundsException rule See above. There is typically no need to catch this Exception type in practice.

    The Future

    0.13 is on it’s way. There are already 10 new rules in 0.13 (by the way, Snapshot downloads are available from Canoo). We’re going to continue working on new rules and making the project better. There is another project called Groovy Lint as well. There are only a handful of rules in GroovyLint, but it integrates into Groovyc instead of run as a separate tool. If you’re curious you may want to check it out. That’s all for now. See you in the 0.13 release!

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    IDEA series (ix) selective actions

    January 12th, 2011
    Working with selections

    Please note that this is for Groovy and Grails development on Mac OS X with Swiss-german keyboard layout and default keymap, so the keybindings may differ on your machine. (For Windows, you most often can replace Cmd with Ctrl)

    We have seen the editing support for lines, combined with selections. This part is more specifically about working with selections.
    know your keyboard navigation
    first of all, it is very helpful to familiarize yourself with your OS-specific keyboard commands for moving the cursor around and with the Shift key pressed, doing a selection. On Mac that is Cmd left/right for begin/end of line and Alt left/right for jumping over words. Of course you can use the mouse for selections but once you master the keystrokes, you will be faster and more precise.
    Cmd W (Shift for reverse)
    is widening the current selection. That is, if you already have a selection, it expands it to the next enclosing syntactical scope (expression, statement, block). Without a selection, it starts a selection at the caret.
    Mac users may expect Cmd W to close the current editor (internal window) as typical for mac applications, but that functionality is mapped to Cmd F4 in the standard keymap (somehow resembles the Windows keystroke).
    I use widening most of the time to select a small expression precisely – often for later use in a refactoring. I start in the middle of the code and hit Cmd W repeatedly.
    When selecting a larger block, let’s say a method or a whole class body, it’s efficient to place the cursor just after the opening brace and hit Cmd W just once to select the whole block.
    Cmd Alt T
    surrounds the selection (or current line if there is no selection) with a live template. This features spares you the need for fiddling around with cursor positioning to put some code into an “if” block and the likes. I even made my own templates for surrounding a selection with parentheses, brackets (to make a literal Groovy list), braces (to make a closure or block), single quotes, and double quotes.
    Especially putting quotes around a selection is nice since otherwise IDEA sometimes inserts pairs of quotes when it shouldn’t.
    Context menu -> Compare with Clipboard
    when you have a selection and open the context menu (right mouse click) you’ll see a “Compare with clipboard” entry, which opens the internal diffing view. Nice.
    keep groovin’
    Dierk
    @mittie
    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    IDEA series (viii) line management

    January 11th, 2011
    Rethinking your line management (pun intended)
    Please note that this is for Groovy and Grails development on Mac OS X with Swiss-german keyboard layout and default keymap, so the keybindings may differ on your machine. (For Windows, you most often can replace Cmd with Ctrl)

    This series has come to the point where we do the actual editing of the code and we start with working on the current line. That is, the actions below work on the current line where the caret is positioned in. When it says “or selection” then the action works on the current selection if there is any and on the current line otherwise.
    Cmd Y
    yanks out the current line. I use this a lot. It is quicker than selecting and deleting even when yanking many lines, since you can simply press the same keystroke again (remember the discussion about interaction design?).
    Cmd D
    duplicate the current line (or selection). Again, a much used shortcut for me for making variants of the current line or selection. Some Eclipse converts take issue with this one since they expect a delete action. (It’s worse when you get from IDEA to Eclipse and mistakingly delete a line that you want to duplicate, but then you deserve the pain)
    Cmd /
    comments the current line or selection with a line comment (//). This has a little gotcha when working with non-english keyboards where you need to press Shift to get to the slash character. With my swiss-german layout the shortcut is actually Cmd . (dot) because the dot is where the slash is on english keyboards (see also http://youtrack.jetbrains.net/issue/IDEA-63779).
    Ctrl Shift J
    join the current line with next line. This shortcut is used by many text-editors. It is worth remembering. Much faster than a manual join.
    Cmd Shift up/down
    moves the current line (or selection) one line up or down. This used to have issues in older versions when it tried to be too clever about which lines to jump over, e.g. when you select a whole method, it jumps not per-line but per-method. This makes sense for methods but other blocks are not as easy to support since you may want to nest them. The “intelligent” jumping sometimes led to unexpected results, especially in Groovy code. I haven’t seen any trouble with version X, yet.
    Cmd Alt V
    the “insert explaining variable” refactoring is something you normally call on a selected expression but when there is no selection, it takes the current line as the expression. Now, this has an interesting effect: in a variable assignment, you never have to write the left-hand side! I learned this from IDEA uber-guru Vaclav Pech himself. It works like this: you don’t type “MyType myRef = expression” but only “expression” then strike Cmd Alt V. Try this and enjoy the effect.
    keep groovin’
    Dierk
    @mittie
    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    IntelliJ IDEA series (vii)

    January 10th, 2011

    helpful selection modes and type inference

    Please note that this is for Groovy and Grails development on Mac OS X with Swiss-german keyboard layout and default keymap, so the keybindings may differ on your machine. (For Windows, you most often can replace Cmd with Ctrl)

    With only a few keystrokes it becomes much easier to move code around in your editor or gather more information.

    Press the Alt key while selecting with the mouse

    and the selection is in “column” mode. Very useful for many well-formatted source files and often even more in resource files with tabular format.

    Column mode

    can also be toggled with a keystroke. I couldn’t quite remember the default keystroke, so I’ve set it to Cmd Alt Backspace. To find your keystroke look in the Edit menu under Column Mode (or as always use Cmd Shift A and type “col”).

    Hold Cmd while hovering over a reference

    and you will see the inferred type like so:

    Note that this is Groovy code and from the content of the dynamically typed myMap, IDEA infers that this is a Map from Strings to Integers, i.e. not only the raw type is inferred but also the generic type! Is that cool or is that cool?

    We touch a very important topic here.

    Many developers are under the misconception that IDEs can only do what the compiler of a specific language does. The Groovy compiler does no type inference but still, IDEA does and uses this info for code completion, analysis, refactorings, warnings on mistyped method names, and so on.

    This shouldn’t come as a big surprise. Even for Java, IDEs do a lot more analysis than what the Java compiler does.

    Using a dynamic language like Groovy does not mean that you lose all the IDE support (as you can hear occasionally). Also note that in Groovy you can always declare your types, making it an optionally typed language.
    Inside IDEA, you can seamlessly switch between Groovy and Java, using cross-language testing, debugging, analysis tools, and refactoring.

    The next post will be about more editing commands.

    keep groovin’
    Dierk
    @mittie

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    IntelliJ IDEA series (vi)

    January 9th, 2011

    Understanding dependencies – a smooth intro

    Beside all the navigation, editing, and refactoring goodness that IDEA brings to the table, there is one feature that I really adore and find under-utilized by most teams: the dependency structure matrix (DSM).

    It seems that many developers shy away because they expect it to be difficult, while in fact it is easy to understand and remember with just a little bit of intro. Here it comes.

    Prerequisites: your project must compile. That’s it.

    How to start: from the Analyze menu choose Analyze Dependency Matrix.

    This is what you see (this is the code from my personal wiki – yes, it has only 5 classes. The code is under github.com/Dierk/MittieWiki)

    Now, what does this mean? Well, it actually shows the layering of your architecture – not how you want it to be but how it actually is.

    How would you depict the architectural layers in a document? Probably as some kind of pyramid with the common functionality as the fundamental bottom layers and users of the infrastructure on top of it. The DSM is exactly that!

    If you want, you can imagine the pyramid being slightly pushed to the left such that the left edges align. Then you have exactly the lower-left triangle of the DSM. The upper layers depend on what is below them. They use the common base functionality.
    The common base layers use nothing, therefore they go to the bottom. The uppermost layers are used by nobody.

    For the moment, we don’t look at the numbers since we only seek to understand the structure.

    The structure of the DSM shows that EventController (second line) uses classes below it. But which ones? Simply click on the EventController label and you will see this picture:

    Every class that EventController actually uses gets an orange marker. Do yo see the one at CookService? From that we can tell that EventController uses CookService and no other project class!

    CookService seems to be an interesting class. So let’s click on its label:

    Do you see the green markers? They tell that CookService is used by EventController, FindController, and PageController.

    From this intro you can infer that green markers should always be above the current selection and orange ones below.

    Understanding the numbers

    The numbers quite obviously show how often a class uses some other class. But which cell contains this information? Well, if you think about it, there is only one possible way of arranging numbers in cells that makes sense. Let’s revisit

    The blue cross covers the number 5 saying that EventController uses CookService 5 times.

    I mean, you only use classes below yourself, that means a cell that tells how often you use it must necessarily be placed below you, right? And where else should it be than in the row of the used class? And it is quite obviously in the column that responds to the using class.
    The columns are not labeled explicitely but they are in same sequence as the rows and therefore you can simply use the diagonal as a “mirror”.

    Fazit: usages along with usage counts are shown in the column below the diagonal!

    With this knowledge we can anticipate what happens when we select the other controller classes. They equally show 5 usages of CookService.

    Now, think in the opposite direction. Who uses our class?

    EventController uses CookService 5 times. In other words: CookService is used by EventController 5 times. And the same is true for FindController and PageController. That’s three times the used-by count of 5 in the same row. This means: used-by along with its counts is shown in the row of the used class!

    In cases where the situation is less obvious, you can select a single cell (here where the 5 is in) to see the whole picture:

    So much for the intro.

    A very comprehensive description with many use cases and screencasts is under http://www.jetbrains.com/idea/features/dependency_analysis.html . You will see that this intro helps you understanding it. Once you have understood the concept, you will easily grasp package dependencies, module dependencies, and cyclic references.

    The DSM has become an indispensable tool for my consulting work. Whenever I visit a new project, it is my first tool to fire up. There is so much to tell from this simple matrix.

    After a while, you start to see patterns like a horizontal line of dependencies (as in CookService) to show a service or utility class or a line just below the diagonal to show a strict layering, breaches of layering, and so on.

    A word of caution

    Static analysis never shows the whole truth. Especially, it doesn’t show semantic dependencies. Just recently I heard a friend advocating the use of dependency injection to avoid unwanted dependencies in the DSM. It is very easy to fool oneself with that approach if the semantic dependency is not resolved at the same time.
    Actually, I’d rather like to see my unwanted dependencies in the DSM than hiding it with tricks (DI, AOP, “Object” in signatures, “def” in Groovy).

    I hope this little intro motivated you to give the DSM a try.

    keep groovin’
    Dierk
    @mittie
    dzone: http://www.dzone.com/links/r/intellij_idea_tips.html

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks

    css.php