SRP without encapsulation violation

I had problems reconciling the principle of shared responsibility with encapsulation. Segregation of duties between classes seems to require exposing large amounts of data. As an example, consider an object called DataPoints . DataPoints populated with x and y coordinates, among other things. I can create a Generator class that populates DataPoints . Now let me say that I want to build these data points. Clearly, this is a separate responsibility that may arise from a class called DataPointsPlotter . But to build the data, I need to know what internal coordinates are x and y. With one class handling both, this is not a problem. x and y are internal variables, but both the create () and print () methods have access to them. I can expose x and y (possibly via getters / seters - ugh), or I can pass the DataPoints structure DataPoints the Plotter class, but still need to get inside to get x and y. I may have a Plotter instance declared in the DataPoints class to which I send x and y. But that is still the impact.

How can I plot x and y in this example using a plotter without breaking encapsulation?

+4
source share
1 answer
 class DataPoint { protected x, y public function construct(theX, theY) { x = theX y = theY } public function getX { return x } public function getY { return y } } 

This encapsulates the responsibility for presenting data in a known format. Assuming there is another sanity check to confirm that x and y are good values, this is one responsibility that is encapsulated here.

 class Plotter { public function plot(DataPoint dp) { x = dp.getX y = dp.getY ... plot ... } } 

The plotter accepts a DataPoint instance and displays it. This is also one responsibility: write down a DataPoint example. It does not require Plotter have any knowledge of the internal structure of a DataPoint . This requires a specific and stable interface, as Plotter can get the necessary data from DataPoint . What are getX and getY . You can change the internal elements of the DataPoint around, but you want as long as its interface remains the same. And DataPoint 's responsibility is to hold the data point and provide other code to access its data in a specific way. If there was no way to get data from DataPoint , its existence would be completely useless.

So no, SRP and encapsulation are not conflicting. You just need to clearly understand what exactly is responsible.

+3
source

Source: https://habr.com/ru/post/1447092/


All Articles