3 ms·
While at it, also don't do if (condition) return true; else return false; Boolean is a perfectly cromulent data type that you can return from a function direct
by ahartmetz 4y ago
While at it, also don't do if (condition) return true; else return false;
Boolean is a perfectly cromulent data type that you can return from a function directly.
- Twisol 4y agoI agree most of the time, but it can make sense in certain contexts. One common example is comparison methods: if (x1 < y1) return true; if (x2 < y2) return true; if (x3 < y3) return true; return false; I wouldn't want to replace the last two lines with `return (x3 < y3)`, even though that's functionally the same thing. In this contrived example, we could just return a single compound condition, but hopefully it's clear that there are cases where doing so would make more of a mess, too.
- wruza 4y agoFor my mind it only works if a meaning of a return value is “compatible” with an expression. E.g. if a function returns a status, but an expression is an integer comparison, the flow of logic skips an important conversion step. bool is_db_open() { return (db != NULL); } bool is_time_to_report() { if (n_errors >= limit) { return true; } return false; // a little confusing way return n_errors >= limit; } Also, if there’s a chance of an additional condition, they can be easily be added and documented. if (n_errors >= limit) { return true; // too many errors } if (now() >= deadline) { return true; // periodic } return false; For the same reason I often do this: if (x == 0) { return 0; // not `x`
- gpderetta 4y agoMany of these seen in the wild are due to workarounding an extremely annoying and useless MSVC performance warning.