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.
source share