Use derivation instead of type-fields

Whenever your class uses a type-field, as in the following case:

 	class Internl { //internationalization aid		Lang lg; //type field		FontResource fonts		public:		enum Lang {English, Hebrew, Danish}		Internl(Lang lang) lg(lang) {};		Loadfonts(Lang lang); 	};

Every modification to the Internl class affects all of its users, even when they should not be affected. For instance, when adding support to a new language, the users of the already-supported languages have to recompile (or worse: download) the new version. Moreover, as time goes by and support for new languages is added, the class becomes bigger, and its code harder to maintain. It takes longer to compile and contains more bugs. A bug introduced due to an addition of a new language will affect all users. Obviously, a much better choice is to use derivation:

 	class Internl { //now a base class		FontResource fonts		public:		Internl();		virtual int Loadfonts(); 		virtual void SetDirectionality();	};	class English : public Internl {		public:		English();		Loadfonts() { fonts = TimesNewRoman; }  		SetDirectionality(){}//do nothing; default: left to right	};	class Hebrew : public Internl {		public:		Hebrew();		Loadfonts() { fonts = David; }  		SetDirectionality() { directionality = right_to_left;}	};

The class hierarchy advantages over a type-field are:

  • It simplifies the structure of its classes.
  • It reduces the number of potential bugs (and when they do occur, they are confined to a single class and not shared by all).
  • It improves performance; no use of lengthy switch statements everywhere.
  • Creation of new derived classes does not affect users of existing classes.
  • Share the Post:
    Share on facebook
    Share on twitter
    Share on linkedin


    Recent Articles: