tcepsa: (Default)
[personal profile] tcepsa
If you program, please only use code to toggle things back and forth when you're absolutely certain that you want something to be the opposite of what it was. For example (completely hypothetical, of course) say you have graphical image that you sometimes want to display and sometimes want to hide. Let's also say you have a toggle function which will hide it if it is showing and show it if it is hiding.


That's all well and good, but there is only one type of situation in which I can think that would be appropriate, and that would be the situation where you can say "At this point I don't care what it was before, but I want it to be the other way now!"

Never assume that you already know what state it is in unless you just checked it, but if you're doing something like "if it is visible, then toggle it" when you want to hide it you should probably two different chunks of functionality designed specifically to hide it or show it in those situations where you know you want it definitely to be turned on or definitely to be turned off.

Yes, it is possible to use just the toggle function and get the results you want, but it requires extremely rigorous analysis of the rest of the program to be certain that it will never accidentally end up turning it off when it was supposed to be turned on (and even then, you probably can't be 100% sure that it will work every time--what if there was some incredibly obscure state that you didn't think of but which could, under just the right circumstances, occur?)

But possible and easy, efficient, and least-stressful are not always the same thing. If you want it hidden, don't call the toggle function and hope that it was visible (or do the extra work of checking whether to see that it's visible and then call the toggle function) or just call the hide function. Setting it to hidden twice won't make it more hidden (at least not if it's a binary state thing, which it should be if you're thinking about using a toggle in the first place), but it will guarantee that it is exactly where you want it.


Take control of your program. Don't be subject to its fickle nature. Put it in its place!

We now return you to your irregularly scheduled WootOff

Date: 2006-10-14 12:13 am (UTC)
From: [identity profile] wanderingghost.livejournal.com
Why ever would you not check current (starting) state? Should be a simple "if" function.....

Sounds like an interesting back story to that little code lesson. ::grin::

Profile

tcepsa: (Default)
tcepsa

April 2015

S M T W T F S
   12 34
567891011
12131415161718
19202122232425
2627282930  

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 19th, 2025 05:05 pm
Powered by Dreamwidth Studios