When studying Android's BitmapFactory.Options
class, I noticed that its fields are publicly available to be accessed and modified.
This is contrary to the general encapsulation rule that states the fields should be declared private
, and accessing/modifying them should be achieved via public
getter/setter methods. This way we can control how clients can approach our class's fields.
That makes me wonder if I'm misunderstanding the encapsulation concept.
When writing my own classes, in which situations I am allowed to ignore the encapsulation, just as it is ignored in BitmapFactory.Options
?
One may argue that encapsulation is not necessary when there is no need for restrictions in getting/setting the field values. But I think it is not the case with BitmapFactory.Options
, because, e.g., BitmapFactory.Options.inSampleSize
should be a power of 2:
the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.
Hence, the developers could declare a setter method that
What the Javadoc says for inSampleSize
is
Also, powers of 2 are often faster/easier for the decoder to honor.
This means the class
author is delegating to you the decision of which value to assign to it.
Nowhere is stated other values won't work, it is just they won't be as efficient, becuase of the rounding phase. There might be usecases where non-power-of-two numbers have to be assigned.
By giving a look at that inner static class
I see no reason to use getters/setters encapsulation.
They would be unnecessary and redundant, like many classes which "respect" the JavaBean style.
Why have a 500 NLOC
class when you can have a 50 NLOC
one? Keep it simple.