I've been reading about data hiding and there seem to be slightly different definitions of it, so when trying to come up with a practical example, I'm not sure if I'm doing the right thing.
So far, I got that data hiding protects data from being accessible in an unexpected way. This makes me think of two different cases, but I'm not sure if these actually describe data hiding or I'm describing something else:
- Let's say I have a Gym class and a Member class. The Gym class will have a container of Member object called members. So if I'm using Python, maybe it will be a list of Member. But if I add members to my Gym by doing
gym.members.append(new_member)
then I'm revealing the actual implementation of my container. This could cause trouble if, for example, at some point I wish to stop using a list and start using a dictionary, since I'd have to find and replace all lines where I've appended members. So to avoid this, I'd rather create a method calledaddMember(self, member)
where I can manage my implementation internally, within the Gym class. - The other case is where I don't want an attribute value to be changed directly, because I need to do some checks before. To extend the first example, let's say the Member class has also
active
and alastPayment
attributes whereactive
is a boolean set to True when gym membership is active and to False otherwise, andlastPayment
is the date of the last payment made by the gym member. When the last payment was made more than a month ago, then membership is automatically set toactive=False
and then only when a new payment is made it's set back to True. This means that theactive
value shouldn't be directly changed by doingmember.active=False
. So in that case I'd protect this attribute by naming it as__active
.
So these are two different cases (revealing actual implementation and preventing accidental changes) that I understand to represent data hiding, and I'm not sure if both are just two different examples of data hiding or I have some misconception and I'm describing something else.