DEV Community

Composition over encapsulation

Aleksi Kauppila on August 08, 2019

A big problem with inheritance is that it easily gets out of hand a becames an unmaintainable mess. It very quickly becomes a tree that reaches out...
Collapse
 
stereobooster profile image
stereobooster

Define encapsulation

  1. the action of enclosing something in or as if in a capsule.
  2. the provision of an interface for a piece of software or hardware to allow or simplify access for the user.

If we take "1" then inheritance breaks the encapsulation, because other class knows some details for parent class.

If we take "2" then composition doesn't break it - you can provide interfaces and use composition.

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

Am i correct to make the conclusion that #2 supports the idea that Kasey Speakman introduced in his response about DTOs?

Thanks for this response! I think this is turning into a real ”aha moment”! πŸ‘πŸ‘

Collapse
 
stereobooster profile image
stereobooster

Maybe to some extent.

The main question is what you try to isolate from what? There are different ways to build isolations, in some PL you can restrict access to inside of the module, ot you can use closures to hide some data, or something like wrapper object which takes callback-functions (like monad).

I'm not sure I fully understand your initial question.

Collapse
 
kspeakman profile image
Kasey Speakman

A report is a compilation of data, almost by definition. It seems like it is more of a produced artifact than something with behavior. Sometimes things are just data. And sometimes functions from one type of data (the report) to another (the view) is sufficient.

I recently made a post that touched on that here.

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

Which solution would you prefer in this example and why? Or would you have some other solution? Thanks!

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

For me the solution would be to make the report "just data" (probably immutable) -- a DTO. If you provide it as data, it can be readily adapted to a specific view technology at render time. Having a "view" behavior could probably never work if it is used in more than one UI technology anyway.

I probably would choose to go WET with this report... no composition or inheritance. Once you need the same set of report fields again for the same reason, then you could worry about refactoring them into their own data class and use composition.

Remember the practices (like SOLID) and paradigms (like OO) should serve the purpose of the code, not the other way around.

Thread Thread
 
aleksikauppila profile image
Aleksi Kauppila

Very nice, thanks for your input πŸ‘