Archive

Archive for the ‘Patterns’ Category

Turtle DSL, another little language

May 11th, 2009

The latest revision of the Ludo game uses yet another DSL.

As you might recall, the Ludo game uses a fluent interface to create squares. This time, we are going to layout the squares on a grid for printing (or drawing).

The basic idea is to use a turtle that walks around the grid. The turtle can advance and change direction. With each step the turtle puts the next square on its current cell (unless told to not do so). Class SquareGrid provides a turtle that can be scripted to put squares on the grid. The turtle knows the sequence of linked squares and can do three things:

  • It can turn 90 degrees.
  • It can put the next square on the current cell, and advance one cell.
  • It can advance one cell without putting a square.

Actually, the turtle can do two more things:

  • It can memorize the begin of a branch.
  • It can go back to that position.

This is all we need to layout squares on the grid. The following code creates a grid of 15 on 15 cells, and executes four times the same sequence of turtle movements. Once for each quarter of the game board.

public static SquareGrid makeGrid(Iterator start) {
    SquareGrid grid = new SquareGrid(15,15);
    makeQuarter(grid.getTurtle(5, 1, DOWN, start.next()));
    makeQuarter(grid.getTurtle(1, 9, LEFT, start.next()));
    makeQuarter(grid.getTurtle(9, 13, UP, start.next()));
    makeQuarter(grid.getTurtle(13, 5, RIGHT, start.next()));
    return grid;
}
private static void makeQuarter(Turtle turtle) {
    turtle
        .move(1)
        .turnLeft()
        .move(5)
        .turnLeft()
        .skip()
        .move(5)
        .turnRight()
        .move(1)
        .branchHere()
        .move(2)
    .gotoBranch()
        .turnRight()
        .skip()
        .move(5)
        .skip()
        .move(1);
}

This little DSL is obviously inspired by the LOGO programming language. For the full implementation, please refer to SquareGrid’s source code.

TLDR, fun with turtles.

akuhn Patterns, Readability

Arrays considered harmful

April 20th, 2009

Java offers to kind of containers, arrays and collections.

As a rule, you should always prefer collections. Collections offer a higher level of abstractions. The way arrays are realized in Java is a reminiscence of lower level languages, as for example C. The role of arrays in Java is not for end-user application programmer but for building of high-level library constructions.

Arrays do not follow Java’s usual semantics, they neither are full objects nor do they have real classes. They do not have a meaningful toString() output. They have a final length field instead of a size() method. They offer no useful methods beside that. You cannot implement your own array classes. And worst, their type system is broken. You can assign an A[] array to a B[] array if B is a subtype of A (called covariance), and thus bad things may happen

Object[] array = new String[10];
array[3] = new Square();

The above code fails at runtime with an ArrayStoreException because you try to store a square in an array of strings. Collections avoid this problem (even though generics aren’t without pitfalls either).

You should not return an array as the value of a public method or property. If an Object returns an array, it exposes its internal state because an array is always mutable. Client can modify the array and thus peek and poke the internal state of your object. This violates encapsulation!

The same problem arises when returning a collection, just here we can do either of two things: return an immutable collection, or (even better) return an iterable. Recall that the caller is requesting values, not variables. And typically even, the caller will just enumerate over the values rather than accessing them by index. Thus the best practice is:

class Folder {
    private List<File> files;
    public Iterable<File> files() {
        return files; // list implements iterable, lucky us
    }
    public int filesCount() {
        return files.size();
    }
}

Method files() returns the files as a stream of values rather than by index. Clients can only enumerate over the values, for example using a for loop, but not modify the underlying collection (ignoring iterator’s unlucky remove method #java #fail). An iterable is a factory for iterables, thus the client can even iterate multiple times over the collection. Basically, we what return is a view on the collection where only its iterator() method is visible. (Of course, they could still cast it to a list, but this is considered very bad style in static typing world).

(parts via Eric Lippert and Reinier Zwitserloot and rssh)

akuhn Java, Patterns, Uncategorized

Fluent Interface

April 16th, 2009

The solution of the Ludo exercise uses a fluent interface to create the board.

Fluent interfaces are a novel way of implementing object oriented APIs, coined by Eric Evans and Martin Fowler. Fluent interfaces use method chaining, ie each method returns the receiver of the next method, which might lead to more readable code than the classic Java Beans convention. Typical use cases of fluent interfaces are builders, such as this class, as well as other internal DSLs. Please use fluent interfaces with care, most classes are best served with a classic Beans API (ie getters and setters).

The following example creates the default Ludo board:

public static List makeBoard() {
    SquareBuilder board = new SquareBuilder();
    for (Color color: Color.values()) board
            .branch(color)
            .squares(5)
            .goal()
            .endOfBranch()
            .squares(2)
            .startHere(color)
            .squares(10);
    board.closeRing();
    return board.getStartSquares();
}

Whereas unit tests use the builder to create dummy board, such as:

@Before
public void makeBoard() {
    board = new SquareBuilder().squares(3)
            .branch(RED).squares(1).goal().endOfBranch()
            .squares(99).getFirst();
    red = board.makeStone(RED);
    green = board.makeStone(GREEN);
}

For more details, please refer to SquareBuilder’s source code.

akuhn Patterns, Readability

Guard Clause and other Implementation Patterns

April 15th, 2009

While programs have a main flow, some situations require deviations from the
main flow. The guard clause is a way to express simple and local exceptional
situations with purely local consequences. Compare the following:

void initialize() {
    if (!isInitialized()) {
        ...
    }
}

with:

void initialize() {
    if (!isInitialized()) return;
    ...
}

When I read the first version, I make a note to look for an else clause while I
am reading the then clause. I mentally put the condition on a stack. All of this is
a distraction while I am reading the body of the then clause. The first two lines
of the second version simply give me a fact to note: the receiver hasn’t been
initialized.

If-then-else expresses alternative, equally important control flows. Guard
clause is appropriate for expressing a different situation, one in which one of
the control flows is more important than the other.

(via Sample chapter of Kent’s book, Implementation Patterns)

akuhn Java, Patterns, Read this!, Readability

No Need for Comments

April 14th, 2009

The comments of a recent blog post by Diomidis Spinellis, sparked an interesting discussion on how to comment your code. Diomidis showed the evolution a comment that documents an if condition in his code. The commenters took the stand that this code should be rewritten such that it documents itself. This is done by introducing variables (or even methods) that are named by what otherwise would be the content of the comment.

For example, instead of

// No edge unless both functions were visited on the same tour
// as indicated by the corresponding bitmasks.
if (!((*call)->get_visited() & fun->second->get_visited()))
        continue;

write

typedef int bitmask;
bitmask function1_visited = (*call)->get_visited();
bitmask function2_visited = fun->second->get_visited();
bool has_edge = function1_visited & function2_visited;
if (!has_edge) continue;

 

“If you feel like commenting, refactor instead!” is also found in in Martin Fowler’s seminal “Refactoring” book, Kent Beck’s “Smalltalk Best Practice Pattern”, and many other books by former C2 wikicitizens. They even go to the extreme that each branch condition shall be put in a method of its own, since boolean logic cannot document the indent but a method name can.

In the above example, we’d best put the whole condition expression into an separate function (which can be inlined by the compiler for better performance). Often, you’ll later stumble upon another site with the same code and thus find that this not only increases readability but also fosters better reuse of your code. If you encounter a big piece of code, keep refactoring it until it turns into an “eventually trivial piece of code” that does not require comments.

The only valid comment are documenting dead ends, ie solution taken in the past that one should not consider again in the future. Since deleted code cannot stand there to document the rational of its removal.

akuhn Patterns

On Testing Getters and Setters

March 24th, 2009

The rule in TDD is “Test everything that could possibly break” Can a getter break? Generally not, so I don’t bother to test it. Besides, the code I do test will certainly call the getter so it will be tested.

My personal rule is that I’ll write a test for any function that makes a decision, or makes more than a trivial calculation. I won’t write a test for i+1, but I probably will for if (i<0)... and definitely will for (-b + Math.sqrt(b*b - 4*a*c))/(2*a).

via stackoverflow.com

akuhn Patterns

Assert that Assertions are Enabled

March 24th, 2009

I have just been told that yet another group failed their exercises due to broken assertions. It is very important that your code makes sure that assertions are turned on! Otherwise it might contain broken assertion of which you are not aware.

Use the following code in your main class.

public class Main {
    static { assert assertionsEnabled(); }
    private static boolean assertionsEnabled() {
        try {
            assert false;
            return false;
        }
        catch(AssertionError ex) {
            return true;
        }
    }
}

And in your tests, use the following test case

public class AssertionsEnabled {
    @Test(expect=AssertionError.class)
    public void areAssertionsEnabledQuestionMark() {
        assert false;
    }
}

PS, if the code does not compile, please report, I just wrote it here in the text editor without running Eclipse.

akuhn Java, Patterns

Why Packages Anyway?

March 24th, 2009

You should use packages to structure your code. (Use of the default package is strongly discouraged.) But, what are packages?

  • First of all, packages are folders on the file system used to structure classes.
  • Each package is a name space. Class names must be unique within one package, but two different packages may contain classes with the same name. (To avoid clashes among package names, it is convection to start them with your domain name, eg ch.unibe.scglectures.p2.)
  • Packages manage visibility of classes and method. For example, while public members are visible from any package, protected members are visibile from the same package only.

Gotcha: Please beware that while folders are nested, packages are not. There is no such thing as a “subpackage”, even if folder scglectures is nested in folder unibe, package ch.unibe.scglectures is not a subpackage of ch.unibe. Thus protected members of the latter package are not visible to the former package!

Which classes belong together? It is hard to give a golden set of rules, as there are conflicting forces as work. You best follow Uncle Bob’s principles.

The first three package principles are about package cohesion, they tell us what to put inside packages:

  • The Release Reuse Equivalency Principle (REP): the granule of reuse is the granule of release.
  • The Common Closure Principle (CCP): classes that change together are packaged together.
  • The Common Reuse Principle (CRP): classes that are used together are packaged together.

The last three principles are about the couplings between packages, and talk about metrics that evaluate the package structure of a system.

  • The Acyclic Dependencies Principle (ADP): the dependency graph of packages must have no cycles.
  • The Stable Dependencies Principle (SDP): depend in the direction of stability.
  • The Stable Abstractions Principle (SAP): abstractness increases with stability.

(via Uncle Bob’s Principles of OO Design)

akuhn Java, Patterns

The Gang of Four Book

March 13th, 2009

design-patterns-book-cover

The book that started it all. The original design patterns catalog. Commonly known as the Gang of Four (GoF) book.

Available here (Univ of Bern access only).

akuhn Patterns, Read this!

Test-driven development is like dual-entry-bookkeeping

March 8th, 2009

Great insight into test-driven development.

TDD is a discipline similar to the discipline of dual-entry-bookkeeping practiced by accountants. It prevents errors in-the-small. Accountants will enter every transaction twice, once as a credit, and once as a debit. If no simple errors were made, then the balance sheet will sum to zero. That zero is a simple spot check that prevents the executives from going to jail. By the same token programmers write unit tests in advance of their code as a simple spot check. In effect they write each bit of code twice; once as a test, and once as production code. If the tests pass, the two bits of code are in agreement. Neither practice protects against larger and more complex errors, but both practices are nonetheless valuable.

via stackoverflow.com by unclebob

NB, you can follow his answers as RSS feed.

 

admin Patterns