According to the principle of encapsulation, objects should be responsible for their own states.
Because of this, class members should never be public. It's easy to imagine how difficult it can be to find cause of errors related to an object when anything from the outside can modify its state. Objects can control their states by exposing their interfaces alone.
In mathematics, a rational number is any number that can be expressed as the quotient a/b of two integers, with the denominator b not equal to zero.
class RationalNumberUnsafe {
private int a;
private int b;
public RationalNumberUnsafe(int a, int b) {
this.a = a;
this.b = b;
}
public double getValue() {
return a / b;
}
}
With encapsulation, a class instance can have control over its state, avoiding possible errors like setting b denominator to zero. In fact the object shouldn't even instantiate in the first place. This principle will be further discussed under the topic of value objects.
class RationalNumber {
private int a;
private int b;
public RationalNumber(int a, int b) {
this.a = a;
if(b != 0) {
this.b = b;
} else {
throw new Exception("Denominator can't be set to 0")
}
}
public double getValue() {
return a / b;
}
}
Read the next guide: Refactoring class methods