4 ms·
I find it interesting that a few of the patterns showed here can (should) be prevented by the compiler Pattern: A < B, B > A Can be prevented by using a compa
by berdario 9y ago
I find it interesting that a few of the patterns showed here can (should) be prevented by the compiler
Pattern: A < B, B > A
Can be prevented by using a compare/compareTo function. Even better if the data type returned by it is not an Int, but rather an enumeration/sum of LessThan | Equal | GreatherThan (which is pretty common in ML-family languages).
Such a data type will automatically give you warnings if you forget one of the comparison cases (or if you mistakenly go over the same case multiple times)
Pattern: a Member of the Class is Compared with itself
All of the examples are about writing a definition of compare/compareTo for the specific class.
This can be prevented by having the compiler automatically generating the implementation, as in Haskell:
https://www.haskell.org/onlinereport/derived.html https://www.haskell.org/onlinereport/derived.html
Pattern: Incorrect Check of Null References
This is handled by the usual Maybe/Optional types
Pattern: Incorrect Loops
This is quite interesting, I think it's fine to have a `,` operator that ignores the result on the left. What is not fine is to have such an operator for a side-effects-free context. Or, put another way, C-style `for` loops are too clever for their own good. If a for loop syntax is:
for( initialization; test; mutation)
obviously you want to have some sort of side effect for `initialization` and `mutation`. But most often you don't want/can do without side effects for the `test`, and disallowing `,` in tests would prevent these issues.
Similarly, for while loops, even if it's a common idiom/shortcut to have `++value` or `--value` in the test expression, it's not without shortcomings.
Ultimately, a for-each loop, (or better, a map) is less error-prone. That would also prevent the other issues listed under the same pattern (in which an unsigned int had been used for a decreasing counter).
Pattern: Sloppy Copying of the Code
The Compiler::RefCntCmp example ought to be prevented by factoring out more the code into reusable functions.
MySql's rr_cmp unfortunately is an example of, even when your tool has safer way to do things, you might miss out, in the (often misguided?) attempt to optimize it further.
Just like your code might not use the appropriate data types, and thus be unable to rely on safety guarantees provided by the compiler. Plenty of projects don't use static analyzers, and thus miss out on all the checks mentioned in the article.
I'd avoid writing new projects in C family languages, but given that there's plenty of code written in those languages already out there, I'm glad that tools like the one described in the article exist.