Are there any alternative solutions for avoiding Getter/Setter methods in Android?
I am already using getter/setter methods but below link said, avoid getter/setter method.
How to access collection object using without getter/setter google solution?
Are there any alternative solutions for avoiding Getter/Setter methods in Android?
I am already using getter/setter methods but below link said, avoid getter/setter method.
How to access collection object using without getter/setter google solution?
Usage of getters and setters is a very long argument. There are reasons for and against. Saying that using setters ensures encapsulation simply isn't true in most cases.
There is no difference between:
object.x = value;
and
object.setX(value);
Some examples of discussions here:
Advantage of set and get methods vs public variable
Are getters and setters poor design? Contradictory advice seen
From the link you provided:
It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.
From this we learn 2 things:
public, this doesn't respect the OOP principles;getter/setter only when you are outside the scope of a class. When you are writing code inside the class you should always access the field directly. Here is the access speed for direct access:Without a JIT, direct field access is about 3x faster than invoking a trivial getter. With the JIT (where direct field access is as cheap as accessing a local), direct field access is about 7x faster than invoking a trivial getter.
From the link you provided:
However, this is a bad idea on Android. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.
Basically what it means is that you can have getters and setters, but when you want to access a class' own fields, access it directly. In other words, you should do this:
class Foo {
private int bar;
public int getBar() { return bar; }
public void setBar(int value) { bar = value; }
public someOtherMethod() {
// here if you want to access bar, do:
bar = 10;
System.out.println(bar);
// instead of:
// setBar(10);
// System.out.println(getBar());
}
}
// but outside of this class, you should use getBar and setBar