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.”

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
   3:    private int rolls[] = new int [21];
   4:    private int currentRoll = 0;
   6:    public void roll(int pins)
   7:    {
   8:        rolls[currentRoll++] = pins;
   9:    }
  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:    .

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?

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
   3:    public void creditToAccount(Account account, double value)
   4:    {
   5:        double balance = account.balance();
   6:        double newBalance = balance + value;
   7:        account.setBalance(newBalance);
   8:    }
  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:    }

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;
   3:public class Account
   5:    private BigDecimal balance;
   6:    private BigDecimal limit;
   8:    public Account(double balance)
   9:    {
  10:        this.balance = new BigDecimal(balance);
  11:    }
  13:    public Account(double amount,
  14:        double limit)
  15:    {
  16:        this(amount);
  17:        this.limit = new BigDecimal(limit);
  18:    }
  20:    public void credit(double value)
  21:    {
  22:        balance = balance.add(new BigDecimal(value));
  23:    }
  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:    }
  34:    public double balance()
  35:    {
  36:        return balance.doubleValue();
  37:    }
  39:    private boolean canWithdraw(double quantity)
  40:    {
  41:        return (balance.doubleValue() + 
  42:                limit.doubleValue() >= quantity)
  43:                ? true
  44:                : false;
  45:    }
  47:    public void setBalance(double balance)
  48:    {
  49:        this.balance = new BigDecimal(balance);
  50:    }
  52:    public double limit()
  53:    {
  54:        return limit.doubleValue();
  55:    }

So, the initial Java code stretch become this one:

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

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”.

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?

Single Responsability Principle

Look at these Java code snippet:

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

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?

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.

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.

Thread Groups

Some months ago I was wondering what was the benefit of using thread groups, which is a container of threads in Java. Reading Bruce Eckel’s Thinking in Java, I discovered this quote from Joshua Block, the one who improved the Collections framework in JDK 1.2:

“Thread groups are best viewed as an unsuccessful experiment, and you may simply ignore their existence.”

I haven’t been told about any Sun’s official statement about this topic before reading the book. So, why do they let us spend our effort trying to figure out the value of thread groups? 🙂