In Java (or any similar language) how would you write a Pure function (or method) that removes an element from a list.
If the element is in the list, we simply return a new (ideally immutable) list containing all the elements of the input list, minus the element we removed.
But how would you handle the case where the element isn't found in the list?
Let's assume the method receives 2 parameters, the list
and the element
to remove:
public SOMETHING remove(final List<String> list, final String element){
// Copy the input list and remove the first occurrence of 'element', if I find it.
//
// if I don't find it ... do something clever here ...
}
If I call this method, and element
is not contained inside list
:
- Throwing an exception would presumably make method "impure" (?)
- Modifying the input list and returning a boolean (similar to List#remove()) would presumable make the method "impure" (modifying the input would be a side-effect)
- Returning the input as output would seem unintuitive to me if I was calling this method.
- return an
Optional.of(listCopy)
(EDIT: added to my question after posting it) - Any other ideas ?
EDIT
I should have mentioned that I only want to remove the first occurrence of element
, so if the input list
has multiple occurrences of element
, I don't want to remove them all with a sigle call to my remove() method (e.g. using stream().filter()
). I just edited the comment in my code example to reflect this. However, this is not fully relevant to my question, as my main question revolves around how to make the method intuitive to use AND remain "pure".
EDIT 2
I added an additional idea to the above suggestions. Returning Optional.of(listCopy)
seems like the most elegant solution of the proposed solutions so far. It forces the caller to check if the requested operation was successful or not, AND (if it was successful), it returns a new list, thereby not modifying the original input list. If the operation was not successful (element
wasn't found inside list
), the method returns Optional.empty()
. It seems to me this would also fulfil the below mentioned referential integrity.