by mattkrause · 6y ago · 0 comments
In some cases, I'd say that 1 can be a magic number. For example, it would better to write
fprintf(STDOUT, output_string)
than fprintf(1, output_string)
However, 0 and ±1 have a special role in picking out the first/next/previous elements of a sequence (and related things), which is so common that it'd be silly to insist on defining POSSIBLE_NEXT_INDEX and POSSIBLE_PREDECESSOR. That said, people do seem to love Python's itertools, so....maybe that's where we're headed. I had somebody aggressively complain about the readability of the all-pairs for-loop, which I thought was basically standard. for(auto i=0; i<N-1; i++)
for(auto j=i+1; j<N; j++)
process(X[i], X[j])
The flip side is that I don't think you always need to do this. For example, this is silly: double triangle::area() const {
const double NORMALIZATION = 1/2.0;
return this->base * this->height * NORMALIZATION;
}
The point is just to make it clear why that particular number is being used and where it came from. for i < j <= N
as this is super clear.However, Python has itertools.combinations(X,2) and Julia has IterTools.subsets(X,2) if that's what you want.
# see __magic_numbers.py
itertools.combinations(X, number_of_things_in_a_pair)Some things only/obviously make sense over pairs of items. For those, go with a literal 2 for x,y in itertools.combinations(obj, 2): if is_overlapping(x,y): raise OverlapError(x,y)
However, sometimes the subset’s size just happens to be two (but you might change it), maybe a constant would be good. Ditto if you’re doing some math where there are “real” 2s that are part of a formula and incidental ones that are due to the subset size. For example:
subset_size = 2
for subset in itertools.combinations(X, subset_size):
mse.append(sum((subset - target)**2)/subset_size)
is a bit more flexible and more clear than using all 2s, IMO, and at very little cost (YAGNI blah blah, but I think that’s an argument for not making a whole configuration system that lets you set the size at runtime).