views:

63

answers:

2

Is it better to write functions that explicitly do something (i.e. HideForm/ShowForm etc...)

or is it better to write 'Toggle' type functions (i.e. ToggleVisibility)?

I find Toggle type functions awkard because it's hard to track the state by reading the code.

In what situations is a toggle type function useful?

+1  A: 

I use it sometimes in JavasScript to handle buttons( checkbox like ) and visibility, but mostly I avoid it, because it makes a little harder to control the state of the think you are trying to handle.

It can be bad if you are not or can't be sure of the initial state (but usually you can). Anyway, most of the cases require not some 'simetric' or simple code to be run, so I don't go for .toogle a lot

Fabiano PS
A: 

If the goal is readability, then use two separate functions.

We could have: ShowXYZ() and HideXYZ(), or ToggleXYZ(bool show). The latter would only show up in code as ToggleXYZ(true) or ToggleXYZ(false), making it somewhat unclear what each one does. Putting them as two separate functions leaves no guessing as to what the function is supposed to do.

I'm going to extend the question you asked a little bit, as there is another option. For the sake of extensibility in the case where there are two or more states, you can take advantage of the language you're using (I'm giving examples in C#, so YMMV).

So in the case of C#, you can create an enum to provide the different states and add readability to your code. You could have something like:

SetXYZState(XYZState.Show)

or

SetXYZState(XYZState.MakeWaffles)

which is very clear while using the same function signature.

This could be applied to a situation where you'll only ever have two states (or even just one if you might extend it later), but the overhead in getting it set up is probably more work than simply writing two functions.

Jon Seigel