c++ - Modifying class behavior depending on property using if() is code smell or not? -


i have class representing parameter. parameter can number, array, enum or bitfield - param type. behavior different between these types, subclasses of parambase class. parameter can stored in ram or static (i.e. hardcoded in way, saved in file).

void read() implemented in parambase , uses template method pattern implement reading param type, works ram storage. if parameter static read() must completely different (i.e. read file).

a straightforward solution can further subclassing paramarraystatic, paramnumberstatic, etc. (it 8 subclasses). difference between paramarray , paramarraystatic in read() method, straightforward solution lead code duplication.

also can add if( m_storage==static ) read() method , modify behavior, code smell(afik).

class parambase     {     public:         virtual paramtype_t type() = 0;          paramstorage_t storage();          virtual somedefaultimplementedmethod()         {             //default implementation         }          void read()         {             //template method pattern             m_prop1 = blablabla;             somedefaultimplementedmethod();         }      protected:         paramstorage_t m_storage;         int m_prop1;         int m_prop2;     };      class paramarray: public parambase     {     public:         virtual paramtype_t type()         {             return pt_array;         }         virtual somedefaultimplementedmethod()         {             //overriding default implementation of base             //i.e. modify templated read() method behavior         }     protected:         int m_additional_prop1;         int m_additional_prop2;     }; 

in end, have 4 subclasses of base , need modify behavior of read() static/non_static modificator.

how solve without code duplication , code smell? condition if( m_storage==static ) in read() code smell or not?

you never have duplicate code: re-implement single method read. if need use pointers base class, virtual that. if have common code between 8 read method (or between of them), put in common middle layer.

if want make clear class might not use method @ base level, can make abstract, add ninth subclass ram case.

having huge switch calling 9 different read methods in same class seems far worse me.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -