design - Best way to write a Java function that modifies an object -
i'm moving c++ java work , having difficulty without const , pointers make sure intent clear. 1 of largest problems i'm having returning modified object of same type.
take example filter function. it's used filter out values.
public list<int> filter(list<integer> values) { ... } here serializable copy whole list first modify contents , return it. seems little pointlessly inefficient though. if list large. copying inputs every time looks quite clumsy.
we pass in normally, modify , make clear doing name:
public void modifyinputlistwithfilter(list<integer> values) { ... } this cleanest approach can think of - can copy before hand if need to, otherwise pass in. still rather not modify input parameters.
we make list member variable of class in , add filter method current class. chances though our class doing more 1 thing.
we consider moving list it's own class filter function of. seems little excessive 1 variable though, we'll have more classes can keep track of. if use strategy , more filtering happens list class unavoidably start doing more 1 thing.
so best way of writing , why?
the short answer there not single best way. different scenarios call different approaches. different design patterns call different approaches.
you've suggested 2 approaches, , either 1 of them might valid depending on scenario.
i there nothing inherently wrong modifying list pass function: take @ collections.sort() function, example. there nothing wrong returning copy of list instead.
the "rule" here liskov rule (not the liskov rule): function should whatever documentation says do. if you're going modify list, make sure documentation says so. if aren't, make sure says instead.
Comments
Post a Comment