Is this a bad doStuff practice and returns a boolean?

In the java course that I am currently running, I need to add a value to the key if the key does not already matter, except that they also want the method to return true if the key has been added or false when the key already had a value.

HashMap<RegistrationPlate, String> register = new HashMap<RegistrationPlate, String>(); public boolean add(RegistrationPlate plate, String owner) { if (register.get(plate) == null) { register.put(plate, owner); return true; } return false; } 

It seems strange to me to have an add method that returns true values ​​if it was a void method?

+4
source share
3 answers

In Java util classes, these methods are widely used.

Just look at the ArrayList class that almost everyone knows:

There is a method in this class called boolean add(T e) , and in java there are many other classes that work like this.

In my opinion, this is normal and it makes testing easier. (you can check if the method was successful by the return value)

+2
source

Returning a boolean for such a thing as adding can be quite useful. In fact, put returns the old value since it uses it.

Therefore, you do not need to use get - or better containsKey , but you can:

 public boolean add(RegistrationPlate plate, String owner) { String oldValue = register.put(plate, owner); return oldValue == null || !owner.equals(oldValue); } 

|| ... || ... little bust.

0
source

It seems strange to me to have an add method that returns true values ​​if it was a void method?

Definitely not weird. Do not think of boolean methods as a way to ask a question and return a yes or no answer. They can do much more!

Take a look at the Java source code and you will see how good it is for certain methods to have a return type of boolean . Want to add something to an object? Was it successful? There are several circumstances where return types of the boolean type are beneficial for interactions between classes / objects / methods.

Take a look at the Java ArrayList remove (Object) implementation for a great example of boolean return types that provide additional information.

0
source

All Articles