by aftbit · 5mo ago · 0 comments
HTTPS_SCHEME = 'https'
DOMAIN = 'www.example.com'
url = HTTPS_SCHEME + '://' + DOMAIN
I don't understand what they think this is buying, other than just cargo culting "don't embed constants." And of course, the constant definitions were at the top of the file and the url building code was hundreds of lines away.Do not put regex at the top of the file either! Put it where you use it. Languages are smart, they’ll probably be able to tell that it’s constant anyway.
Also for tiny functions just use a lambda. Please don’t make a one line function a million miles away that you use once or twice.
Anyway, maybe there are other reasons too, so see Chesterton’s Fence. In any case, it’s never a good idea to assume cargo culting. Someone could easily say the same thing about using inline literals. If it looks weird, ask around and maybe you’ll find out there are good reasons, or maybe you’ll find out nobody cared and that people will like it if you refactor and embed the constants.
Over time, everyone develops their own intuition and opinions on what sorts of change and refactors are likely, and which sorts will never come. It's not perfect - it's part of the art of software, not the science. I'm not going to claim I've never written an interface that had a useless cut-point - I definitely have written many.
In my opinion, it's better to err on the side of simplicity, understandability, and closeness than to prematurely factor out those constants.
It's a judgement call - every situation and every practitioner will have a different response. In this case, knowing this product, and as the code reviewer for this patch made by a newer engineer (senior but new to the team), I was very confident that we would never need to change the scheme, and that the extra line and extra cognitive load of groking `HTTPS_SCHEME + "://"` over just `"https://"` or `BASE_URL + blah` was not worth it.
I suggested that the engineer either rewrite it with an inline constant, or refactor the whole base URL out without separating the scheme.
If you pull it out into a constant, you're back to opening up projects one-by-one to 'find usages'
Luckily there are often solutions that just come down to which arbitrary labels that you assign. e.g. compare these two blocks
do_thing = do_thing_one_way if condition else do_thing_other_way
process(data, do_thing=do_thing)
versus thing_processor = do_thing_one_way if condition else do_thing_other_way
process(data, thing_processor=thing_processor)
The first is much more greppable - search for "\bdo_thing" all over the code base. The second requires realizing that the processor function renames the internal function to "thing_processor".