0

Is it bad to refer field attributtes directly if there exist an access method for it (get/set)?

Also when dealing with JComponents, earlier exams initialise the field attributtes in the constructor, when I see no reason why it can't be initialized in the class field. Is there a good reason for this, or am I free to choose?

Kevin Frostad
  • 181
  • 1
  • 1
  • 12
  • 1
    1 In general yes, since it defeats the point of having accessors. 2 It is a matter of style. You are advised to use the style preferred by whoever is evaluating your code. – khelwood May 31 '16 at 14:30
  • An answer to your first question : http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Akah May 31 '16 at 14:31
  • I see. It's just that we have to write on paper for the exam and initializing 8 field componets in the constructor after setting the variables in the field gets a bit frustrating. Guess I'll just have to suck it up then. – Kevin Frostad May 31 '16 at 14:36

1 Answers1

1

Creating a getter and setter for a private field help to hide the internal implementation of the class. It means that you can change the internal representation without changing the external interface to other classes.

For example if you have a custom class that implements a data structure similar to a sequence of values. The first implementation can use an array of values.

Adding some new functionalities you can decide to change the internal representation of the values from an array to a List.

Here an example.

Original code using an array:

public class MySequence {
    private Object[] values;

    public Object[] getValues() {
        return values;
    }

    public void setValues(Object[] values) {
        this.values = values;
    }
} 

Then you think can be a good idea to create a method to add a new value. Here you can change the internal implementation, leaving the same interface to the users of the MySequence class.

public class MySequence {
    private List<Object> values;

    public void add(Object value) {
        values.add(value);
    }

    public Object[] getValues() {
        return values.toArray(new Object[values.size()]);
    }

    public void setValues(Object[] values) {
        this.values = Arrays.asList(values);
    }
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56