proper mathematics way to explain in a comment that there is no duplicate items in a set

56 Views Asked by At

i'm writing some code, and I want my code to be well documented.
there is a part in the code where I'm checking that when there is a try to insert new element E to a list L, the element E will be unique (so there is no other elements in L that equals to him).

I'm having difficult to write a user-friendly mathematics comment, something that will look like the example bellow

the function will change all elements (that in list L) fields E.color to "Black" only if color to black element.size > 10.
so in that case I will write the comment -
[ X.color="Black" | X in L, X.size > 10]

but for the scenario above I couldnt find any satisfied mathmatics comment.

2

There are 2 best solutions below

1
On BEST ANSWER

A mathematical set by definition has no duplicates inside it, so perhaps using the a set rather than a list would solve your problem.

However if that's too hard to change now then you could write something like:

[ L.insert(E) | E not in L ]

where E is the element and L is the list.

0
On

an exhaustive answer to your question requires two observations:

  1. Best coding practices require you to know collections very well and when to use them. So you want the right collection for the right Job. In this case as advised in other comments, you need to use a Set instead of a list. A Set uses a Map under the hood, having your elements as keys and values as DEFAULT. Every time that you add an element to your Set, the Hash value for it is calculated and compared using equals to the existing elements. So no dups are allowed.
  2. I really appreciate the fact that you want to write good comments, however you don't need to for the following reasons:

    • List and Sets behaviour is largely documented already, so nobody expects you to comment them;
    • Books like Refactoring and Clean code, teach us that good code should never be commented as it should be self explaining. That means that your method/class/variable name should tell me what the method is doing.