List or List ?

Java 1.5 introduced some new concepts at the Java language level. One of them is Generics, which you can make use mainly when creating type safe collections. This new concept facilitates the programmers’ life: being type safe, errors when working with collections can be caught at compile time (if you have a List<String>in hand, only Strings can be added to this list, neither Integers, Cats or Dogs ) and the programmer doesn’t have to cast when taking out an object of a collection. I was thus wondering whether there is any difference between List<?> and List<Object>. Let’s take a look at the following lines of Java code:

   1:import java.util.ArrayList;
   2:import java.util.List;
   3:
   4:public class Music
   5:{
   6:    abstract class Instrument
   7:    {
   8:    }
   9:
  10:    class Guitar
  11:            extends Instrument
  12:    {
  13:    }
  14:
  15:    class Flute
  16:            extends Instrument
  17:    {
  18:    }
  19:
  20:    class Drums
  21:            extends Instrument
  22:    {
  23:    }
  24:
  25:    public static void main(String [ ] args)
  26:    {
  27:        List<Instrument> instruments =
  28:            new ArrayList<Instrument>();
  29:        List<Guitar> guitars = new ArrayList<Guitar>();
  30:        List<Flute> flutes = new ArrayList<Flute>();
  31:        List<Drums> drums = new ArrayList<Drums>();
  32:        List<Integer> integers = new ArrayList<Integer>();
  33:        List<Object> objects = new ArrayList<Object>();
  34:        check(instruments);
  35:        check(guitars);
  36:        check(flutes);
  37:        check(drums);
  38:        check(integers);
  39:        validate(objects);
  40:        validate(drums);
  41:    }
  42:
  43:    private static void check(List<?> instruments)
  44:    {
  45:    }
  46:
  47:    private static void validate
  48:        (List<Object> instruments)
  49:    {
  50:    }
  51:}

If you try to execute the lines of code, you´ll note:

  • List<?>, which is the wildcard <?> bounded type, also know as List<capture-of ?>, simply means “any type.” That is, it could be a List of <Guitar>, <Flute>,<Drums>, whatever. It also means that you cannot ADD anything to the list referred to as List<?>.
  • List<Object> only accepts Object as an argument. Not Guitars, Drums, Flutes or Integers. If you have a method which the argument specifies List<Object>, this method can only take a List<Object>. The compiler allows you to add to the List<Object>, since you pass an Object as an argument.

So, there are differences between List<?> and List<Object>. The above code doesn´t compile, because an List<Drums> is being passed to a method which has a List<Object> as argument. But if you modify the method to this one:

   1:private static void validate
   2:        (List<? extends Object> instruments)
   3:{
   4:}

The code now compiles!! So, we saw the behavior of List<?> and List<? extends Object> is the same! They both means “I can refer to any type of object”. But neither List<?> nor List<?> nor List<? extends Object> are the same as List<Object>. When you see code using the wildcard notation (?), you can think: “this code refer to many options”. If you try to add something to a List<?>, the compiler won’t let you, because whether it were possible, it would be an unsafe operation, as you could pass a List<Guitar> to a method which receives a List<?> and add, say, a String to the list, as List<?> accepts “any type”. So now you may think: “Ok, Generics is a good feature, I can now create type safe collections and work with them in a safer way at compile time, that’s very good”. But everything isn’t the way we’d want it to be. If you try to mix Java generics code and legacy code,

   1:private static void add(List instruments)
   2:{
   3:    instruments.add("45");
   4:}

and

   1:add(instruments);
   2:add(guitars);
   3:add(flutes);
   4:add(drums);
   5:add(integers);
   6:add(objects);

It compiles!! But let’s deal with it in another post.

Tags:

FastTrack – Free Tracker plugin for Eclipse

FastTrack Logo

For those interested in project management stuff, like issue tracking, team collaboration and other team planning resources, there is a free Eclipse plugin called Tracker, which is intended ( I didn’t have time to test it yet 🙂 ) to manage team development stuff inside Eclipse IDE. It provides, among other things (which I think are the best ones):

  • Issue tracking and planning for Requirements, Tasks, Change Requests, etc. (called “Work ITems”)
  • Linking of Work Items with other artifacts in the Eclipse workspace
  • Search Work Items using the standard Eclipse search facility
  • History of Work Items
  • Comparison of different historical revisions of any Work Item
  • XML data shared via Subversion – no complicated database setup, no administration headaches

If you ever tried this plugin, post your feelings and comments here.

Tags:

About Refactoring

From Objects First With Java’s book: “Refactoring is the activity of restructuring an existing design to maintain a good class design when the application is modified or extended. Doing good refactoring is as much about thinking in a certain mindset as it is about technical skills. While we make changes and extensions to applications, we should regularly question whether an original class design still represents the best solution. As the functionality changes, arguments for or against certain designs change. What was a good design for a simple application might not be good anymore when some extensions are added. Recognizing these changes and actually making the refactoring modifications to the source code usually saves a lot of time and effort in the end. The earlier we clean up our design, the more work we usually save.”

Tags:

Spring 2.0 released

Spring 2.0 has been final released. Here is the news.

Tags:

SRP Example – Bowling Game

Browsing Uncle Bob’s blog, I’ve found this interesting post about teaching TDD with a practical example. It tries to show the principles of TDD while implementing a bowling game. A class diagram showing the mainly concepts of the game is presented. Here it is (click on the thumbnail to see a larger image):

Bowling Game

Some Java code of Game class is show below:

   1:public class Game
   2:{
   3:    private int rolls[] = new int [21];
   4:    private int currentRoll = 0;
   5:
   6:    public void roll(int pins)
   7:    {
   8:        rolls[currentRoll++] = pins;
   9:    }
  10:
  11:    public int score()
  12:    {
  13:        int score = 0;
  14:        int frameIndex = 0;
  15:        for(int frame = 0; frame < 10; frame++) {
  16:            if(isStrike(frameIndex)) {
  17:                score += 10 + strikeBonus(frameIndex);
  18:                frameIndex++;
  19:            }
  20:            else if(isSpare(frameIndex)) {
  21:                score += 10 + spareBonus(frameIndex);
  22:                frameIndex += 2;
  23:            }
  24:            else {
  25:                score += sumOfBallsInFrame(frameIndex);
  26:                frameIndex += 2;
  27:            }
  28:        }
  29:        return score;
  30:    }
  31:    .
  32:    .
  33:}

The Single Responsability Principle (SRP) states “there should never be more than one reason for a class to change”. Analysing carefully the Game class, you can note it has more than one reason to change. So, this class has more than one responsability. One is to keep track of the current frame and the other is to calculate the score. It sometimes is hard to see beacuse it’s difficult to detect a bad class design concerning SRP, because SRP is about implementation, not interface, as I’ve posted before. It’s bad for a class to have two responsabilities, because they become coupled. In the real world this king of coupling doesn’t exist, so in the computational world you can’t create this coupling. If we have to change a client of the BowlingGame class who depends only on the roll() operation and this change causes the BowlingGame class too, we would have to rebuild and retest another client of the BowlingGame class who depends on the score() operation. A better design would separate these responsabilities in different classes or maybe applying Interface Segregation Principle (ISP). I’ve changed a little this class design, ending up doing this (click ont the thumbnail to see a larger image):

Bowling Game

Notice that I have decoupled the clients from the BowlingGame in terms of interfaces. Now, those interfaces provide the clients the services they need, staying far away from the Game implementation.
I think this class design is better beacuse we have decoupled the concepts from each other concerning the whole application, separating in two interfaces. Notice the implementation of the two responsabilities still continues in the BowlingGame
class, but nobody need depend upon this class. Nobody will know it exists. The client who needs to know the bowling game score, will depend on the Scorer interface and another client who wants to register rolls will depend on the RollRegister interface. The implementation is far away from the client. I will change the code concerning this new design and I will post here later. As I’ve told, I think this design is better. Do you have an opinion or suggestion about this?

Tags:

Applying the Law of Demeter

Have you ever been told about the Law of Demeter when developing object-oriented systems? This law states the following:

More formally, the Law of Demeter for functions requires that any method M of an object O may only invoke the methods of the following kinds of objects:

  1. itself
  2. its parameters
  3. any objects it creates/instantiates
  4. its direct component objects

In particular, an object should avoid invoking methods of a member object returned by another method.

Browsing the source code of a project, I found this Java code stretch:

   1:public class AccountHelper
   2:{
   3:    public void creditToAccount(Account account, double value)
   4:    {
   5:        double balance = account.balance();
   6:        double newBalance = balance + value;
   7:        account.setBalance(newBalance);
   8:    }
   9:
  10:    public boolean withdrawFromAccount(Account account,
  11:            double value)
  12:    {
  13:        double balance = account.balance();
  14:        double limit = account.limit();
  15:        double newBalance = balance;
  16:        boolean canWithdraw = false;
  17:        if(balance + limit >= value) {
  18:            newBalance = balance - value;
  19:            canWithdraw = true;
  20:        }
  21:        account.setBalance(newBalance);
  22:        return canWithdraw;
  23:    }
  24:}

This code snippet doesn’t follow demeter’s law. And it’s hiding a responsability that would have been better in the Account class. If the Account knows its balance and limit, why putting the credit and withdraw behavior in a helper class? If we follow the Specialist grasp pattern, the responsability has to be at the class with the specific knowledge. So, I’ve improved the design to this new one Java code:

   1:import java.math.BigDecimal;
   2:
   3:public class Account
   4:{
   5:    private BigDecimal balance;
   6:    private BigDecimal limit;
   7:
   8:    public Account(double balance)
   9:    {
  10:        this.balance = new BigDecimal(balance);
  11:    }
  12:
  13:    public Account(double amount,
  14:        double limit)
  15:    {
  16:        this(amount);
  17:        this.limit = new BigDecimal(limit);
  18:    }
  19:
  20:    public void credit(double value)
  21:    {
  22:        balance = balance.add(new BigDecimal(value));
  23:    }
  24:
  25:    public boolean withdraw(double quantity)
  26:    {
  27:        if(canWithdraw(quantity)) {
  28:            balance.subtract(new BigDecimal(quantity));
  29:            return true;
  30:        }
  31:        return false;
  32:    }
  33:
  34:    public double balance()
  35:    {
  36:        return balance.doubleValue();
  37:    }
  38:
  39:    private boolean canWithdraw(double quantity)
  40:    {
  41:        return (balance.doubleValue() + 
  42:                limit.doubleValue() >= quantity)
  43:                ? true
  44:                : false;
  45:    }
  46:
  47:    public void setBalance(double balance)
  48:    {
  49:        this.balance = new BigDecimal(balance);
  50:    }
  51:
  52:    public double limit()
  53:    {
  54:        return limit.doubleValue();
  55:    }
  56:}

So, the initial Java code stretch become this one:

   1:public class AccountHelper
   2:{
   3:    public void credit(Account account, double value)
   4:    {
   5:        assert account != null;
   6:        account.credit(value);
   7:    }
   8:
   9:    public boolean withdraw(Account account, double value)
  10:    {
  11:        assert account != null;
  12:        return account.withdraw(value);
  13:    }
  14:}

This code above is better because we hide from the clients the Account class internal structure (clients don’t need to know the existence of suborders). Moreover, if the internal structure of account is intended to change, less clients would suffer with those changes (actually, if the Account class changes, only it would have to receive the changes and its clients would have to stay far away from its changes. It’s why Object Oriented design is focused in behavior instead of state). This nice phrase resumes demeter’s law: “The resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers”.

Tags:

Open sourcing Java: good or bad?

Sun announced it will start open sourcing Java by the end of this year, according to eweek. Sun plans to open-source firts the Java C (Java Compiler) and the HotSpot virtual machine, with the bulk of the rest of the code likely to follow in early 2007, including JavaME. Sun hasn’t decided which licence to choose yet, maybe GNU GPL (General PublicLicense) or CDDL (Common Development and Distribution License). What are the benefits of open sourcing Java? What do you think about the compatibility, if we have a lot of distributions of the technology? Nowadays we have this kind of thing with Linux distros, some are incompatible with the others. What’s your opinion about that?

Tags:

Single Responsability Principle

Look at these Java code snippet:

   1:import java.util.Date;
   2:
   3:class Movie
   4:{
   5:    private Date exhibitionDate;
   6:    private Director director;
   7:    private Persister persister = new Persister();
   8:
   9:    public boolean isDirectedBy(String director)
  10:    {
  11:        // some code here;
  12:    }
  13:
  14:    public void changeDateWithDirectorApproval(Date newDate)
  15:    {
  16:        // some code here;
  17:    }
  18:
  19:    public void save()
  20:    {
  21:        persister.save(this);
  22:    }
  23:}

At the save() method, persister takes care of the responsability to update the current movie, saving it at the persistent environment (a file, a DBMS, any data source, etc..) . Some may argue this class has two responsabilities: the Movie is responsible for its own behaviour AND its persistence. ButUncleBob has an interesting opinion about the Single Responsability Principle (SRP). It says Movie actually is not implementing persistence, the persister is a collaborator of the class. The persister is hidden from the client of the class, that is, is not part of the public interface. So, the lose coupling and the encapsulation is preserved. If the persister changes, the clients won’t be affected. It concludes SRP is about implementation, not interface. But imagine if you wanna find a movie, you can’t do movie.find() 🙂 . So, you have to deal with another collaborator who knows how to find a movie. Couldn’t be the Persister? No, because this one is hidden from the clients and if you become it public, you would fail with the information hiding principle. In this case, I think it’s better a Finder object. And you?

Tags:

Interfaces and Abstract classes

My friend bruno started a thread about interfaces and abstract classes and I wanna continue here. I totally agree with his points and I’m adding other ones here. About interfaces:

  1. define a communication “protocol” between classes.
  2. It is, a class which has an interface as a colaborator knows which operations it can send messages for this interface;

  3. isolate the clients from the implementation.
  4. So, you are free to change the internal structure of your implementation and the clients don’t have to concern with this. So, we are applying the hiding mechanism here, known as encapsulation;

  5. clients don’t have to concern with implementation details, because they only work with the interface. The real type doesn’t care for the client;
  6. define the form for a class. More precisely, is what the classes look like while the implementation says how the classes work.

About abstract classes:

  1. describe an incomplete abstraction definition, as interfaces do;
  2. define a common interface for all the subtypes;
  3. establish a basic form, so it’s easy to say what’s in common between the subtypes;
  4. express only a interface, not a particular implementation

Interfaces and abstract classes are ways of managing the internal coupling of your code. You create them when you want to manipulate classes through this common interface. If you only want to factor behavior, interfaces are a good choice, but if you want to factor structure too, choose abstract classes.

Tags:

GRASP patterns

Have you ever been told about GRASP patterns? Those kind of patterns are part of the design discipline of the unified process. Their goal is to assign classes responsabilities around the system. We can say GRASP patterns help objects and theirs collaborators to apply the correct behavior as well. I think the most important GRASP patterns are:

  • Specialist: put the responsability in the class with the specific knowledge. For instance, in a monetary system, as the account has the information of the balance value, the withdraw() method has to be put in this class.
  • Creator: helps deciding who creates the object. If there is an association, aggregation or composition relationships, put in the composed object the responsability to create the other object.
  • High Cohesion: classes have only and exact one responsability around the system. Presentation classes don’t have to know persistence classes. It’s a measure of affinity and overloading responsabilities within classes. For instance, in the same monetary system, the Account class only withdraw() money and not saves this information in a persistence mechanism, a collaborator can do this for the account object.
  • Low coupling: measures classes dependencies within its context. Classes don’t have to be very dependent on its context. For example, if I have to change my database design, I have to change my business objects also.
  • Controller: objects responsible to handle assynchronous event messages originated from GUI. Those can be the use case representation, a system or a subsystem, etcetera… They have the responsability to coordinate tasks and interactions between business objects.

Do you apply GRASP patterns on your software designs? To know more GRASP patterns, checkout this.

Tags: