My function takes an optional parameter, type, which is used to filter through a collection. However, the filter should only apply if the parameter is passed in (in other words, non-null). If the filter is not passed in, it should not be applied. How can I write my logic to reflect this? What I have now is -

if( other conditions && ( Type == null || (Type != null && Order.Type == Type ) ) )
    return val += Order;

But this feels clunky and wrong. Is there a way I can simplify my logic here?

有帮助吗?

解决方案

The OP has stated in a comment that the language used has short-circuiting Boolean operators, so this could be written as:

if( other conditions && ( Type == null || Order.Type == Type ) )
    return val += Order;

其他提示

It's often cleaner to avoid the null altogether by creating two functions: one with the filter and one without. The former can call the latter, like:

if (Order.Type == Type)
  return nonFilterFunction(...)

This style follows the Single Responsibility Principle by having one function do only filtering and one function doing the other stuff. It allows the compiler and runtime assertions to help you out in verifying programmers are using your code correctly. It's also easier to reason about because in one function you don't have to worry about Type at all, and in the other one, you can assume or assert that Type is never null and not have to worry about it afterward.

The main drawback is one extra function in your API. Also, this style is difficult if you have a lot of optional parameters, because you couldn't create a new function for every combination, but there are usually other ways to handle that situation.

许可以下: CC-BY-SA归因
scroll top