Which is a better way to write an "add or initialize"?

  • Thread starter Thread starter SlurrerOfSpeech
  • Start date Start date
AI Thread Summary
The discussion centers on different approaches to adding or initializing elements in a map or associative array in programming. One method uses a conditional block to check if a key exists before pushing an element or creating a new array, while the preferred method minimizes conditional blocks by initializing the array if it doesn't exist and then pushing the element. Participants highlight that separating initialization from adding can enhance clarity and efficiency across various programming languages, including JavaScript, Python, Perl, and C++. The conversation also touches on idiomatic practices in different languages, such as using the or-operator in JavaScript and exception handling in Python. Overall, the preference leans towards approaches that streamline logic and reduce complexity.
SlurrerOfSpeech
Messages
141
Reaction score
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

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.
 
Technology news on Phys.org
When initialization and adding can be separated (not always the case for all data structures) then your second approach is quite common and, in my opinion, a bit more clear than the former approach. I would go with the later approach whenever possible.

Note, that in JavaScript there is another common idiom when initializing and adding that uses the or-operator. Provided that your M object only have array members, then in your case that idiom would be like
Code:
(M[key] || (M[key] = [])).push(elem);
 
In this case, the difference is so small that it's a bit moot. How one would accomplish that is also language-dependent.

In python, I'd probably follow the mantra that it's easier to ask for forgiveness:
Python:
def add_element (M, key, elem) :
    try :
        M[key].append (elem)
    except KeyError :
        M[key] = [elem]

In perl, I'd use something similar to your new method, except I'd use an end-line conditional, and to avoid not, I'd use unless:
Perl:
sub add_element($$$) {
    my ($M, $key, $elem) = @_;
    $M->{$key} = [] unless exists $M->{$key};
    push @{$M->{$key}}, $elem;
}

Update on the above: @Filip Larsen's approach also works nicely in perl:
Perl:
sub add_element($$$) {
    my ($M, $key, $elem) = @_;
    push @{$M->{$key} or $M->{$key} = []}, $elem;
}

In C++, I'd use the fact that M[key] automatically adds the key to the associative array if it's not present:
Code:
template <KeyType, ElemType>
void add_element (
    std::unordered_map<KeyType, std::vector<ElemType>>& M,
    const KeyType& key,
    const ElemType& elem)
{
    M[key].append(elem);
}
 
Last edited:
  • Like
Likes SlurrerOfSpeech
Now DH has started on other languages I may add that in C# (where the standard dictionary index operator getter throws exception on unknown keys) I mostly end up do something like

Code:
void AddElement<TKey,TValue>(IDictionary<TKey,ICollection<TValue>> map, TKey key, TValue value) 
{
  ICollection<TValue> values;
  if (!map.TryGet(key, out values)) {
    map[key] = values = new List<TValue>();
  }
  values.Add(value);
}
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
What percentage of programmers have learned to touch type? Have you? Do you think it's important, not just for programming, but for more-than-casual computer users generally? ChatGPT didn't have much on it ("Research indicates that less than 20% of people can touch type fluently, with many relying on the hunt-and-peck method for typing ."). 'Hunt-and-peck method' made me smile. It added, "For programmers, touch typing is a valuable skill that can enhance speed, accuracy, and focus. While...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top