c++ - Derive & Destroy Encapsulation, or Violate DRY? -
i have 2 c++ classes: sequence, std::vector, , file, sequence of strings represents file on machine.
deriving file sequence no-brainer. behavior same, added functionality of reading , writing files. file-specific functionality implemented easily, without need sequence's data members marked protected. instead, can private, , file can use sequence's public interface. happy times around.
i want make array class internally manages dynamically-allocated memory. array object cannot resized; size specified in constructor.*
here's things arguable.
concept-wise, makes sense derive sequence array. file sequence added functionality of reading , writing files, sequence array added functionality of resizing on-demand.
but there's key difference: resizing functions require direct access memory array managing. in other words, previously-private members must protected.
using protected members instead of private ones destroys encapsulation. link between array , sequence 1 requires it; other classes in works can use parents' public interfaces. in sense, it's bad idea derive.
you argue people want arrays can use sequence , ignore resizing functionality. again, use file , ignore read/write functionality. buying laptop never moving desk. doesn't make sense.
what's best move: derive, , potentially destroy encapsulation; make array free-standing class, , have pointlessly re-implement lot of functionality; or forget array , make people use sequence?
*note project fun , education, practicality of having non-resizable dynamically-allocated array beside point.
well, deriving sequence array public inheritance in case bad idea (as deriving square rectangle). in terms of object-oriented programming, sequence is not array, since array has property sequence not have, , it's: an array object cannot resized. if make derivation, break liskov substitution principle.
in case, want implement functionality, existing in class, suggest use either private inheritance (which means inheritance of implementation), or composition, e.g. storing instance of array in private zone of sequence , using inner implementation.
upd: however, implementing sequence usage of array seems me quite problematic. maybe better create abstract base class container implement common functionality of sequence , array, , derive both these classes it.
Comments
Post a Comment