Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Adding methods to a polymorphic class hierarchy without violating SRP?
    primarykey
    data
    text
    <p>I have a design issue that I constantly keep encountering.</p> <p>For the sake of illustration, let's assume that I have a polymorphic class hierarchy</p> <pre><code>class A { public: virtual ~A() {} ... }; class B: public A { ... }; class C: public B { ... }; class D: public A { ... }; ... </code></pre> <p>I want to be able to print instances of these classes in a polymorphic way, i.e. each class has its own way of printing itself. The obvious way of achieving this would be to add</p> <pre><code>virtual void print(OutputStream &amp;os) = 0; </code></pre> <p>into the base class and override this method in every subclass. However, if the original responsibility of the classes is not related to printing, this will add another responsibility to them, thus violating <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow noreferrer">SRP</a>.</p> <p>My question is: what is a proper way of achieving the desired behavior without violating SRP?</p> <p>In <a href="https://stackoverflow.com/q/2352533/2580955">this post</a>, a solution based on the <a href="http://en.wikipedia.org/wiki/Visitor_design_pattern" rel="nofollow noreferrer">Visitor design pattern</a> is proposed. However, then I would need to create a class which has to know about every subclass of <code>A</code>. I would like to be able to add and remove subclasses without a need to always modify the visitor.</p> <p>Is there some other, SRP-preserving way than the two ways described above?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload