4

Background: I'm working on an application that will manage backup generators. These generators need to be able to be "linked" together. For example, Generator B might serve as a backup for Generator A. If A fails, then the software turns B on. Or they might be linked in a load-sharing configuration, where Generator A and B run together, and share the load.

I'm making a function that will make the link, given 2 generators and the type of link desired.

public void LinkGenerators(Generator A, Generator B, Type linkType);

In writing my tests, I've come with a large number of invalid parameter configurations. My LinkGenerators function looks like this:

public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
     .....
     //Actually make the link after making sure all the arguments are valid.
}

Most of the LinkGenerator functions consists of verifying that the parameters are good. The actual link creation takes 2 lines of code. There's a bit of business logic (verifying that link doesn't already exist and that the generators are not the same) mixed in with a bit functional logic (making sure that the linkType derives from Link, arguments aren't null...), and makes me.......uncomfortable.

Is a long list of parameter checks an anti-pattern or a code smell? And if so, what can one do about it?

(Just to make this clear to close-voters probably misunderstanding the question: this is not a question about "coding style for conditions" like this one).

7

When you need to check conditions that aren't business rules, that's where it gets suspect and a bit smelly. I try to avoid those where possible.

Some of your tests seem suspect:

 if (linkType.BaseType != typeof(Link))

This looks like a check that should be made by the type system. i.e. its a type restriction and ideally your function signature should, as much as possible, only accept parameters of the correct type. How to do that depends on more details of what you are doing.

 if (A.Equals(B) || B.Equals(A))

Why do you feel the need to check it both ways? If A.Equals(B) != B.Equals(A) you are in for a world of hurt.

 if (A == null || B == null || linkType == null)

There is no way to tell which parameter was null from the resulting exception. It's also done after the other checks which means that you probably already caused an exception trying to dereference a null parameter.

I avoid null checks in general. Typically, they aren't that helpful because the code in question will end up throwing an exception after tripping on the null anyways and I haven't gained anything by strewing null checks throughout my code. If you do insist on a null check, I suggest extracting it into a utility function.

  • Good answer, but I would like to add some bits. From the signature of LinkGenerators in the OP's code it is not clear that "linkType" is derived from Link. Maybe the signature is wrong? And null checks (when done one by one, of course) can help to get a better, clearer error message, displaying which parameter was forgotten. – Doc Brown Sep 13 '14 at 7:46
  • @DocBrown, I totally misread the Type in the signature. Thanks for pointing that out. As for null checks, I see pros and cons. Yes, they can get you better error messages. But I also like the flexibility of passing null for parameters that I know won't actually be used in a particular test. On balance, I think they aren't worth the extra code, but I can certainly see that others won't see it the same way. – Winston Ewert Sep 13 '14 at 16:12
  • Null pointers are a painful part of life for most languages, but not checking for them at the right time may not be smart; it would violate the idea of failfast if unlucky. Of course, if the method in question dereferences anyway, they may be spurious. In those case I usually leave a comment though (checked implicitly) otherwise the dereferencing code may be removed later on. – Maarten Bodewes Sep 13 '14 at 20:36
5

I don't think what you've done here is that bad, although it could be moved to a separate procedure to keep things neater:

public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     //simplest way to refactor is to just not catch the exception that's
     // thrown by the validation function.
     validateLinkGeneratorArgs(A, B, linkType);
     .....
     //Actually make the link after making sure all the arguments are valid.
}

private void validateLinkGeneratorArgs(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
 }
  • The only problem with this solution is that the callstack now starts in the validation method, but that's not a major issue. – Magus Sep 12 '14 at 21:42
  • The other problem with this approach is that it's very difficult to pre-validate the things and know what the issue is. Exceptions are maybe not best here. – Telastyn Sep 12 '14 at 23:37
  • The check for null either needs to be relocated (and probably argument specific) or removed as A.Equals(B) will throw on A, B.Equals(A) will throw on B (and what's up with that, checking equality twice?) and linkType.BaseType will throw on linkType. – jmoreno Sep 13 '14 at 17:50
2

Is a long list of parameter checks an anti-pattern?

Literally no. I've never heard of an "anti-pattern" that says lots of parameter checking is a bad thing. Parameter checking implemented as a sequence of if statements isn't an anti-pattern either.

However, that doesn't necessarily mean that what you are doing is right.

Up-front error checking in an API method has pros and cons:

  • On the "pro" side, you pick up problems (programming errors or problems in the "inputs") e*arly. This (typically) makes it easier to diagnose the problems, and before the errors can cause damage (or waste resources).

  • On the "con" side, if the error checking is excessive or in the wrong place, it can be wasteful, or ineffective.

Take this code snippet for example:

 if (A == null || B == null || linkType == null)
 {
    throw new ArgumentException("Cannot pass a null argument");
 }

There are two problems with this:

  • You are doing this too late. If any of those are null, then you will already have triggered an exception.
  • The tests are arguably redundant anyway, since the CLR will already have implicitly tested for null in the earlier parameter checks. And the resulting exceptions are just as effective for diagnostic purposes ... provided that you have source code and a stack trace.

Or this:

 if (A.Equals(B) || B.Equals(A))
 {
    throw new InvalidOperationException("A and B cannot be the same");
 }
  • Does it really matter that A and B are unequal? (Or could this be a harmless error, or possibly even something that is useful?)

  • Is it really necessary to test equality both ways? (Can't you assume that the Equals method has been implemented to be reflexive?)

Finally, there is the larger problem of whether the checks are (too) repetitious. By the sounds of it, they are not in your example. But in general, they could be.


In summary. No anti-pattern, but you still need to think about how much error checking is advisable, and how best to implement it.

0
if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }

should be

checkArgument(linkType.BaseType != typeof(Link),
    "linkType is not a valid link type");

In Java, there's a library with a class Preconditions for this (no idea about c#, but it's easy to write).

This way you get shorter code and it's clean what is what. Incidentally, it can also be faster as the method gets shorter leaving better chances for inlining (at least in the JVM). Hoisting out all checks into one method... maybe.

In general, input validation is good (fail early). For non-public methods consider asserts instead.

Most of the LinkGenerator functions consists of verifying that the parameters are good.

This is a code smell... it seems like you should look for alternatives, how to ensure some conditions so that this method could be simplified. But this is not always possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.