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

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

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

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

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

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

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

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật