vendredi 24 décembre 2021

Encapsulation vs data hiding (they are not the same)

I am a little confused by whole terminology of encapsulation and data hiding. I'm reading a book "Dive into design patterns" by refactoring guru and when he explains what encapsulation is, I thought that something is off.

I've searched and I found a really nice explanation: https://stackoverflow.com/a/28614407/11993214.

He mistook encapsulation with data hiding. After reading answer from above link I sum this up to those definitions:

encapsulation - is when we are seperating from a piece of code, data and methods, which are using these data, and we are packing them together. data hiding - is a place where everything we can, we do as private and we are implementing getters and setters as the only places from which we can access this data.

But as I read more, I've got even more confused. He made a topic: Encapsulate what varies. It have two subcategories - encapsulate on method level, and on class level. It says for example to remake this:

enter image description here

into this:

enter image description here

I think it's similar to the statement from question from link above.

Whatever changes encapsulate it. Protecting anything which is prone to change.

, and answer to this was:

(...) And 2, as noted by CommuSoft, isn't really a definition, it's a rule of thumb. And I will add that it's a rule of thumb about when to use data hiding, not encapsulation

So now, I have this section from book, and based on this example that I gave I think that it is more likely to be an encapsulation case. But if I'm thinking correctly and it is similar to the quotes from linked topic, than based on that answer this example code is a rule of thumb about when to use data hiding? So to sum up... I'm really confused if I understand encapsulation and data hiding correctly. Based on those examples which I provide, I'm thinking that this example is encapsulation. Is it correct? And if yes, than how is it different from the topic mentioned in quotes?

I'm looking forward to your answers, and if this whole explanation is not clear than please give me feedback, and I will try my best to do better.

Aucun commentaire:

Enregistrer un commentaire