Archive

Archive for September, 2009

Fail Fast principle

September 22nd, 2009 5 comments

Recently I received a NullReference-Exception when I called another method from a foreign component. Fortunately I had the source code of this component and I found the following code:

public class AgeValidator
{
	public Dictionary<string, int> Config { get; set; }

	public bool Validate(int nAge)
	{
		int nMinAge = FindValue("MinAge");

		return nAge > nMinAge;
	}

	private int FindValue(string strParameter)
	{
		int nValue = -1;

		if(this.Config.ContainsKey(strParameter)) nValue = this.Config[strParameter];

		return nValue;
	}
}

There are several problems with this code. First, there are no preconditions which checks if the object is in a valid state or the parameters are valid. This cause to behaviour which isn’t intended. The problem with a not available configuration could already detect in the Validate method. The Find method could check if the parameter is valid, if not it doesn’t make any sense to continue. The FindValue method doesn’t follow the Fail Fast principle. Jim Shore wrote an excellent article about the Fail Fast principle. After a refactoring the code looks like that:

public class AgeValidator
{
	public Dictionary<string, int> Config { get; set; }

	public bool Validate(int nAge)
	{
		if(this.Config == null || this.Config.Keys.Count == 0) throw new InvalidOperationException("No valid configuration available.");
			
		int nMinAge = FindValue("MinAge");

		return nAge > nMinAge;
	}

	private int FindValue(string strParameter)
	{
		if(string.IsNullOrEmpty(strParameter)) throw new ArgumentNullException("strParameter");
		if(!this.Config.ContainsKey(strParameter)) throw new ArgumentException(string.Format("No configuration for the key '{0}' found.", strParameter));

		return this.Config[strParameter];
	}
}

What I advise junior software developers is to follow the Fail Fast principle, disciplined use of preconditions and if it adequate the use of postconditions. But all these advices don’t replacing unit testing.

Share

To be a model

September 9th, 2009 No comments

Currently I study for a MAS-IT. Last semester came a photograph and asked if he could take some pictures. So I thought nothing of it and I continued discussing with my colleagues about a topic.
Today I saw on the page of the Berner Fachhochschule, Technik und Informatik two images with me:
bfh1
And here:
bfh2
That’s funny. Normally I describe models, but now I’m the model.

Share
Categories: Private, Software engineering Tags: