c++ - Programming pattern for components that are toggleable at runtime -


i'm wondering if there kind of logical programming pattern or structure should using if during runtime component should used , other times not. obvious simple solution use if-else statements everywhere. i'm trying avoid littering code if-else statements since once component toggled on, more on while , wonder if worth recheck if same component active on place when answer not have changed between checks.

thanks

a brief example of i'm trying avoid

class mainclass { public:     // constructors, destructors, etc  private:     componentclass m_togglablecomponent; }  // somewhere else in codebase if (m_togglablecomponent.isactive()) {     // stuff }  // somewhere totally different in codebase if (m_togglablecomponent.isactive()) {     // different stuff }    

looks you're headed towards feature toggle. common occurrence when there's piece of functionality need able toggle on or off @ run time. key piece of insight approach use polymorphism instead of if/else statements, leveraging object oriented practices.

martin fowler details approach here, rationale: http://martinfowler.com/articles/feature-toggles.html

but quick answer, instead of having state in componentclass tells observers whether it's active or not, you'll want make base class, abstractcomponentclass, , 2 base classes activecomponentclass , inactivecomponentclass. bear in mind m_togglablecomponent automatic member, , you'll need make pointer under new setup.

abstractcomponentclass define pure virtual methods both need implement. in activecomponentclass put normal functionality, if enabled. in inactivecomponentclass little possible, enough make component invisible far mainclass concerned. void functions nothing , functions return values return neutral values.

the last step creating instance of 1 of these 2 classes. bring in dependency injection. in constructor mainclass, you'll take pointer of type abstractcomponentclass. there on doesn't care if it's active or inactive, calls virtual functions. whoever owns or controls mainclass 1 injects kind want, either active or inactive, read configuration or else system decides when toggle.

if need change behaviour @ run time, you'll need setter method takes abstractcomponentclass pointer , replaces 1 constructor.


Comments