I'm currently moving from C++ to Java for work and am having difficulty without const and pointers to make sure intent is always clear. One of the largest problems I'm having is with returning a modified object of the same type.
Take for example a filter function. It's used to filter out values.
public List<int> filter(List<Integer> values) { ... } Here everything is Serializable so we could copy the whole list first then modify the contents and return it. Seems a little pointlessly inefficient though. Especially if that list is large. Also copying your inputs every time looks quite clumsy.
We could pass it in normally, modify it and make it clear that we are doing that from the name:
public void modifyInputListWithFilter(List<Integer> values) { ... } This is the cleanest approach I can think of - you can copy it before hand if you need to, otherwise just pass it in. However I would still rather not modify input parameters.
We could make the List a member variable of the class we are in and add the filter method to the current class. Chances are though that now our class is doing more than one thing.
We could consider moving the List to it's own class which filter is a function of. It seems a little excessive for one variable though, we'll quickly have more classes than we can keep a track of. Also if we only use this strategy and more than just filtering happens to the List class will unavoidably start doing more than one thing.
So what is the best way of writing this and why?
List<int>is not possible in Java. You can't have aListof primitives.filterthat accepts aList, I'd expect to be getting a new list with matching items as a return value. (If the items were objects, I'd expect the same references on both lists, not a deep copy.) Same formapand other similar functions.