dth42345 2014-04-07 16:43
浏览 7
已采纳

直接或通过返回操作结构

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条回答 默认 最新

  • doubi9531 2014-04-07 17:13
    关注

    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

    http://en.wikipedia.org/wiki/Law_of_Demeter

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改