Browse DevX
Sign up for e-mail newsletters from DevX


Simplify Callback Dispatching with Enumerated Indexes-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Demonstrating the Problem
Suppose you're developing a graphical mail client that displays "Send," "Reply," etc. icons. A typical design consists of a GUI layer (which I will not discuss here) and an engine that intercepts a click on an icon and dispatches a callback function to perform the requested operation. The callback functions are typically stored in an array of pointers to member functions. For example:

class Mail //a set of operations associated with icons { public: int Send(); int Reply(); int Forward(); int Delete(); };

To avoid the unwieldy syntax of pointers to members, I will use the following typedef:

typedef int (Mail::*mail_pmf)();

Finally, the array of pointers to members is defined and initialized like this:

mail_pmf options[4]= {&Mail::Send, &Mail::Reply, &Mail::Forward, &Mail::Delete};

When the user clicks on the "Send" icon, the event-dispatcher launches the callback function stored in options[0]; clicking on "Reply" causes the dispatcher to launch options[1] and so on:

enum Icons { IC_Send = 10, IC_Reply = 20, IC_Forward = 30, IC_Delete = 40, IC_Help = 50 }; Mail mail; //object used by dispatcher switch (icon_val) { case IC_Send: dispatch(mail, options[0]); break; case IC_Reply: dispatch(mail, options[1]); break; case IC_Forward: dispatch(mail, options[2]); break; //.. }

Even in such a simple example, the use of numeric indexes is a recipe for human errors and maintenance problems. Who can guess what options[1] contains? What if the programmer mistakenly places two identical indexes in two different case blocks?

case IC_Forward: dispatch(mail, options[2]); break; case IC_Delete: dispatch(mail, options[2]);//oops! should be options[3] break;

Detecting such bugs (which are common in IDEs that support copy and paste) isn't always easy. Furthermore, it makes code maintenance difficult. What if you decide to add more operations such as "Save" and "Print"?

Obviously, forcing programmers to remember by heart which array element is associated with which operation is a bad idea.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date