45

There seem to be many different ways of organizing methods in a class. I could group methods by access, and order them alphabetically. I could group related methods together. I could use a mix of the two, or something else entirely. Is there a standard way to approach this? If not, how do you approach it?

Matthew
  • 28,056
  • 26
  • 104
  • 170

12 Answers12

54

StyleCop enforces some things here:

Within a class, struct, or interface, elements must be positioned in the following order:

  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Furthermore, elements are ordered by access:

  • public
  • internal
  • protected internal
  • protected
  • private

As well as a few other rules:

  • Contants have to appear before fields
  • static elements have to appear before instance elements.

This might be a good baseline to start. As for additional ordering rules, I usually group related methods together.

Community
  • 1
  • 1
Joey
  • 344,408
  • 85
  • 689
  • 683
  • 1
    This is exactly what I was looking for. Is `#region` recommended to separate each of these areas, or is that considered over-using `#region`? – Matthew Jan 28 '10 at 16:49
  • Interesting. I do the top 3, element ordering, and putting constants and static elements first by habit, but not the others. – Powerlord Jan 28 '10 at 16:50
  • 1
    I used to use a lot of #regions in my code, for the code-folding function in VS. But inevitably I would end up removing them because it's just a pain to not be able to quickly scan my code if everything is folded up. Eventually I just gave up on it. Your mileage may vary. – Doug R Jan 28 '10 at 17:02
  • I hate how regions collapse by default, and the only choice you have is either 1) have them collapse by default or 2) have them not just stay open, but also not have any of the little boxes available to manually collapse things. First thing I do with `#region` marked code is remove them all. – Sam Harwell Jan 28 '10 at 17:05
  • 1
    @Doug: Even if you don't use cold-folding, `#region` is nice for letting you jump around your code quickly (at least in MonoDevelop, I assume VS does the same thing). – Matthew Jan 28 '10 at 17:06
  • 2
    Honestly, I find regions visual noise and a code smell. They hide code from sight. Why is the code hidden? From what I've seen it's to make the class more navigatable. I'm all for organizing your classes, but if you can't open your favorite IDE and see how the code is organized, the class is too large and more than likely needs to be broken down into smaller components. – Chuck Conway Jan 28 '10 at 17:22
  • @Rob: Wow, that command is pretty terribly named. Sounds like it would invert it - regions expanded by methods collapsed. I'll still prefer ordering my file structure to using regions, but this gives me a workable solution when i'm having to deal with code from other people. – Sam Harwell Jan 28 '10 at 17:26
  • 10
    #regions were created to hide auto-generated code. Partial classes achieve that now. I think they obfuscate more than help. There's plenty of find functionality in dev tools. #regions are just clutter, imho. – Jeff Yates Jan 28 '10 at 17:32
  • I'm now facing a dilemma with static methods. If you have them first, they get away from their caller methods too easy, thus breaking the vertical distance practice. Best to have the public static ones first, and keep the other static ones close to their callers as usual. – Alexandre Fernandes May 30 '18 at 14:07
  • @AlexandreFernandes, That sounds like a good solution. For static helper methods that are used only by another method you can also employ nested methods these days. – Joey May 30 '18 at 14:20
  • @Joey, yeah, I've been trying Local Functions out to compensate for these situations. Just keep in mind you can still have private static methods called more than once, thus this would not work. But I've not found a way of using Local Functions without cluttering the parent method yet. – Alexandre Fernandes May 30 '18 at 14:44
7

Whatever you do, put it in your standards and be consistent. We use a custom Regionerate configuration to order our methods. Everyone on the team uses the same configuration.

EDIT: We're now using ReSharper's Code Cleanup with a custom Type Members Layout.

TrueWill
  • 25,132
  • 10
  • 101
  • 150
5

I use NArrange which does most of the things I want: Group fields, methods... alphabetically and by access modifiers. It also enforces some Style Cop rules (e.g. order of element types, location of using statements). NArrange is configurable to quite some degree, you do not have to live with the default configuration if you do not like it.

Update: Now I use Resharper since NArrange does not work correctly with newer C# syntax.

Stefan Egli
  • 17,398
  • 3
  • 54
  • 75
2

I do not order them by access modifier, nor do I order them alphabetically. (I think this is quite a burden when you add or rename a method in that class ... ).

If necessary, I group them by functionality. I mean: I put related methods toghether.

But, if you follow the SRP (Single Responsability Principle), then I think that ordering methods is in most of the circumstances a non-issue; since, when you follow SRP, your classes wouldn't have very much methods.

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
2

I group my methods by their access modifier 
and in the following sequence:

  • public
  • internal
  • protected internal
  • protected
  • private

1

Since Visual Studio has tools for navigating quickly to methods by name, I prefer to put private member variables and constructors close to the top and group methods by functionality (ie, helper methods are close by to the methods that call them). I also group properties together. If a class becomes substantial, I make use of #region directives to show the organization.

plinth
  • 48,267
  • 11
  • 78
  • 120
1

I tend to find grouping of related methods far more useful when reading someone else's source code, than some arbitrary pseudo-order such as alphabetical.

Although the book is specifically about Java, Uncle Bob's Clean Code contains some excellent general principles for readability in OO classes. In particular, he uses the metaphor of a well-written newspaper article, with a headline at the top followed by a synopsis paragraph and then increasing detail as you read further down the article. By aiming for a similar top-down structure in your classes, it makes the task of reading or understanding your code much easier for others.

Phil Booth
  • 4,853
  • 1
  • 33
  • 35
0

No, most people just group methods by logical similarity, or not at all. It doesn't really matter - classes shouldn't get too big, and with a decent IDE you can just ctrl+click to goto to any method definition anyways.

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
  • it is `F12` in visual studio 2010 – chouaib Nov 28 '14 at 05:32
  • I recently faced this issue. I use regions to sort my code by "group methods and logical similarity". I believe this is easier to follow. However I've been reading about some standards and got stuck.So if if should keep every function in its own method; how can I follow my code faster and maintain it? I ended up with tons of methods (even though was trying to avoid creating too many) and ended up in a hard time to follow the code. Having every function in its own method seems counter productive. –  Apr 27 '18 at 09:06
  • @RicardoGarcia: Generally the things you are separating into different regions should instead be separated into different classes. I don't know what you mean by "every function in its own method" - a "method" is by definition "a function inside a class" – BlueRaja - Danny Pflughoeft Apr 27 '18 at 16:21
0

I suggest first grouping by interface they come thru, with a nice comment saying the interface name - because these are non-obvious.

Then, by relation, and only then sorting alphabetically.

Use a lot of blank lines to reduce the reader's cognitive load.

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67
0

I group my method by functionality, ranging from most generic to most concrete, all that inside a region, so I can hide unnecessary details.

Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
0

Microsoft's StyleCop tool does a nice job of defining element order within a class. You can also write extensions to the tool to conform to your company's coding standards. That being said, StyleCop is a good starting point.

Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87
0

I'm not sure there's a consistently standard way... but I group related methods together, perhaps sub-grouped by accessor. Makes it the easiest for finding related things later down the track.

LJW
  • 2,378
  • 1
  • 21
  • 35