切换功能的用处

发布于 2024-08-28 22:38:21 字数 168 浏览 2 评论 0原文

是编写显式执行某些操作的函数(即 HideForm/ShowForm 等)更好

,还是编写“切换”类型函数(即 ToggleVisibility)更好?

我发现 Toggle 类型函数很尴尬,因为很难通过阅读代码来跟踪状态。

切换类型函数在什么情况下有用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

卸妝后依然美 2024-09-04 22:38:21

我有时在 JavasScript 中使用它来处理按钮(如复选框)和可见性,但大多数情况下我会避免使用它,因为它使控制您正在尝试处理的想法的状态变得有点困难。

如果您不确定或不能确定初始状态(但通常可以),那可能会很糟糕。不管怎样,大多数情况不需要运行一些“simetric”或简单的代码,所以我不会经常使用 .toogle

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

命硬 2024-09-04 22:38:21

如果目标是可读性,则使用两个单独的函数。

我们可以有:ShowXYZ()HideXYZ(),或ToggleXYZ(bool show)。后者只会在代码中显示为 ToggleXYZ(true)ToggleXYZ(false),这使得每个人的作用有些不清楚。将它们作为两个独立的函数,就不会猜测该函数应该做什么。

我将稍微扩展一下您提出的问题,因为还有另一种选择。为了在有两个或多个状态的情况下的可扩展性,您可以利用您正在使用的语言(我在 C# 中给出示例,所以 YMMV)。

因此,对于 C#,您可以创建一个 enum 来提供不同的状态并增加代码的可读性。你可以有类似的东西:

SetXYZState(XYZState.Show)

或者

SetXYZState(XYZState.MakeWaffles)

在使用相同的函数签名时非常清楚。

这可以应用于只有两种状态的情况(或者甚至只有一种,如果您以后可能扩展的话),但是设置它的开销可能比简单地编写两个函数更多。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文