I have a function to show or hide a certain UI control. In my example case below, the framework is jQuery I'm using for an event to show a tool tip that may fire a LOT (based on mouse movements) - but the underlying problem is more general and may also arise in a similar manner in lots of other UI frameworks. In fact, the problem could be even more generalized to any kind of component with two states to be switched often, not just UI components.
Consider:
Code A:
$(this).plothover(function(item) {
if(item&&item!="undefined"){
show tooltip
}
else
remove tooltip
});
Code B:
$(this).plothover(function(item) {
if(item&&item!="undefined"){
show tooltip
}
else {
if(tool tip is shown){
remove tooltip
}
}
});
item
will exist at defined Cartesian points where datapoints exist (ie, graph coordinates on a canvas). In other words, the odds are ~10000:1 in the favor of the else condition firing on a DPI
basis.
As the mouse moves,
Code A removes it with no regard to any condition Code B only removes it if it was already created, but has to test the creation first
So, which is considered 'right'? Blind hide the control whether it is visible or not, or only hide it if it is visible?
I've benchmark'ed it through jsperf and the differences are negligible performance wise but does lean towards the blind destroy. But if it's 'wrong' by theory to do it, i'd rather chose the best practice route.
--- EDIT --- To clarify, The actual invocation is not important (ie, how is it removed). Nor am I looking for a code review. The above given example is one of many times I've run into this case.
Rather, I wish to discuss the theory involved in "Destroy what may exist" or "search and destroy if it exists".
style.display = 'none'
, yes? I would prefer the first option, just because it makes for shorter code, but I don't think there are any clear-cut arguments for either case here. In some other case, where the "remove" operation is not idempotent, or would throw an exception, you would of course have to test before removing.