Don't implement functionality in built-in events


Link to this posting

Postby Ursego » 19 Feb 2013, 22:29

If the functionality is longer than a few lines then don't implement it in system (built-in) events (Clicked, ItemChanged etc). Instead, extract the fragments to brand new well-named functions and call these functions from the built-in events.

It's ok to call two or three functions from a system event, but if the script grows and begins to have its own logic then... it becomes "implementing functionality" and, therefore, needs to be extracted into a dedicated function. Many times I called such function following the pattern uf_itemchanged__<col name> (with two underscores), like uf_itemchanged__birth_date and uf_itemchanged__country_id. In fact, the built-in events are only traffic hubs for routing the program flow to different functions using choose case construction (the only exception is when the code is simply a few lines), so it's absolutely ok to end up with many uf_itemchanged__XXX functions. It will be very convenient to concentrate on what happens when user changed birth_date without seeing in the same script the processing of absolutely unrelated country_id.

Advantages:

1. A function name tells the code reader which task is performed by the piece of code (like uf_print_bill). The name of a built-in event doesn't convey this information (like Clicked - you need to investigate the code to figure out what the script does).

2. If a built-in event should perform more than one logical task then implementing each task in its own function will conform to the best coding practices. As the topic Keep functions simple says, Divide your program into short methods that perform one identifiable task ("separation of concerns").

3. One day that functionality can need to be called from another place. Calling a well-named function is not only more elegant (you should NEVER call built-in GUI events unless you're using call super from a descendant) but also enables developers to add arguments, which is impossible with the built-in events. Today the required functionality is identical (so, no arguments are needed), but sooner or later it can branch - why not to prepare the ground in advance to facilitate future work?

4. Someone will write the ancestor's ButtonClicked script, thinking it's only going to fire when user clicks the button. But, in fact, it can be called programmatically as well - by a developer who didn't read the previous paragraph. Then you'll end up with some spaghetti solution to keep track of whether this is a non-button-clicked ButtonClick... :twisted: Ufffffff!
User avatar
Ursego
Site Admin
 
Posts: 131
Joined: 19 Feb 2013, 20:33



IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:




cron
free counters

eXTReMe Tracker