comments (not for humans)

As programmers we often pick the easy way out, even though we often hear that we should keep things simple. Creating something simple can be hard, and creating something complex (and often buggy) is easy.

One example of picking the easy way out and being lazy, is passing strings around as parameters to functions (and thus creating anemic object models). An example of this could be the following method:

public bool ValidatePassword(String email, String password){...}

If we look at this closely, we notice that this API is very permissive. While almost any string can be a password, this is definitely not true for email. In fact most strings are not valid email adresses. But the way this is setup right now, and basically every other place this value is used, we are accepting a lot more than we are expecting. And if we wanted to validate this input where it is used, we might have to add something like EmailValidator.Validate(email) in a lot of different places in our code.

A better approach could be to build a less permissibe and more explicit API like this:

public bool ValidatePassword(EmailAddress email, String password){...}

We have now changed the type of the email to be EmailAddress. If we now build the EmailAddress class in such a way as though the constructor validates any incoming string, and throws an exception on invalid input, we only have to validate the value of the email address in one location:

public class EmailAdreess {
private String
_email;
public
EmailAddress(String email) {
EmailValidator.Validate(email);
_email = email;
}
...
}

This allows us to use the email address everywhere without caring about validation (except null checks), because each instance of EmailAddress is a valid email.

Next, we should also change the password. We probably have as set of rules defining a valid password (more than 8 characters, must contain both letters and numbers etc.):

public bool ValidatePassword(EmailAddress email, Password password){...}

And then we build the Password class in a similar way as we did for EmailAddress.

We might also want to provide some static helper methods to allow other developers to validate an email address or a password with knowing about the validator classes or doing exception based flow control:

public class EmailAdreess {
...
public static bool
IsValid(String email){...}
...
}

We could even move the contents of the validator method into our class, to keep the validation together with the actual object.

Other resources
Dan Bergh Johnsson from OWASP AppSec Research 2010
gene
I think you mean password in this sentence:
[i]Next, we should also change the password. We probably have as set of rules defining a valid email (more than 8 characters, must contain both letters and numbers etc.):[/i]
Erlend
@gene: Yes, thanks. Fixed
Comments closed for this post