4 ms·
It's my rule of thumb that the only numbers one should find in code are 0 and 1. Anything else is a magic number and needs to be handled accordingly.
by 2-718-281-828 4y ago
It's my rule of thumb that the only numbers one should find in code are 0 and 1. Anything else is a magic number and needs to be handled accordingly.
- xigoi 4y agodef solve_quadratic_equation(a, b, c): d = b * b - 4 * a * c if d >= 0: return [(-b + sqrt(d)) / (2 * a), (-b - sqrt(d)) / (2 * a)] else: return [] How would you deal with the “magic numbers” here?
- 2-718-281-828 4y agogood question. but if you look at the "magic" concept from a higher level then you'll find that this function of course is based on magic numbers as it itself is a _magic function_. it doesn't solve generally equations but specifically _quadratic_ equations. a more extreme and obvious example in the same vain would be: def print_every_second_for_a_minute(): ... having said that - there are always exceptions.
- xigoi 4y agoHow would you define a “magic function”? Solving equations in general is not possible, so if you're trying to say that this function is too specific, good luck generalizing it.
- 2-718-281-828 4y agoI talk about magic numbers from an abstract, theoretical perspective. from that perspective it's not relevant that you can't generalize an equation solver. but would bet that if it was possible then there would be no numbers except for 0 and 1. --- you could also think of it this way. a generalized equation solver would necessarily derive the solution in a complete fashion. for someone analyzing the code it would be come clear what's going on. your specialized equation solver otoh just has some "magical" solution in there.