必须按特定顺序调用的方法的命名约定?
我有一个类,需要按特定顺序调用它的一些方法。如果这些方法被乱序调用,那么该对象将停止正常工作。方法中有一些断言来确保对象处于有效状态。我可以使用什么命名约定来与下一个阅读代码的人沟通,这些方法需要按特定顺序调用?
可以将其变成一个巨大的方法,但是巨大的方法是制造问题的好方法。 (有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是否可以重构,以便(至少部分)第一个函数的状态作为参数传递给第二个函数,那么这是无法避免的?
否则,如果你有评论和断言,那么你就做得很好了。
然而,“有可能将其变成一个巨大的方法”听起来像是外部代码不需要以任何方式访问中间状态。如果是这样,为什么不只创建一个公共方法,依次调用多个私有方法呢?类似于:
这并不完美,但如果顺序集中到该一个函数,那么很容易看出它们应该按什么顺序排列。
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:
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.
消息摘要和加密/解密例程通常有一个
_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.