英文:
Manipulate struct directly or via return
问题
我注意到在编写golang时,我在以下问题上不一致:在方法中,是直接通过结构体本身来操作结构体,还是通过返回值来操作结构体,哪种方式更好?由于这个问题听起来很愚蠢,这里有一个例子:
直接操作结构体
http://play.golang.org/p/7G5D8Pm5wv
通过返回值操作
http://play.golang.org/p/L9Z_t7pA8b
请解释为什么一种尝试比另一种更好。如果两种方式都不正确,请给出一个可以接受的示例。
提前感谢!
英文:
I noticed that I am not consistent when writing golang regarding the following question: Is it better to manipulate a struct in its methods via the struct itself directly or by using return? Since this question sounds stupid, here's an example:
Manipulate a struct directly
http://play.golang.org/p/7G5D8Pm5wv
Via return
http://play.golang.org/p/L9Z_t7pA8b
Please explain why one attempt is better than the other. An if both somehow wrong, please give an example that would be ok.
Thanks in advance!
答案1
得分: 2
我认为这取决于你如何使用你的结构体。如果你将其用作对象,即有接收器的函数,我认为你应该使用函数来操作状态(结构体的字段)。如果你纯粹将结构体用作数据存储,那么直接操作字段似乎更合适。
阅读《Clean Code: A Handbook of Agile Software Craftsmanship》(《代码整洁之道:程序员的职业素养》)罗伯特·C·马丁著,第6章“对象和数据结构”。
在谷歌上搜索这本书,你会找到在线版本。
还有,可以参考德米特法则(Law of Demeter)。
英文:
I think it depends on how you use your struct. If you use it as an object i.e. there function with receivers of that type I think you should manipulate the state (the fields of the struct) with functions too. If you use the struct purely as a data store, then manipulating the fields directly seems more OK.
Read
Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin, chapter 6 on Objects & Data structures
Google for that book and you will find online versions.
and
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论