Passing whole object vs passing object's property

后端 未结 3 1459
逝去的感伤
逝去的感伤 2020-12-24 00:38

I\'m thinking about the solution for my application. Here\'s the situation: I have a class with a method that takes ObjectA as an input parameter and calls several small met

3条回答
  •  独厮守ぢ
    2020-12-24 01:39

    Let's examine a scenario. Now this may or may not be your scenario but it illustrates a point.

    Lets say field1 and field2 in your case are two integers and method1 sums them and returns the result.

    If you pass in the objects then that method can only ever sum those two fields. The method is also now strongly coupled with those objects.

    On the other hand, if you pass in only the fields, the two integers in this case your method becomes more generic. You can now sum any 2 arbitrary integers regardless of which objects they are on.

    In general though, always expose as little of your objects to other methods and classes. This promotes loose coupling.

    Exceptions

    AS maaartinus points out if for example field1 and field2 were Points and method1 calculated the distance between those two points, then I would have to agree that passing two Points would be better than passing 2 xy integer pairs (4 parameters)

    Hope this helps

提交回复
热议问题