开发者

In what order do you put methods in class code?

开发者 https://www.devze.com 2023-01-11 13:36 出处:网络
Class could have static, private开发者_如何学Go, protected, public methods. Each method is made for modifying, adding, removing etc.

Class could have static, private开发者_如何学Go, protected, public methods. Each method is made for modifying, adding, removing etc.

How do you group functions in class's code to make it clean to read? What is the best practices?

Thank you.


This is how I do it for Java classes:

  1. constructors
  2. public methods from implemented interfaces
  3. public methods overridden or methods declared abstract from extended classes (not Object, see below)
  4. public methods (other than getter/setter/Object methods)
  5. getters and setters, in the order the property is declared
  6. equals, hashCode and toString
  7. private methods
  8. public static methods


One convention need not fit all scenarios - typically, in our team, we use C# and we use "region" for grouping private fields, static members, private methods, constructors, protected methods and public methods. Order doesn't matter much because VS can collapse all regions nicely giving a summary view. Sometimes, we also use "overrides" and/or "virtual" regions. It also depends upon the complexity of the class in question. For few complex classes, you will even find regions based on functionality. For example, all "Parsing" stuff (variables, private methods, public methods involved in parsing) would be together under one region. In the end, goal is to have readable (maintainable) code and "consistency" would be one of the tool for that - as long as team understands this, there shouldn't be any issues.

0

精彩评论

暂无评论...
验证码 换一张
取 消