Posts Tagged software design

Rule 3: Wrap All Primitives and Strings

This is the third part of a series of articles starting here.

Wrapping primitives (ints, floats etc) and strings is an easy way to increase maintainability and readability of your code. Also, as Abinesh TD has commented below, wrapping expresses intent of data, preventing misuse. Consider for example the following pseudo-javacode:

public class Contact {
    private String emailAddress;
 
    public void setEmail(String emailAddress) throws InvalidEmailException {
        if (! validateEmail(emailAddress)) {
            throw new InvalidEmailException("Uhm, that's not a valid mail address...");
        }
 
        this.emailAddress = emailAddress;
    }
 
    public String getEmail() {
        return emailAddress;
    }
 
    private Boolean validateEmail(String emailAddress) {
        // TODO: validation regexp etc
    }
}

A very simple class, containing a single field intended to hold an email address. It looks good enough, but imagine that you have other places where you would need to validate and store email addresses. You would have a tendency for code duplication right there.

Worst case would be that you would have a validation function in every email container class. It would be better to wrap the string intended to hold the email address in its own class, even if it only holds one field, the potential for code reuse increases exponentially.

A better implementation could look like this:

public class Contact {
    private EmailAddress emailAddress;
 
    public void setEmail(EmailAddress emailAddress) {
        this.emailAddress = emailAddress;
    }
 
    public void setEmail(String emailAddress) {
    try {
        this.emailAddress = new EmailAddress(emailAddress);
    } catch (InvalidEmailException e) {
        // Oh lord something went wrong here... :)
    }
 
    public String getEmail() {
        return emailAddress;
    }
}

The benefits should be immediately clear. Suddenly the class EmailAddress requires the email address string to be valid to be instantiated at all. This would make it much easier to quickly zero in on bugs and also increases the potential reuse of your code.

Pretty much any variable you want to store, whether it is a primitive or a string – WILL need some sort of validation. This is a major reason for wrapping them. But other than that, consistently wrapping gives your object oriented code a higher degree of encapsulation.

Previous « Rule 2: Don’t Use the Else Keyword
Next » Rule 4: Only Use One Dot Per Line

,

5 Comments

Rule 2: Don’t Use the Else Keyword

This is the second part of a series of articles starting here.

The second rule of the “Nine Ways to Better Software Today” is to stop using

else

This builds on top of rule 1, to decrease the level on indentation by again focusing on minimizing complex conditionals. Within the object oriented paradigm, polymorphism is a powerful model to handle this. Regardless of programming model,  this exercise forces you as developer to find alternatives to using the else keyword and thus considerably beautifying your code.

Consider the following Python code

def set_member_status(member, status):
    """ Spot the else keyword """
 
    if is_active(member):
        do_something(member, status)
    else:
        do_something_else(member, status)

There are several ways to simplify this method. For simple cases use early returns, as below. Early returns only work in methods which are short and lacking in complexity (keeping down the level of indentation helps with this). Once a method is long and contains many levels of abstraction, early returns can of course not be used. But by then you’ve failed at this exercise anyway.

def set_member_status(member, status):
    """ Example of using early returns """
 
    if is_active(member):
        do_something(member, status)
        return # here is the early return :)
 
    do_something_else(member, status)

In many languages it is possible to use the ternary operator. That would look something like this (in javascript):

/** Wrong */
function drowned() {
  if (timeInWater < SURVIVABLE_TIME) {
    return false;
  } else {
    return true;
  }
}
 
/** Right */
function drowned() {
   return timeInWater < 10 ? false : true;
}

Guard clauses is another way of increasing readability. The following example is taken from here

double getPayAmount() {
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetired) result = retiredAmount();
	    else result = normalPayAmount();
        };
    }
    return result;
};	
 
double getPayAmount() {
	if (_isDead) return deadAmount();
	if (_isSeparated) return separatedAmount();
	if (_isRetired) return retiredAmount();
	return normalPayAmount();
};

Previous « Rule 1: Only Use One Level of Indentation
Next » Rule 3: Wrap All Primitives and Strings

,

10 Comments

Nine Steps to Better Software Design Today: Thoughtworks Exercise

There are few companies out there more exiting to me than Thoughtworks. They sport a fantastic set of values, and have some of todays most brilliant programmers and software thinkers on board. But what strikes me as most wonderful about them is the way they communicate with programmers around the world. They really have an interest in good software, whether it is their own, or somebody else’s.

On reading their book, the Thoughtworks Anthology there was one chapter (Object Calisthenics by Jeff Bay) which struck me as extremely fun to read, it contained an exercise called “Nine Steps to Better Software Design Today”. An exercise completely focused on object oriented design quality with all that that entails, like encapsulation and appropriate use of polymorphism.

It is really a very simple exercise in many aspects, it simply provides nine rules, and asks me as a developer to do my absolute best to abide by those rules. What Thoughtworks does is so ingenious. Instead of just preaching the holy grail of object oriented programming, they ask me to be a part of the sermon. On reading the whole exercise I was instantly revving my engine to actually do the exercise. So I started up a small GWT project and forced myself to actually try and comply with the nine rules.

I’ve never had so much fun programming! And the process truly changed the way I will write code from now, whether it is in a purely object oriented language or not.

Said and done. I will start with the first rule:

Rule 1 : Use only one level of indentation per method

No matter which language you are working with, this is something that is very important. Check out the class, that thoughtworks uses as an example, below. It contains one function with several levels of indentation.

class Board {
  String board() {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++)
        buf.append(data[i][j]);
      buf.append("\n");
    }
    return buf.toString();
  }
}

Now consider that after some refactoring the code could look like this:

class Board {
 String board() {
  StringBuffer buf = new StringBuffer();
  collectRows(buf);
  return buf.toString();
 }
 
 void collectRows(StringBuffer buf) {
  for (int i = 0; i < 10; i++)
   collectRow(buf, i);
 }
 
 void collectRow(StringBuffer buf, int row) {
  for (int i = 0; i < 10; i++)
   buf.append(data[row][i]);
  buf.append("\n");
 }
}

What basically has happened here is that methods have been extracted for each level of indentation. The whole class is so much more readable, unit testable, understandable… you name it. Or as the authors of the chapter puts it:

Try to ensure that each method does exactly one thing. One control structure, or one block of statements per method. [Heavy indentation] in a method [is] a signal that you’re working at multiple level of abstraction, and that means you’re doing more than one thing.

Working with methods that do exactly one thing, and classes doing exactly one thing, your code begins to change, [...] increasing exponentially the level of reuse.

Next time I will talk about rule 2: Don’t use the else keyword :)

,

5 Comments