- #1
SlurrerOfSpeech
- 141
- 11
In my work I often find myself having to write a procedure for
"If this key is in the map, push this element to the end of the array associated with the key; otherwise, add the key and an associated array whose single element is this one".
I used to do this like
but now prefer to write it like
Why do I like this new way if the old way is equivalent?
Because I like as few conditional blocks as possible. I like to think in terms of "If not this, change that fact and move on to the same logic we will always move on to" rather than "If not this, enter a different block of logic".
Please share your thoughts on this religious doctrine.
Note: I labeled this question as JavaScript only because I had to choose a label. My code is in JavaScript, but this question can apply to other languages.
"If this key is in the map, push this element to the end of the array associated with the key; otherwise, add the key and an associated array whose single element is this one".
I used to do this like
Code:
if ( key in M ) { M[key].push(elem); }
else { M[key] = [elem]; }
but now prefer to write it like
Code:
if ( !(key in M ) { M.[key] = new Array(); }
M[key].push(elem);
Why do I like this new way if the old way is equivalent?
Because I like as few conditional blocks as possible. I like to think in terms of "If not this, change that fact and move on to the same logic we will always move on to" rather than "If not this, enter a different block of logic".
Please share your thoughts on this religious doctrine.
Note: I labeled this question as JavaScript only because I had to choose a label. My code is in JavaScript, but this question can apply to other languages.