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).
0
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.
3
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");
}
}
3
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.
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.