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 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
#1 by pellepim on January 25, 2010 - 15:55
My take on Thoughtworks’ exercise “9 steps” – part 3: Wrap all primitives and strings http://bit.ly/4AMfhL
This comment was originally posted on Twitter
#2 by Abinesh TD on January 27, 2010 - 18:23
Also wrapping discourages misuse of the data. For instance, when you store zip code as int, nothing stops any of your API users from doing meaningless stuffs like adding two zip codes, finding their square roots, etc. On the contrary, a custom object representing zip code expresses intent of the data.
#3 by Jon on January 27, 2010 - 18:36
Wonderful clarification.