TomatoMato
TomatoMato

Reputation: 713

Java: use fields or not

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?

Upvotes: 4

Views: 93

Answers (2)

Fritz
Fritz

Reputation: 10045

Fields define the structure of an object. It's an attribute of the entity it represents, either by being the name of a person or the currency of an account, just to give some examples.

Those define a particular instance of a class and in a group, define the current state of an object. Those kind of attributes should go in a field, because they will be queried and updated multiple times.

You should consider the context in which that certain value is meaningful. If it is something deeply related to a certain object and should stick to it for as long as the object "exists", it can be a field. Otherwise, it can be just a method or constructor parameter.

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25705

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'.

Upvotes: 4

Related Questions