开发者

Sorting methods in class file by access modifiers [duplicate]

This question already has answers here: Order of items in classes: Fields, Properties, Constructors, Methods (16 answers) Closed 9 years ago.

Sorting methods in class file by access modifiers is good o开发者_开发问答r wrong habit?

Which are another methods for structure of class file?


The important thing with coding standards as that they are documented, well known by your team and that they are applied consistently.

It does also help if they aren't too "off-the-wall" compared to the coding standards adopted across the industry.

In this case, the company I am working at currently has a similar policy, which is the place the class in a particular order, with properties, constructors, public methods then private methods.

I have also worked in locations where the private methods are placed close the public methods that consume them - but I have to admit that this tends to get messy as the whole idea of extracting the logic into a separate method was to get re-use.


This is the sorting order that StyleCop uses (if I recall correctly):

  1. variables (All constant and readonly private fields must be placed before all non-constant, non-readonly private fields)
  2. constructors (static first)
  3. enums
  4. interfaces
  5. properties
  6. methods
  7. classes

Also:

  • Static members should always be placed before instance members of the same visibility.
  • Members should be sorted with: public before internal before protected before private.

Personally I removed the rule that static members should be placed before non-static members, because this often conflicts with good readability, because I like to be able to read my class like a book, but also like to adhere the rules of FxCop (yet another tool) that points me at instance methods that don't use the this argument.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜