Advertisement

Should I use arguments with private methods in Java?

Started by January 01, 2019 11:03 PM
3 comments, last by Oberon_Command 5 years, 11 months ago

I have a class with a bunch of private methods used to determine class attributes. These methods rely on other class attributes to determine the values they return.

I was wondering if it is seen as more proper/elegant to pass in attributes as arguments or just call `this.attributeName` whenever I need to reference them.

The argument could be simply made that it's easier to see the dependencies of the method when they are included in the header of said method, especially if it's a large several hundred, or a 1000+ line method

Though I could use ctrl+f to find the instances where you reference the `this` pointer, however my control key sticks you see. 

 

Advertisement
17 hours ago, RidiculousName said:

I was wondering if it is seen as more proper/elegant to pass in attributes as arguments or just call `this.attributeName` whenever I need to reference them.

I don't see these both options as equivalent. A "obj.f()" says to me that it computes a value purely from the object. A "obj.g(obj.y)" says to me that it computes a value from the object and the argument (which happens to live in the object too, but that's just a coincidence). I consider g() to be much more generic, as nothing prevents me from inserting another value as argument. In the extreme case, g could be a static function, computing its value from parameters only.

Depends on context. It is usual for methods in general in any language to just look at the fields they need on the object when it needs those fields, unless there's some reason not to. For instance, you might have a case where you want to call the same method on different fields on the object; in this case, you'd pass them in an argument. Having two separate functions for the sake of having the same behaviour with different fields falls under "copy paste" code and therefore "silly", in my book.

I also would advocate against keeping non-owning references to other objects in your class just for the sake of a single method. In general, pass in external dependencies as function arguments, unless it is necessary or significantly more convenient not to. The dependencies of any particular method should be evident to the caller. A class should store exactly the fields it needs to fulfill its design contract and no more than that.

This topic is closed to new replies.

Advertisement