Note that there are some explanatory texts on larger screens.

plurals
  1. PODerive & Destroy Encapsulation, or Violate DRY?
    text
    copied!<p>I have two C++ classes: <code>Sequence</code>, which is just like <code>std::vector</code>, and <code>File</code>, which is a <code>Sequence</code> of strings that represents a file on the machine.</p> <p>Deriving <code>File</code> from <code>Sequence</code> is a no-brainer. Its behavior is exactly the same, but with the added functionality of reading and writing files. The <code>File</code>-specific functionality is implemented easily, without the need for <code>Sequence</code>'s data members to be marked as protected. Instead, they can be private, and <code>File</code> can use <code>Sequence</code>'s public interface. Happy times all around.</p> <p>I want to make an <code>Array</code> class that internally manages dynamically-allocated memory. An <code>Array</code> object cannot be resized; the size is specified in the constructor.*</p> <p>Here's where things get arguable.</p> <p>Concept-wise, it makes sense to derive <code>Sequence</code> from <code>Array</code>. Just as a <code>File</code> is a <code>Sequence</code> with the added functionality of reading and writing files, <code>Sequence</code> is an <code>Array</code> with the added functionality of resizing on-demand.</p> <p>But there's a key difference: The resizing functions require <strong>direct access</strong> to the memory <code>Array</code> is managing. In other words, the previously-private members must now be protected.</p> <p>Using protected members instead of private ones destroys encapsulation. The link between <code>Array</code> and <code>Sequence</code> is the only one that requires it; other classes in the works can just use their parents' public interfaces. In this sense, it's a bad idea to derive.</p> <p>You could argue that people who want arrays can just use <code>Sequence</code> and ignore the resizing functionality. But then again, you could just use <code>File</code> and ignore the read/write functionality. It would be like buying a laptop but never moving it from your desk. It simply doesn't make sense.</p> <p>What's the best move: To derive, and potentially destroy encapsulation; to make <code>Array</code> a completely free-standing class, and have to pointlessly re-implement a lot of functionality; or to forget about <code>Array</code> completely and just make people use <code>Sequence</code>?</p> <p>*<em>Note that this is a project for fun and education, so the practicality of having a non-resizable dynamically-allocated array is beside the point.</em></p>
 

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