Properties vs. Attributes

You have a class object. it will have methods and routines in it, right? Well if you have a class variable (like an integer, an array, or another object) you can declare it as private, public, friend, and so on. Those would be attributes. Attributes are the class's variables. Properties would be directed ways of interacting with attributes (class variables).

See when I build a class all my class variables are declared private. I don't want someone else mucking around undirected with my attributes (variables). However I *do* want them to use be able to access them so I build properties that limit how and what a user can do to the variable.


When talking about Object Oriented design, attributes and behaviors are more concepts than language constructs. For such design considerations, only the public elements of an object need generally be considered. Or protected, when you get to inheritance.

Consider the following:

1 class Point {
2     public int X, Y; // attribute
3     public Point(int x, int y) {
4         this.X = x;
5         this.Y = y;
6     }
7     public void moveX(int diff) { this.X += diff; } // behavior
8 }


An object variable can be considered an attribute by it's nature. However, it's considered  very  bad practice to ever expose variables to the public. What if you want to put a rule on the max value of x? How do you impose that on a variable? Remember, one of the big reasons to use OO techniques is to limit the impact of future changes.

01 class Point {
02     private int x, y;
03     public Point(int x, int y) {
04         this.x = x;
05         this.y = y;
06     }
07     public int getX() { return this.x; } // attribute
08     public int getY() { return this.y; } // attribute
09     public void moveX(int diff) { this.x += diff; } // behavior
10 }


Now the only exposed elements of this object are methods. It's a little awkward, but it's good practice. Functionally, X is readonly. To make it read write, we can add a setX method. "Getters and setters" are part of a Java best practive for attributes. But they aren't implicit, they just follow a naming convention. In C# we can use a elegant solution: Properties.

01 class Point {
02     private int x, y;
03     public Point(int x, int y) {
04         this.x = x;
05         this.y = y;
06     }
07     public int X { get { return this.x; } set { this.x = value } } // attribute
08     public int Y { get { return this.y; } } // attribute ( read only )
09     public void moveX(int diff) { this.x += diff; } // behavior
10 }


With the properties we can give object attributes in a natural way. The following example works with the first class and the last one:
1 Point pt = new Point(2,3);
2 pt.X = 5;


For a program, a Property actually feels like a variable, serves as an OO attribute, and has the functionality of a method.

Hope that made some sense

你可能感兴趣的:(Properties vs. Attributes)