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-4 : Page 4


advertisement
enums Will Save the Day
The most important contribution of this technique is in the event-dispatcher. Instead of using meaningless numbers as array indexes, you can now use mnemonic enumerators:

switch (icon_code) { case IC_Send: dispatch(mail, options[send]); break; case IC_Reply: dispatch(mail, options[reply]); break; case IC_Forward: dispatch(mail, options[forward]); break; //.. case IC_Save: dispatch(mail, options[save]); break; case IC_Help: showOnlineHelp(); break; }

As a bonus, detecting typos is much easier now:

case IC_Save: dispatch(mail, options[save]); break; case IC_Print: dispatch(mail, options[save]);//a typo!

But That's Not All!
enum types offer two benefits over const int values: they automatically assign consecutive values to enumerators and they are strongly typed. Thus, if you declare a function that returns an enum:


mail_ops getUserClick();

The compiler can easily catch silly mistakes like this one:

mail_ops getUserClick() { return 20; //error }

Some compilers are even clever enough to warn about missing enumerators in a switch statement.



Danny Kalev is a system analyst and software engineer with 13 years of experience, specializing in C++ and object-oriented analysis and design. He is a member of the ANSI C++ standardization committee and the author of ANSI/ISO C++ Professional Programmer's Handbook (Que, 1999, ISBN: 0789720221). Reach him at dannykk@inter.net.il.
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap