views:

35

answers:

3

Hello,

Class could have static, private, 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.

A: 

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
Paul McKenzie
A: 

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.

VinayC
A: 

If you have the need to organize the order of methods in your class, I'd say you're doing something wrong.

Franco
certainly a large number of methods in a class is a code-smell, but even with three or four, it makes sense to be consistent in the order in which they appear.
Paul McKenzie