Fail Fast principle

Fail Fast principle

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:
[code language=”csharp”]
public class AgeValidator
{
public Dictionary 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;
}
}
[/code]

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:
[code language=”csharp”]
public class AgeValidator
{
public Dictionary 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];
}
}
[/code]

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.

5 thoughts on “Fail Fast principle

  1. I don’t know… I am not the biggest fan of so much precondition-checking. It just doesn’t fit in C#, since it is not really a language construct.

    The consequence as you realize it (with imperative statements in each method) is a lot of code-noise, that distracts from the real business-value.

    At least the string.IsNullOrEmpty check is superflous in my opinion (1) it is a private method, so only you are calling it. (2) The scond check applies, if you call it with null or empty.

    Also I dont agree that every public method must check that the current object is in a valid state. I agree that it can be sensible/pragmatic in the real world, but I would argue that in theory it is rather an OO antipattern.
    I suspect this stance results from the idea that objects should be the unit of reusability. But in my opinion this has turned out to be rarely the case.
    Concretely in your example, the Validator can only be used in combination with a sensible configuration. I would shift the responibility of providing a sensible configuration to the architecture (IoC) and then rely on sensible testing, to ensure it. This way the Validator itself can be relieved of this responsibility and concentrate on its real responsibility.
    Don’t get me wrong, Fail Fast is extremely important here. But the class should on fail coherently to its responsibility. It should not strive to fail at any possible error, that’s not in its responsibility.

  2. @Jonas
    Thank you for your interesting and differentiated comment.

    Private methods are too often too lazy programmed. One reason what I heard is “I’m the only one who call this private method”. But in reality, this private method will be reused by other methods in this class (and these methods are programmed by other people). So it is very important to use preconditions also in private method to make your code more robust.

    Yes, you could use here the IoC pattern, but you solve not the problem. You could inject an invalid configuration, so it is the responsibility of the validator to check if it make sense to continue or not.

    Where I agree with you is that it increase the noise in the code. This noise is in fact a kind of infrastructure code, but maybe with AOP you could reduce this noise a little bit.

  3. Yup, reusing private methods is one of the reasons for creating private methods. But they should not reused (and rarely are) as black-box, but the code must be understood.
    So precondition checking is in my opinion either over-paranoid or fights a symptom not a cause…

  4. I read a few topics. I respect your work and added blog to favorites.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.