|
|
|
|
|
by robotresearcher
1117 days ago
|
|
That’s what the ‘is’ is for. If you have a ‘?’ character, you don’t need it. But tastes vary. I don’t even like the ‘is’. 1. if isValid()
2. if valid?()
3. if isValid?()
4. if valid() Number 4 is nicest to my eyes. But I guess if the ‘?’ or ‘is’ (or both) is a promise to the user that the function is a true predicate, then I can see its utility. |
|
If I saw something like this while reading code, I'd pause and carefully check what exactly is going on here.
In fact, I was going to write "Option 2) resembles resource management patterns, for example memory management in C", but then I checked and noticed that free() in C does not return a value, so this pattern would not exist with malloc()/free() - in other words, despite doing a bit of C and a lot of C++ in the past two decades, I still tripped over this.
Now compare with:
Both resolve this ambiguity.On that note, I'd love some kind of sigil for "asserting" functions - which are similar to checks, but instead of returning true/false, they ensure the argument is in the state described by the function name, or else they throw an exception. It's a pattern I've been using in exception-ful code to cut down on noise. For example:
It's not a big deal, but in some cases, that "Ensure" or "Assert" look weird, and I don't like inventing more synonyms for the same pattern.