Archive for November, 2006

Stealing from the framework

Tuesday, November 28th, 2006

I have written in the past about feeling uneasy when it comes to bringing frameworks into applications without first trying to find a really good reason as to why I should be doing so.

But, OK, being skeptical about something is one thing, blindly denying the possibility of creating less work (oxymoron?) for yourself is totally different and possibly somewhat silly. And code reuse, misunderstood/misapplied or not, is less-work-remedy whichever way you look at it.

Let me explain with an example… A few months ago, my colleague Amit Arora introduced me to Spring’s JdbcTemplate - shame on me for not knowing! I love JdbcTemplate (functional database test setUp and tearDown firewater), like I enjoy many other tiny framework packed marvels out there. My problem is, though, it hurts having to import the whole of Spring Core just to use JdbcTemplate. You wouldn’t buy a car only to use the Stereo, would you?

Now, one solution would be to write the thing myself. This means extra work (bad) and the possibility of me introducing bugs (more work in the future (bad)), while JdbcTemplate has been thoroughly tested release-after-release by the nice Spring folks and the Restless Open Source Community ™.

Since then I’ve been toying with the idea of just grabbing the bits of code that I like (need, even) and shamelessly adding them to the codebase I would be working on at the time. Don’t get me wrong, I’m not trying to steal anyone’s thunder here and I’m making sure respect due is given with copyright stuff carefully packed with the code in question. Not that anybody ever reads those, but anyway…

Situations like this remind me of why I’m not a big fan of full blown frameworks that aim solve all of the worlds problems in the first place. There are always specific bits in there that are useful for specific applications, but the rest ends up being dead weight. I have a thing against dead weight. Others don’t mind it, I do not like the thing.

So, yes, I’m kind of not-a-100%-convinced about the morals behind this type of approach, but I’d rather go with a bit of borrowing rather than importing the whole shebang just for something that should have been part of the Java Core libraries in the first place.

Is that wrong?..

The Testing Anti-Patterns Drafts: Overusing Mocks

Tuesday, November 28th, 2006

There is something problematic about Mocks. They are just too convenient. Developers are lured into employing them all over the place, often forgetting Mocks’ primary function. And that is not the convenience of satisfying the dependencies of the code under test.

Mocks’ main purpose is to test interaction between Objects. This is why Mock verification is performed upon expectations of method calls. One of the golden rules of Unit Testing is testing one thing at a time. In this context, if there is more than one Mock per test case, this rule is probably broken.

public class CustomerServiceTest extends TestCase {

  public void testShouldSaveCustomerDetailsWithRepository() {
    Customer customer = new Customer("Kirk", "Hammet");

    CustomerRepository repository =
        EasyMock.createMock(CustomerRepository.class);
    AuditLog log = EasyMock.createMock(AuditLog.class);

    repository.save(customer);
    log.logCustomerSaved(customer);

    EasyMock.replay(repository);
    EasyMock.replay(log);

    new CustomerService(repository, log).save(customer);

    EasyMock.verify(customer);
    EasyMock.verify(log);
  }

}

Looking at the name of the test, we should be able to safely assume that we expect the CustomerService to use the CustomerRepository for saving a new Customer. Going through the code of the test, it is apparent that we are testing one more scenario apart from the interaction between the CustomerService and the CustomerRepository: We expect the CustomerService to call the logCustomerSaved(customer) method on the AuditLog. In other words, we are also testing the interaction between the CustomerService and the AuditLog.

Let’s imagine that at some point the call to logCustomerSaved(customer) is removed from the actual CustomerService code. This will result to a breaking test telling us that CustomerService Should Save Customer Details With Repository is no longer happening. This is clearly not the case.

There is a sloppy way out of situations like the above and that is stubbing the code that needs to be there in order for the test to run. This can be achieved either by coding a Stub for the AuditLog or by employing the stubbing facilities offered by Mock Object Frameworks, such as EasyMock’s createNiceMock() method. This doesn’t significantly impove readability, neither does it solve the underlying problem which is the usual suspect behind dubious tests: The Application Code is probably not modeled correctly. In the CustomerService case, logging is probably not happening in the right place.

The benefits of code being responsible for performing one task are well documented and apply to both Application and Test Code. Breaking the one mock per test limit usually signifies that this rule is not sufficiently applied.

If you’d like to follow the discussion, feel free to grab The Testing Anti-Patterns Drafts feed.

Is the clutter in your test trying to tell you something?

Tuesday, November 14th, 2006

Tests are often the mirror of application code in terms of elegance and correct distribution of responsibilities. Stuart explains…

If you’d like to follow the discussion, feel free to grab The Testing Anti-Patterns Drafts feed.

Groovy on Jetty on IntelliJ IDEA

Wednesday, November 8th, 2006

I finally got around giving Groovy a relatively serious spin this week. Yeah, yeah, I know… a tad too late.

However, I did have my reasons for Groovy absence all this time. The first one, which pretty much got invalidated as I will soon explain, was: Since there’s Ruby and Ruby already rocks, why bother with Groovy in the first place?. To be honest, I’m pretty content with Ruby and Rails for personal projects, or projects for which I get to choose the development platform. But that, of course, is not always the case.

Then, there’s that name… It still puts me off. If the name of a language should ever be reason enough to vote against it, then Groovy’s the one. Probably too late to change it now, but seriously…

Despite the name aversion silliness, I am very glad I gave Groovy a chance. So far, the prospect of introducing Ruby, or any other non-Enterprise platform, in any of the Corporate environments I usually get to spend my job hours in has been a case of When hell freezes over. As many of us might figure, such decisions are, in the Enterprise arena, often affected by reasons far heavier than a platform’s potency or relevancy.

Enter Groovy. Groovy’s dirty lil’ secret is exactly the fact that it sits directly on top of Java, an Enterprise Certified platform. Also, because of that, it leverages whatever good things come with Java for free. And let’s be fair, there are a few… Because of this all but insignificant detail, Groovy can easily become part of a Programmer’s arsenal without having to put up a fight about its maturity or fit for purpose, since, after all, it is Java.

Groovy can prove itself invaluable in the quest for relief to the somewhat cumbersome Java web tier, and following is a development environment match made in heaven, compared to that of a pure Java approach.

The ingredients: Groovy, Jetty (or Simple) and IntelliJ IDEA.

Jetty and IDEA are two of my all time favorites and the fact that Groovy embraces their use means a very big deal to me. GroovyJ could be more feature rich, but just having some of the power of IDEA at hand combined with the flexibility of a dynamic language can work wonders. I’m not forgetting that all this can very well be possible with the other Java IDEs, I just happen to prefer IDEA.

The project’s directory tree looks something like this:

someproject:
  src:
    java:
      Localhost.java
    test:
      LocalhostTest.java
    webapp:
      SomeGroovlet.groovy
      AnotherGroovler.groovy
      WEB-INF:
        web.xml
  lib:
    antlr-2.7.5.jar
    asm-2.0.jar
    groovy-1.0-jsr-03.jar
    jasper-compiler-4.1.30.jar
    jasper-runtime-4.1.30.jar
    org.mortbay.jetty-4.2.24.jar
    servlet-api-2.3.jar

The contents of lib need to be in the classpath at runtime. Localhost.java is the Jetty server setup and it looks like this:

import org.mortbay.jetty.Server;
import org.mortbay.http.HttpListener;
import org.mortbay.http.SocketListener;

public class Localhost {

  public static void main(String[] args) {
    Server server = null;
    try {
      server = new Server();
      server.addListener(listener());
      server.addWebApplication(”someproject”, “src/webapp”);
      server.start();
    } catch (Exception e) {
      e.printStackTrace();
      if (server != null) {
        try {
          server.stop();
        } catch (InterruptedException ie) {
          ie.printStackTrace();
        }
      }
    }
  }

  private static HttpListener listener() {
    HttpListener listener = new SocketListener();
    listener.setPort(8080);
    return listener;
  }
}

And here’s the web.xml for setting up GroovyServlet, aka support for Groovlets:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

  <display-name>someproject</display-name>

  <servlet>
    <servlet-name>Groovy</servlet-name>
    <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Groovy</servlet-name>
    <url-pattern>*.groovy</url-pattern>
  </servlet-mapping>

</web-app>

Groovlets and Groovy Templates are very powerful, their syntax is sweet and they are recompiled at runtime when changed. This means that I can fire up Localhost once, and keep on developing with instant feedback but without the typical stop server, compile, deploy, start server interruptions that often come with in-container Java development.

I’m pretty sure I haven’t seen half of it yet, but this far Groovy looks like a big, elegant and terribly diplomatic win in all aspects.

Structures in Java

Wednesday, November 1st, 2006

In my mind, there are two basic attributes that characterize Objects: State and Behavior.

Conceptually, an Object with the absence of any of the two is considered perfectly legal in Java, hence, Stateless Objects and what has long now come to be recognized as Java Beans. Java Beans could be seen as Java’s way of creating and representing custom data-types, they’re type definitions with no behavior or any logic attached to them.

I can see how a Stateless Object is still very much an Object. But take away the behavior, and the need for encapsulation becomes unclear.

An Object without behavior should probably not qualify as an Object.

By behavior, I mean any sense of business logic attached to a Class. This could translate to a class having methods, but field accessors do not qualify as such in my book. To cut a long story short, I don’t think Java Beans should be filed under Object, or declared as Classes.

I don’t see the big deal behind a programming language being purely Object Oriented. I think effective programming largely boils down to abstraction, modeling and elegant code and OO is but a means to achieve this.

And something like this:

structure Line {
  int width;
  String color;
}

looks much leaner - and saner - to me than:

class Line {
  private int width;
  private String color;

  public int getHeight() {
    return height;
  }

  public void setHeight(int height) {
    this.height = height;
  }

  public String getColor() {
    return color;
  }

  public void setHeight(String color) {
    this.color = color;
  }
}

Of course, in the absence of a C-like struct keyword, we can always code Java Beans as:

class Line {
  public int width;
  public String color;
}

but what I’m trying to stress here is the distinction between Data Driven and Behavior Driven modeling and that would become much better enforced with the existence of a behavior-less construct.

We’ve always talked about separating data from logic, although that somehow went down the route of XML configurations and property files and there’s nothing wrong with that, but it probably misses a big portion of the bigger picture.