所以我只是遇到了一些看起来像这样的代码:
checkCalculationPeriodFrequency("7D", "7D", SHOULD_MATCH);
Run Code Online (Sandbox Code Playgroud)
和
checkCalculationPeriodFrequency("7D", "8D", SHOULD_NOT_MATCH);
Run Code Online (Sandbox Code Playgroud)
让我们不必担心代码现在(或什至永远)会做什么,而不必担心最后一个参数-SHOULD_MATCH和SHOULD_NOT_MATCH
这是我以前想到的,但是认为可能做起来“不好”(因为“坏”在后现代世界中具有任何实际含义)。
上面,声明了这些值(您可能已经假设过):
private boolean SHOULD_MATCH = true;
private boolean SHOULD_NOT_MATCH = false;
Run Code Online (Sandbox Code Playgroud)
I can't recall reading about "naming" the boolean parameter passed to a method call to ease readability, but it certainly makes sense (for readability, but then, it also hides what the value is, if only a teeny bit). Is this a style thing that others have found is instagram or like, soooo facebook?
Naming the argument would help with readability, especially when the alternative is usually something like
checkCalculationFrequency("7D",
"8D",
true /* should match */);
Run Code Online (Sandbox Code Playgroud)
which is ugly. Having context-specific constants could be a solution to this.
I would actually go a step further and redefine the function prototype to accept an enum instead:
enum MatchType {
ShouldMatch,
ShouldNotMatch
};
void checkCalculationFrequency(string a, string b, MatchType match);
Run Code Online (Sandbox Code Playgroud)
I would prefer this over a boolean, because it gives you flexibility to extend the function to accept other MatchTypes later.