Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Simplify Callback Dispatching with Enumerated Indexes-4 : Page 4




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

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.



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