I’m reading the book “Clean Code” and am struggling with a concept. When discussing Objects and Data Structures, it states the following:
- Objects hide their data behind abstractions and expose functions that operate on that data.
- Data Structures expose their data and have no meaningful functions.
So, what I’m getting from this is that I shouldn’t have any public properties on my object, I should only have methods that perform operations on the properties. If I do need to access properties, they should be on a Data Structure, which could be returned from a method on my object? With this approach, it seems that I would need a GetHeight() and SetHeight() method for my Height property on my object, rather than just using get and set of the property.
Maybe I’m not understanding exactly what is being suggested, but this is my understanding of “Objects hide their data.” If you could help me understand this, I’d greatly appreciate it!
Thanks in advance!
Public properties are fine. Not having to write explicit
GetHeight()andSetHeight()methods is what properties are all about. A property in C# is not data; it is best viewed as a pair of getter/setter methods. (Properties are actually compiled down into methods in the generated IL.)The data hiding is possible because you can change the implementation without changing the interface. For example, you could change
into
if you decided that your object should always be square. The code using your class would not need any modifications.
So if your object exposes public properties, it still “hides it data behind abstractions and exposes functions that operate on that data”, as the book recommends.