Usefulness of Toggle functions

江枫思渺然 提交于 2019-12-10 20:02:55

问题


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:


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




回答2:


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.



来源:https://stackoverflow.com/questions/2632270/usefulness-of-toggle-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!