Is it good practice to do "do nothing" methods based on state?

Kind of specific question, but look at this: (Bare with me, this is just a quick drawn java)

public class Main {

    private static List<Integer> list = new ArrayList<>();

    public static void add(int x) {
        if(list.contains(x)) {
            return;
        }
        list.add(x);
    }

    public static void main() {
        list.add(1);
        list.add(1); //should it do nothing or throw an error?
    }

}

      

Also, please ignore what I may have been using Set<Integer>

, which removes the need forif(list.contains(x))

In any case, assume that list

it cannot have duplicates, and also assume that if at any moment a duplicate is accidentally added (eg: the second list.add(1)

), which should be considered an error; I don't want to add duplicates if I don't need to.

The bottom line is this: if add(int x)

did throw an exception instead (for example, IllegalArgumentException

or something else)? I understand that if I didn't, I wouldn't need to worry about it throwing actual duplicate errors, since it just won't do anything in the second addition, but it still bothers me a little that in some unnecessary moment add()

.

I've seen code like add(int x)

this that checks for something and just doesn't do anything based on it. Hopefully you can apply this idea to what you have done before.

Anyway, I don't even know. Should I continue as above in more recent similar issues or should it rule out?

+3


source to share


2 answers


Yes for both, depending on what you want to achieve. For a set, adding a non-unique element should not do anything and is not an exception. For a list of unique elements, adding a non-unique element may be an exception and should raise an exception. This is not about programming, but about modeling: what your object considers normal and what does not. There is no "best" answer.

For example, if you want to keep track of which developers have completed today, you can add them to the set worked

. If a developer makes another commit today and you add him, he is still just "done the work", and this is not an exceptional situation; just go back without changing the list.



But if you are in employment and hiring a developer while he is actually already in your enterprise, this is an exception and an error occurs.

+4


source


It depends on your requirement. I make methods that conventionally do nothing all the time. But if your requirement requires some error detection, you should throw an exception.



0


source







All Articles