Java: use fields or not

java, object

Solution

If you would not need `amount` after calling `doSomething(amount)` then, that would be preferred over the former example you've posted.

If your `amount` is part of the object at a later instant of time, then it would be logical to use the former 'technique'.

Here is a rule of thumb you can follow:

If the field denotes a terminating state in your class, then make it a field.

If the field denotes a transient state in your class, use the latter 'technique'.

Problem

I'm confused about when to use fields and when not to in similar cases: 1) I can do that: ``` public class myObject{ private int amount; public myObject(int amount) { this.amount = amount; doSomething(); } private void doSomething(){ //some code } } ``` 2) Or that: ``` public class myObject{ public myObject(int amount) { doSomething(amount); } private void doSomething(int amount){ //some code } } ``` First example looks cleaner for me, but the second automatically tells that `amount` won't be used anywhere else but inside the object, because it is not a field. Anyway, it kinda looks like some heavy "ping-pong" technique in my opinion, especially when I want to pass many objects and values through such code. So, should I save constructor/method parameters as a fields, even if I don't need them outside the object?

Original source