November 22, 2010

The Difference Between a Property, Field, Attribute

Originally published 3 Aug 2007

I’ve been asked a similar question at least three times this year.  It goes something like, “What’s the difference between a field and a property?”  Or, “Is there a difference between an attribute and a property?”  Given that many inexperienced developers automatically generate getters and setters for all their fields, I can understand the confusion.

I always give them the example of a circle.  Here’s some Groovy code:

class Circle {
   def radius
   
   def getDiameter() {
      2 * radius
   }
   
   getArea() {
      Math.PI * Math.pow(radius, 2)
   }
   
   def getCircumference() {
      2 * radius * Math.PI
   }
}

radius is a field, also known as an instance variable, also known as a member variable in C++.  It’s an implementation detail of the Circle, i.e., it’s a private variable that gets stored as part of the Circle object.

Properties are more public aspects of an object.  In Java, following JavaBeans conventions for getters and setters allows you to expose properties.  Those properties don’t have to be backed up by fields, but in many cases are.

Coming back to the Groovy Circle, what are its properties?  We’ll you get radius for free as a read-write property.  But because we’ve got some getters that compute other values based on radius, we also have diameter, area, and circumference properties.  These happen to be read-only properties since we didn’t provide setters, but we could have (which would update the radius field accordingly).  You can dump all of a Circle object’s properties in Groovy like this:


println myCircle.properties

The point is Circle could be implemented in different ways: by using a diameter field instead of radius, for instance, but it would have the same properties.

Now, let’s talk about attributes.  I typically think of UML when I hear attributes.  Here’s UML for Circle:



Notice that I’ve distinguished the derived diameter, area, and circumference attributes with a “/”.  This is standard UML.  radius is a regular, non-derived attribute.  We can distinguish fields from other computed properties like this.  However, because we’re modeling, and thinking in a higher level of abstraction, I like to think of attributes as more synonymous with properties.  I’d rather not make the assumption that every attribute is implemented with a field.

A similar discussion of these terms can be found here.

1 comment:

  1. I like ones own post. Her wonderful view you probably discuss through written text aided by the cardiovascular in addition to a resolution you can fundamental situation might be successfully visited. https://rafleys.com

    ReplyDelete