开发者

Class Design - Member variables and properties - Declaration

开发者 https://www.devze.com 2023-03-01 07:31 出处:网络
In my quest to develop some coding \"best practices\" for myself I would like to ask people how they arrange class member variables and getter/setter properties within their class definition. I have s

In my quest to develop some coding "best practices" for myself I would like to ask people how they arrange class member variables and getter/setter properties within their class definition. I have seen it done two ways ...

开发者_JAVA技巧

(1) Declare class member variables at the top of the class ad then in a seperate section declare the properties that get/set those member variables.

Class MyClass
{
  String firstName;
  String lastName;

  public string FirstName
  {
    get { return firstName; }
    set { firstName = value; }
  }

  public string LastName
  {
    get { return lastName; }
    set { lastName = value; }
  }

}

(2) Declare class member variables at the top of the class and define the get/set properties right below the variable declaration.

Class MyClass
{
  String firstName;
  public string FirstName
  {
    get { return firstName; }
    set { firstName = value; }
  }

  String lastName;
  public string LastName
  {
    get { return lastName; }
    set { lastName = value; }
  }

}

Though it may be a matter or personal preference which pattern do people tend to follow and if possible, please give a reason as to why. Thanks.


If you're not doing anything in the property get/sets, use auto-properties, you can always change them later if you need to:

public string LastName {get;set;}

Personally, I like to put all of my member variables at the bottom of the class, following the principle that the stuff clients are interested in (i.e. the public stuff) should be located nearer the top of the file. Lots of people seem to prefer having the members at the top, but it's always seemed a bit backwards to me :)


I prefer option number 1, and then I surround fields in a Fields region, properties in Properties region, constructors, methods, etc, etc. The regions of course allow you to collapse parts of the code to further improve readability (if you only want to look at the constructors for example).

Just a personal preference, but makes classes nicely organized.


Though it's down to personal preference, I prefer option 1, but with the private members at the bottom. Reasoning: API is more important than implementation:

class MyClass
{
  public string FirstName
  {
    get { return firstName; }
    set { firstName = value; }
  }

  public string LastName
  {
    get { return lastName; }
    set { lastName = value; }
  }

  String firstName;
  String lastName;
}
0

精彩评论

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