5 ms·
He proposes to replace if(current_day == "Monday" || current_day == "Wednesday" || current_day == "Friday") with if(["Monday", "Wednesday", "Friday"].
by morsch 15y ago
He proposes to replace
if(current_day == "Monday" || current_day == "Wednesday" || current_day == "Friday")
with
if(["Monday", "Wednesday", "Friday"].include?(current_day))
I've done this before, and I don't think it's any less clear -- I wouldn't have thought of making a public announcement about it, though. I like it because it more closely aligns with the way you're probably thinking in this example: you're wondering if current_day is part of a certain set of days (the discount weekdays, apparently), not if it's equal to "Monday" or equal to "Tuesday", etc. I like the Javascript example with it's indexOf(..) >= 0 a lot less, but I guess people more used to JS idioms auto-translate this sequence to a set-contains operation.
It's more sensible if the set of values is larger than just three; and in this instance, you have to wonder why the day isn't available as a numeric variable, but I think you can let it slide for a contrived example.
It's even more useful if you reference the same set more than once, because you can just define it once, and as a constant if your language of choice does that kind of thing. This would also let you make your code less wordy (but arguably more literal) without hiding logic in functions, e.g. his later example would be
if(discount_weekdays.include?(current_day) && current_date > 20)
- erez 15y ago"It's more sensible if the set of values is larger than just three ... It's even more useful if you reference the same set more than once" Both are correct, I am strictly referring to his rationale being it's too verbose.
- Inufu 15y agoSo like Python's 'in'? if 5 in [1, 2, 5, 6, 8]: pass
- valisystem 15y agocase current_day when "Monday", "Wednesday", "Friday" then <do stuff> end
- bingaling 15y agodo_stuff() if $current_day ~~ @discount_weekdays;