必须按特定顺序调用的方法的命名约定?

发布于 2024-11-18 12:07:47 字数 250 浏览 4 评论 0原文

我有一个类,需要按特定顺序调用它的一些方法。如果这些方法被乱序调用,那么该对象将停止正常工作。方法中有一些断言来确保对象处于有效状态。我可以使用什么命名约定来与下一个阅读代码的人沟通,这些方法需要按特定顺序调用?

可以将其变成一个巨大的方法,但是巨大的方法是制造问题的好方法。 (有 2 个方法可以触发此序列,因此 1 个巨大的方法也会导致重复。)

可以编写注释来解释需要按顺序调用这些方法,但注释不如明确命名的方法有用。

有什么建议吗?

I have a class that requires some of its methods to be called in a specific order. If these methods are called out of order then the object will stop working correctly. There are a few asserts in the methods to ensure that the object is in a valid state. What naming conventions could I use to communicate to the next person to read the code that these methods need to be called in a specific order?

It would be possible to turn this into one huge method, but huge methods are a great way to create problems. (There are a 2 methods than can trigger this sequence so 1 huge method would also result in duplication.)

It would be possible to write comments that explain that the methods need to be called in order but comments are less useful then clearly named methods.

Any suggestions?

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

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

发布评论

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

评论(2

被你宠の有点坏 2024-11-25 12:07:47

是否可以重构,以便(至少部分)第一个函数的状态作为参数传递给第二个函数,那么这是无法避免的?

否则,如果你有评论和断言,那么你就做得很好了。

然而,“有可能将其变成一个巨大的方法”听起来像是外部代码不需要以任何方式访问中间状态。如果是这样,为什么不只创建一个公共方法,依次调用多个私有方法呢?类似于:

FroblicateWeazel() {
   // Need to be in this order:
   FroblicateWeazel_Init();
   FroblicateWeazel_PerformCals();
   FroblicateWeazel_OutputCalcs();
   FroblicateWeazel_Cleanup();
}

这并不完美,但如果顺序集中到该一个函数,那么很容易看出它们应该按什么顺序排列。

Is it possible to refactor so (at least some of) the state from the first function is passed as a paramter to the second function, then it's impossible to avoid?

Otherwise, if you have comments and asserts, you're doing quite well.

However, "It would be possible to turn this into one huge method" makes it sound like the outside code doesn't need to access the intermediate state in any way. If so, why not just make one public method, which calls several private methods successively? Something like:

FroblicateWeazel() {
   // Need to be in this order:
   FroblicateWeazel_Init();
   FroblicateWeazel_PerformCals();
   FroblicateWeazel_OutputCalcs();
   FroblicateWeazel_Cleanup();
}

That's not perfect, but if the order is centralised to that one function, it's fairly easy to see what order they should come in.

仅冇旳回忆 2024-11-25 12:07:47

消息摘要和加密/解密例程通常有一个 _init() 方法来进行设置,一个 _update() 来添加新数据,以及一个 _final() 返回最终结果并再次将其拆除。

Message digest and encryption/decryption routines often have an _init() method to set things up, an _update() to add new data, and a _final() to return final results and tear things back down again.

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