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

  • Thread starter SlurrerOfSpeech
  • Start date
In summary: I have also seen the try-get version "if one line" likevoid AddElement<TKey,TValue>(IDictionary<TKey,ICollection<TValue>> map, TKey key, TValue value) { (map.TryGet(key, out ICollection<TValue> values) ? values : map[key] = new List<TValue>()).Add(value);}...but that's not the way I usually write it.
  • #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

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
  • #2
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);
 
  • #3
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
  • #4
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);
}
 

1. What is the difference between "add" and "initialize" in writing?

"Add" and "initialize" are both terms used in computer programming to describe the process of assigning values to variables. However, "add" typically refers to adding a value to an existing variable, while "initialize" refers to assigning an initial value to a variable before it is used in a program.

2. Which is more commonly used in programming, "add" or "initialize"?

The use of "add" or "initialize" in programming depends on the specific language and coding style. Some languages may use one term more frequently than the other, while others may use them interchangeably. It is important to follow the conventions of the language you are working in and use the term that is most appropriate for the specific task at hand.

3. Is one method more efficient than the other?

The efficiency of "add" versus "initialize" will depend on the specific context in which they are used. In general, "initialize" may be more efficient when assigning values to a large number of variables at once, while "add" may be more efficient for modifying existing variables. However, the difference in efficiency may be negligible in most cases and should not be a determining factor in choosing between the two methods.

4. Can "add" and "initialize" be used interchangeably?

As mentioned before, the use of "add" and "initialize" will depend on the specific programming language and coding style. In some cases, the two terms may be used interchangeably, but it is important to understand the nuances of each term and use them appropriately in your code to avoid confusion and potential errors.

5. Are there any best practices for using "add" and "initialize" in programming?

There are no hard and fast rules for using "add" and "initialize" in programming, but it is generally recommended to use "initialize" when assigning initial values to variables and "add" when modifying existing variables. It is also important to follow the conventions of the language you are working in and be consistent with your usage throughout your code for clarity and readability.

Similar threads

  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
31
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
2
Replies
43
Views
4K
  • Programming and Computer Science
Replies
4
Views
918
  • Programming and Computer Science
Replies
28
Views
3K
Replies
10
Views
961
  • Programming and Computer Science
Replies
7
Views
4K
  • Linear and Abstract Algebra
Replies
2
Views
934
  • Programming and Computer Science
Replies
9
Views
2K
Back
Top