3 ms·
Consider the following two function definitions: int add(int a, int b) { return a + b; } int add(int a, int b) { if ((a >
by torstenvl 4y ago
Consider the following two function definitions:
int add(int a, int b) {
return a + b;
}
int add(int a, int b) {
if ((a > 0 && b > 0) && (INT_MAX - a < b)) {
return INT_MIN + (b - (INT_MAX - a + 1));
} else if ((a < 0 && b < 0) && (INT_MIN - a > b)) {
return INT_MAX + (b - (INT_MIN - a - 1));
} else {
return a + b;
}
}
Which one expresses the intent more simply and understandably?
Which one is more robust?
Which one would you bet the future of your company on?
I offer that, sometimes, simplicity of expression is at odds with protection against edge cases.
- deanmen 4y agoWhy not int add(int a, int b) { unsigned res = (unsigned) a + (unsigned) b; return (int) res; }
- torstenvl 4y ago"When a value with integer type is converted to another integer type ... [if] the new type is signed and the value cannot be represented in it; the result is implementation-defined." C99, 6.3.1.3. "When a value with integer type is converted to another integer type ... [if] the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised." C23 Draft, 6.3.1.3. Calling add(2147483647, 2147483647) with your code could trap, not from the overflow (which is well-defined for unsigned integers) but from casting 4294967294 to a signed integer. I also don't know if it would work with one's complement.
- kemitchell 4y agoDon't let lawyers confuse form and substance as cover. It's perfectly possible to address more possibilities in simple language. The result might run longer, but it won't hurt to read. Too many companies run on legal docs execs don't read. Too may lawyers write those docs to put readers off. If you want robust legal work for your company, maximize accountability for your legal advisers. All the usual tools.
- torstenvl 4y agoSure. Key word is "sometimes." I'm definitely in favor of simpler language when possible, and I think we once spoke about my minimalist ISC variant license. But... we as a profession are still doing way better than past generations and their English/Middle French/Latin code-switching, talking about beasts feræ naturæ like poor reynard, with his depredations on farmers and on barn yards.
- zaphar 4y agoYour second function does more work and covers more cases certainly but could also be written less confusingly to indicate the intent. If I encountered your second function in a code review I would at a minimum be asking you to add comments to clarify to the reader what is happening. When the article talks about bad writing they aren't suggesting that "simpler" is better. They are suggesting that "clarity" is better. By all means cover the edge cases but don't construct the legal language so it looks obfuscated INTERCAL.