3 ms·
Enumerations or other constants are helpful but generally only if the type has any other use besides a single function call (e.g. is it a type that you'd want t
by makecheck 14y ago
Enumerations or other constants are helpful but generally only if the type has any other use besides a single function call (e.g. is it a type that you'd want to store as a field in a structure somewhere, or would it be useful in 2 or 3 other routines?). They should also be absolutely unique types (using whatever scheme in the language would guarantee that) to avoid bugs.
An approach that is usually better is to rename the entire function, creating two functions. To extend the article's example, this would mean having both "widget->repaintImmediately()" and "widget->repaintLater()" (or whatever). This can even be implemented by having both of the public routines call a single internal routine that is still parameterized.
When the function names are different, everything you need is in one place; you don't have to waste time figuring out where the corresponding list of allowed values is defined. Unique functions may also require less error-handling if only some values are allowed; e.g. if the type would include "A, B, C" and a parameterized function wouldn't accept "C", it's easier to define only funcA() and funcB() and just not have funcC(). Conversely, if you some day realize you actually have more cases than you originally thought, adding a funcD() is trivial and that decision doesn't affect anything else.
An example of constant-parameter bugs: it's common to see someone define several unrelated values that are effectively all "const int" or strings, which allows values to be misused without warning (especially if they're named similarly). In Cocoa, NSFontAttributeName and NSFontNameAttribute have the same type but different uses; while this isn't a true/false case it shows how easy it is for something to be wrong and how important a unique type can be for debugging.