6

If we look at typical implementation of a Class, we usually see the private members defined at the beginning and public( mostly functions and Accessors) defined towards the bottom. Now, is this a Industry standard agreed by a lot of people?

How about keeping the private members towards the end as updates and additions are usually done to the Public Members(mostly functions), to fix bug or provide enhancement, so we don't have to scroll down towards the end to get to the function definition section.

I understand, good IDEs will allow us to Jump towards a specific attribute, but considering other factors, such as Code Review, it may be convenient to have the Public Definitions towards the beginning.

What is the most accepted standard for Class Member Organization?

6 Answers 6

3

so we don't have to scroll down towards the end to get to the function definition section

If you have so many private members in a class that you need to scroll down far, you might want to look at the design of the class. I don't think you'll find that the biggest problem is whether you placed the private members at the top or the bottom.

Or, to put it another way, if the sequence of definitions in your classes is really the biggest problem you have to solve then congratulations, you have a great code-base, and you should just get on and develop business functionality, rather than worrying about these kinds of details (which, as you point out yourself, your IDE worries about for you).

That said, if your private members are simply backing members for public properties then the simple answer, in later versions of C#, is auto-properties -- but if you need them then they're probably better hidden away at the bottom.

If you are using them to encapsulate abstract services, then I would prefer to see them at the top so that I know, as soon as I enter that class, what kind of dependencies it has.

3
  • I don't agree with the argument 'don't fix x because unrelated y is an issue', sort of like 'don't give starving animals food - there are humans that need medicine'. I sometimes have to open files where I for the moment can't access the rest of the project, but need to understand how the class is used. The mental jarring is often less if the public interface of the class is first. See @leos answer.
    – Max
    Commented Jan 4, 2012 at 10:09
  • 1
    @Max: I didn't say that I'd always apply 'don't fix x because unrelated y is an issue'. But you really do have to prioritise big problems, and business requirements, against small problems. This has to qualify as a small problem because you wouldn't find 10 randomly chosen developers who even agree on the 'right' way.
    – pdr
    Commented Jan 4, 2012 at 10:24
  • Of course, the old strawman argument ;) But I still think it's a worthwhile issue, since when writing new code it won't waste any time at all, really, if you just keep the convention in your mind. :)
    – Max
    Commented Jan 4, 2012 at 10:33
6

I put public methods at the top of my Class since public methods are the only entry points into encapsulated Class logic.

4

I think that the practice of declaring privates first and publics afterwards has been inherited from C. What usually happens is that publics refer to privates, but not the other way around, so you could not declare your publics first without using lots of highly inconvenient forward references. So, there is a long tradition of doing that, and people are used to it.

Of course, with modern languages like C# there is no reason for doing this any more.

That having been said, I feel compelled to add that I do not happen to be particularly fond of tradition.

2

In his book Clean Code Robert C. Martin argues that methods in a class should be order by the order of use in the class. That is start with a public method, then the private methods that public method uses in the order it uses them. The private methods used in the those private methods follow right after the method that uses them. Then the next public methods, followed by its associated private methods. That way, when reading a method, the other methods is uses are right below.

For this approach to be effective, though, classes really need to be small, and have a single responsibility.

1

I use the following breakdown and will try to justify it after the description.

<class>
members (as in vars)
  internal members
    internal const members
    internal static members
     internal static const members
  (repeat with public, protected, private)
properties (same as members)
  ...
ctors (internal, public, protected, private)
commands (ie void returns, or success or other returns that are not pure functions)
  (internal, etc)
event handlers
 control event handlers
 remote event handlers
 other event handlers
functions (ie queries)
 (internal, etc)

You will notice an indentation scheme applied here. This is to indicate the presence of what I call the structured comments template which is created first thing when the file is blank. What the comments do is give you proper indentation layout (for code folding) and slots where new members are inserted according to the given attributes.

Here is a peak at that in C#, though I also use it for other languages.

The top:

//# namespace
  // Z_DOT package UtilsCL ::UtilsWin32::UtilsCL:UtilsWin32.cs  z.6566885600116177.2009.04.27.14.18.06|package
    namespace UtilsCL{
      //#class
        // Z_DOT class UtilsWin32::UtilsWin32::UtilsCL:UtilsWin32.cs  z.3959885600116177.2009.04.27.14.18.09|static-class
           /// <summary>
           /// Win32 PInvoke
           /// </summary>
          // ReSharper disable ClassNeverInstantiated.Global
          public class UtilsWin32{
            // ReSharper restore ClassNeverInstantiated.Global
            // ReSharper restore UnusedMember.Global
            //#, members
                 // ReSharper disable UnusedMember.Local
                  /// <summary>
                  /// Does nothing
                  /// </summary>
                 private void __(){
                   // ReSharper restore UnusedMember.Local
                 }
              //#i, internal    members
                //;
                //#i*, internal static     members
                  //;
                  //#i*@, internal static const members
                    //;
                //#i@, internal const     members
                  //;
                //;

A midsection, note the comment:

//#-. private                      properties
  //;
  //#-*. private static     properties
    //;
    //#-*@. private static const properties
      // ReSharper disable InconsistentNaming
      // ReSharper disable UnaccessedField.Local
      #pragma warning disable 169
       /// <summary>
       /// Private Static Const Properties
       /// </summary>
      [SuppressMessage("Gendarme.Rules.Performance", "AvoidUnusedPrivateFieldsRule")]
      private static object __God_private_static_const_properties;
      #pragma warning restore 169
      // ReSharper restore InconsistentNaming// ReSharper restore UnaccessedField.Local
      #region "private_static_const_properties"
      // Z_DOT ppt  def:Set ::God::mrobbinsassoc::com::OmegaApp:God.cs  z.7121082100597177.2009.10.18.23.33.21|-*@.
         /// <summary>
         /// Gets the def.
         /// </summary>
         /// <value>The def. from Settings.Default</value>
        // ReSharper disable MemberCanBePrivate.Global
        private static Set def{
          // ReSharper restore MemberCanBePrivate.Global
          get{
            return Set.Default;
          }
        }
      //;                        //<====================== Insertion POINT
      #endregion
  //#-@. private const     properties

Now, for the promised justification, having member vars at the top is the programmers view of things obviously not the best for the client, but that is why we have Doc Tools right?

Keeping code as rigid as this I am sure has its benefits for doing diffs. Also the general layout forces you to think about the architecture you are building. During the workflow I am putting in those Z_DOT identifiers via a macro which relies on the fn sig to be present and proper, before I hit that macro I affirm that I am scoping the member correctly etc. "Is this really what I want to do" instead of just injecting code anywhere in the class where I happen to be sitting and then reordering it later (ie if I wasn't using such a strict system)

The main benefit is now I can write macros that address the code precisely, as well as create external analysis/refactoring/generation tools.

It is very useful to have this second-level breakdown of not only access modifier, but of var, property backer, properties, commands, events, and (pure) functions. It gives you a view-on-things and makes you think in terms of that view.

Wire up a few macros to take you to each insertion point in the file (which doesn't actually have that big arrow thing I put there to demo it) and you are good to go.

0

I think it has to do more on: how each developer like to organize the class members, based, on how it doing some class model in its mind.

Altought, its more common to start with the:

private
protected
public

sort order.

And, eventually mix each access, depending on what they are doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.