Best practice: ordering of public/protected/private within the class definition?

后端 未结 10 1318
遥遥无期
遥遥无期 2020-12-12 14:34

I am starting a new project from the ground up and want it to be clean / have good coding standards. In what order do the seasoned developers on here like to lay things out

10条回答
  •  伪装坚强ぢ
    2020-12-12 14:51

    I think I have a different philosophy on this than most. I prefer to group related items together. I can't stand having to jump around to work with a class. The code should flow and using a rather artificial ordering based on accessibility (public, private, protected etc. ) or instance versus static or member versus property versus function doesn't help keep a nice flow. So if I nave a public method Method that is implemented by private helper methods HelperMethodA, HelperMethodB etc. then rather than have these method far apart from each other in the file, I will keep them close to each other. Similarly, if i have an instance method that is implemented by a static method, I will group these together too.

    So my classes often look like this:

    class MyClass {
        public string Method(int a) {
            return HelperMethodA(a) + HelperMethodB(this.SomeStringMember);
        }
    
        string HelperMethodA(int a) { // returns some string }
    
        string HelperMethodB(string s) { // returns some string }
    
        public bool Equals(MyClass other) { return MyClass.Equals(this, other); }
    
        public static bool Equals(MyClass left, MyClass right) { // return some bool }
    
        public double SomeCalculation(double x, double y) {
            if(x < 0) throw new ArgumentOutOfRangeException("x");
            return DoSomeCalculation(x, y); 
        }
    
        const double aConstant;
        const double anotherConstant;
        double DoSomeCalculation(double x, double y) {
            return Math.Pow(aConstant, x) * Math.Sin(y) 
                + this.SomeDoubleMember * anotherConstant;
        }       
    }
    

提交回复
热议问题