方法命名约定
如果一个方法采用类/结构作为输入参数,那么最好的命名方式是什么?
示例:
class Person{}
class Address{}
class Utility{
//name **style 1** - use method overloading
public void Save(Person p){}
public void Save(Address a){}
*//name **style 2** - use unique names that define what they are doing
//or public void SavePerson(Person p){}
//and public void SaveAddress(Address a){}*
}
我个人喜欢样式 1(使用语言功能 - 在本例中为重载)。 如果您喜欢样式 1,您能给我指出任何表明这是标准的“官方”文档吗?
If a method takes a class/struct as an input parameter, what is the best way to name it?
Example:
class Person{}
class Address{}
class Utility{
//name **style 1** - use method overloading
public void Save(Person p){}
public void Save(Address a){}
*//name **style 2** - use unique names that define what they are doing
//or public void SavePerson(Person p){}
//and public void SaveAddress(Address a){}*
}
I personally like style 1 (Use the languages features - in this case overloading).
If you like style 1, can you point me to any "official" documentation, that states this to be a standard?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说你的挑战不在于方法命名领域,而在于类型设计。负责保存 Person 对象和
Address
对象的类型看起来像是带有 不止一项责任。这种类型往往会不断增长,最终变得难以维持。如果您创建更专业的类型,方法命名可能会自动成为一项更简单的任务。如果您仍然想以同一类型收集这些方法,这主要是风格问题。也许需要考虑的一件事是这种类型是否可以被用另一种语言编写的代码使用,并且不支持方法重载。在这种情况下,最好使用较长的名称。否则,就坚持感觉最好的方式(或者你工作场所的主导惯例)。
I would say your challenge is not in the field of method naming, but rather type design. A type that is responsible for saving both
Person
objects andAddress
objects seems like a type with more than one responsibility. Such a type will tend to grow and grow and grow and will eventually get hard to maintain. If you instead create more specialized types, method naming may automatically become a simpler task.If you would still want to collect these methods in the same type, it's mostly a matter of style. One thing to perhaps think about is whether this type may be consumed by code written in another language, and that does not support method overloading. In such cases the longer names is the way to go. Otherwise just stick to what feels best (or whatever is the ruling convention at your workplace).
这是风格问题。
如果您不喜欢长方法名称,请选择 1。
如果您不喜欢长重载列表,请选择 2。
重要的是保持一致,因此不要在一个项目中混合两种样式。
如果您发现有很多这样的方法,您可能需要重新考虑您的设计 - 也许涉及继承的解决方案会更合适。
It is a matter of style.
If you don't like long method names, go with 1.
If you don't like long overload lists, go with 2.
The important bit is to keep consistent, so do not mix the two styles in one project.
If you are seeing that you have many such methods, you may need to rethink your design - perhaps a solution involving inheritance would be more appropriate.
不同的名称完全避免了与方法重载相关的任何问题。例如:
还值得一问的是,是否可以使用多态性来代替重载。
Distinct names avoid entirely any problems associated with method overloading. For example:
It would also be worthwhile to ask whether polymorphism could be used instead of overloading.