Archive

Author Archive

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

The McCabe Challenge

March 7th, 2009

Each week, I will post a hacker’s challenge.

 

Keep it Simple Stupid!

“Keep it Simple Stupid!”

Cyclomatic complexity of zero*), can it be done?

 

Implement a linked queue in Java, such that

  • there are no if statements,
  • and no method is longer than one line.

The queue must implement the following interface

interface IQueue {
    boolean isEmpty();
    int size();
    void add(Object item); //append item
    Object top(); //return first item, assert if empty
    void remove(); //remove first item, assert if empty
}

The queue must be implemented using a linked list. All boundary conditions must hold (that is, both #remove and #top must throw an AssertionError on an empty queue). The mutation operations #add and #remove must run in O(1), that is constant, time . The implementation must not use any conditional statements, neither ordinary nor trinary if-statements. The implementation must not use or call any API. All methods/initializers of the implementation must be written in one line. The source code must be in Ctrl+Shift+F format! This includes that lines must not be longer than 80 characters (those darn teleprinters, you know).

*) In the mean time, I learned that the minimal McCabe complexity is 1, but whatever, I’ll just leave it like that, zero sounds more daring.

 

Please address submissions to .

Download as PDF.

Have fun!

admin Hack

JExample, more than just Tests

March 6th, 2009

JExample helps you to reuse fixtures and to pinpoint failures. It extends Junit with producer-consumer relationships. A producer is a test method that yields its unit under test as return value. A consumer is a test method that depends on one or more producers and their return values.

  • Pinpoint failures – JExample skips any test method whose producer has failed.
  • Reuse fixtures – the return value of a producer is injected into its consumers.

You can find a tutorial here: JExample Quickstart.

@RunWith(JExample.class)
public class StackTest {

  @Test
  public Stack emptyStack() {
    Stack stack = new Stack();
    assertTrue(stack.isEmpty());
    assertEquals(0, stack.size());
    return stack;
  }

  @Test
  @Given("#emptyStack")
  public Stack testPush(Stack stack) {
    stack.push("foo");
    assertEquals("foo", stack.peek());
    assertEquals(1, stack.size());
    return stack;
  }

  @Test
  @Given("#testPush")
  public void testPop(Stack stack) {
    Object top = stack.pop();
    assertEquals("foo", top);
    assertEquals(0, stack.size());
  }

}

JExample is open source, go get it!

Follow me.

admin Tools

Test Coverage

March 6th, 2009

Programmers love writing tests. If you have a progress-o-meter, writing tests is even more fun. Code coverage tools report how much and which parts of your code are covered by tests.

Eclemma is a coverage tool for Eclipse. You can run both your application or your test cases with Eclemma, and get a coverage report.

Eclemma screenshot.

Eclemma is open source. Go get it!

admin Eclipse, Tools

Hello, 2009!

March 6th, 2009

Welcome to the Panopticon.

This blog will provide a constant stream of resources, pointers and side-notes related to the Programming II lecture. As the name of the blog indicates, articles will cover a broader spectrum than just the very subject of the lecture. Please use the categories on the right to browse posts by topics.

Below you find two of the shortest hello worlds for Java

enum H{W;{System.out.print("Hello, worlds!");}}
class S{static{System.out.print("Hello, worlds!");}}

The are not as short as a hello in the HQ9+ language, but they are as short as one might get in Java. I will leave it up to you to unravel the language features that are being abused in these hellos.

More hellos can be found in the initial post of my personal blog.

cheers,
AA

admin P2

Java Job Trends

May 23rd, 2008

Over at manageability, there is an article about trends in java job ads. This is even more interesting than my recent google trend searches. The blog post shows many disruptive trends, for example, how both Hiberante and Spring are killing EJB.

Hibernate / Spring vs EJB

This is a good thing to happen. EJB was the most broken framework I have ever seen (and was actually the reason why I left industry and came back to academia). If you want to know how broken EJB really was, just consider that after its introduction even POJO became a buzz word. POJO stands for no less than “Plain old Java object”!

(via Manageability)

admin Java

The Good, the bad, the ugly

May 8th, 2008

The Google Singleton Detector can be used on your code base to detect things matching a classic singleton pattern and also some more subtle singleton variants which they call hingeltons, fingletons, and mingletons.

(via Pure Danger Tech)

admin Java, Patterns, Tools

Controlling Visibility – Part 2

May 8th, 2008

Today, we continue our series on controlling visibility in Java. As I told you before, there are two ways to controll visibility: at the level of classes or at the level of packages.

At class level, controlling visibility is done as given in the previous post. We use the modifiers private, protected or public to set the visibility of class members. Class members are fields, methods and inner classes. This give us very fine-grained control, which can be a good and a bad thing.

Sometimes, controlling visibility at class level becomes pain-stacking micromanagement and we wish we could just turn everything public. This is where package level visibility joins the game.

At package level, controlling visibility is done completely different. Let A, B, C be packages of layer Below and X be a package of layer Above. How do we controll the visibility of classes and methods in Below such that Above can not see them?

The solution is to introduce yet another package and use interfaces.

We create interfaces for all to-be-public classes and methods and put them in a new package D, together with a Facade (185) that is an Abstract Factory (87) and a Layer Singeltion (127). The responsability of the facade is to serve as factory for the interfaces defined in D.

Now, we define that code from Above must not (darf nicht, des englische “must not” kann für Deutschsprecher verwirrend sein) directly import members of A, B or C. Rather, all access from Above to Below must be done using package D only.

That way, we get complete controll over the visibility of Below.

Let me give a quick example, where classes A.Below and X.Client are given as follows

package A; // belongs to layer Below
public class Foo {
    public void useMe() {  };
    public void doNotUseMe() {  };
    public Foo self() { return this };
}

package X; // belongs to layer Above
public class Client {
    public void main(String[] argv) {
        A.Foo foo = new A.Foo();
        foo.useMe();
        // architecture violation, but no compile error!
        foo.doNotUseMe();
    }
}

The method A.Foo.doNotUseMe() is supposed to be private to layer Below, but with the present settings we can call it nevertheless. Given that we can not make the method private because of internal uses by packages A, B and C, we must resort to the architecture level to controll its visibility. Therefore, we introduce a new package D as follows

package D; // belongs to layer Below
public interface IFoo {
    public void useMe();
    public IFoo self();
}
public class BelowFactory {
    public IFoo createFoo() {
        return new A.Foo();
    }
}

Now, we can rewrite our client and A.Foo.doNotUseMe() is really hidden!

package X; // belongs to layer Above
public class Client {
    public void main(String[] argv) {
        D.BelowFactory factory = new D.BelowFactory();
        D.IFoo foo = factory.createFoo();
        foo.useMe();
        // architecture violation AND compile error!
        // foo.doNotUseMe();
    }
}

An important issue are return types. To demonstrate that, the Method A.Foo.self() has been included in the example. As you can see, the interface specifies its return type as D.IFoo whereas the implementations returns A.Foo. That is, the return type of the overridding method is more specific than the overriden method. This is call co-variance.

It is very important to use co-variance whenever a method has an internal return type! Without co-variance we could write in the client the following, and thus violate the architecture.

    foo.self().doNotUseMe(); // architecure violation

With co-variance, this does not compile.

A final word regarding naming conventions. Architectural visibility splits each class in two files: a public interface and its internal implementation … and both can not have the same name. Given a class Example, the most common naming conventions are

  • interface IExample and implementation Example
  • interface Example and implementation ExampleImpl
  • interface Example and implementation MyExample
  • interface Example and implementation AbbrExample, where Abbr is the abbreviation of the layer’s name

Please keep in mind that, given such a small example as above, the forces present in a huge architecure are not present and the propose solution may look unnecessary complex. Thus, you must just believe me that it is indeed a very common case that you want to controll visbility with a mechanism other than method modifiers. You will see yourself when you work for the first on a system with 1000 classes or more.

admin Java

Controlling Visibility – Part 1

May 5th, 2008

There is two ways to control visibility in Java. But let us first discuss why visibility matters. Why do we restrict the visibility and thus accessibility of certain fields, methods and classes? The most common misconception is that visibility is about security. That is so wrong! But I have even meet professionals that thought using the private keyword is a way to protected your code against malicous attacks. Calling a private method is as easy as

public static void main(String[] args) throws Exception {
    String string = "Secret.";
    for (Field each : String.class.getDeclaredFields()) {
         each.setAccessible(true);
         System.out.printf("%s = %sn", each, each.get(string));
    }
}

How does this work? Visibility is only checked at compile time, that is, the compiler throws an error if a private method is called. But at runtime, a private method is as any other method, out there in bytecode and ready to be called by whom ever is calling them. Using reflection (you recall, programs thinking about themselves might some day turn into wintermute) we can call any method, even private ones.

Of course, that should not be done without good reason—actually there is no such good reason as we will soon see. Except maybe, when writing an infrastructural library such as the recent serialize/deserialize exercise.

So, if not for security, why do we use visbility then?

You know the answer, it is to be fit for software evolution. To embrace change. By keeping certain parts of our implementation private (or rather protected, in most cases) we reserve us the ability to change them later without afflicting existing code. The goal here is, once again, to keep the number of dependencies between objects or components as minimal and local as possible.

A private method can only be called by the class itself (in Java, private means class-private not instance-private as eg in Smalltalk). Depedencies to a private method can only be introduced in the same class and thus remain local and minimal.

A protected method can only be called from within the same package or by subclasses of the class. Again, the scope of dependencies is limited.

A public method can be called from everywhere, and is thus likely to introduce global and wide spread depedencies. This is bad.

That much about design and class level. I will talk about the package level in a follow up, stay tuned.

admin Java

Meet the Pros

May 5th, 2008

Jazoon, one of the world leading Java conferences takes place in Zurich. Jazoon is Europe’s leading Java conference, and as such, is most probably world’s second most important Java conference beside JavaOne. There will be technical talks about current technologies and latest trends in Java. I can only recommend to visit such a conference as a student, you will learn there stuff that goes beyond what we can teach you in the classroom.

The conference takes place fom June 23–26 in Zurich, and the best is—full registration is almost free for students, 48 CHF only.

Participants must be over 18 and for qualifying for the Student Special rate not older than 24 (on 24 June 2008). To qualify for the student registration fee, students must present proof of fulltime enrolment at a recognized university or college at both the time of registration and during the conference. Please contact the Jazoon registration department at students@jazoon.com to request a student voucher. A copy of your student ID must be attached to the email. Students must present their original student ID on-site in order to receive their conference badge and keep it available during all times at the conference. The registration fee for students includes entry to all conference sessions, access to the exhibition area, the opening and the closing sessions and the Jazoon After Hours networking events. During the conference, food & beverages are included (coffee breaks and lunches).

Go ahead, take your chance!

admin Uncategorized