devxlogo

Use derivation instead of type-fields

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.
  • See also  Why ChatGPT Is So Important Today
    devxblackblue

    About Our Editorial Process

    At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

    See our full editorial policy.

    About Our Journalist