Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Simplify Callback Dispatching with Enumerated Indexes-3 : Page 3


advertisement
Enumerating Options
Using an enum for binding meaningful names to numeric values is an ideal solution to this problem. However, it has to be done carefully. The first step is to define an enumeration that lists all the possible operations:

enum mail_ops { send, reply, forward, delete };

Remember to leave all enumerators without an explicit initializer. This way, the compiler automatically assigns consecutive numbers to each enumerator starting with 0, i.e., send=0, reply=1 etc. Secondly, provide a final enumerator after all the valid operations:

enum mail_ops { send, reply, forward, delete, max_mail_ops //always should be the last };

Author's Note: I deliberately defined an independent enum for the operations instead of reusing enum Icons because there are icons for which class Mail doesn't define an operation, "Help" for instance. Furthermore, mail_ops adheres to stricter definition rules. Therefore, it's best to use separate enums for the icons and the operations.



The last enumerator contains the total number of operations, which is handy for declaring an array of callbacks:

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

This makes your code more resilient to changes. If, for example, you decide to add more operations:

enum mail_ops { send, reply, forward, delete, save, //newly added max_mail_ops };

max_mail_options will be adjusted automatically to 5, as would the number of elements in the array. Of course, the new elements must be initialized appropriately:

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



Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap