2

Just curious to know what difference does it make if one uses a setter function or a property to set a value? Which of the above two should be preferred?

column.setWidth(10);
column.width = 10;
Surily
  • 121
  • 2
  • 10
  • possible duplicate of [Why use getters and setters?](http://stackoverflow.com/questions/1568091/why-use-getters-and-setters) – wingerse Dec 28 '14 at 11:19

2 Answers2

2

Well, that largely depends on what programming language you are using, or, in other words, whether it supports the concept of properties or not. However, lets look at the problem from a general perspective.

The very basic point of view is properties are just plain syntactic sugar, making reading and writing values to some assumed backing field easier and, which is the important point, defining a clear contract for your code's user. Assumed because there needs not be any backing field at all or they can be many.

The high-level semantic difference between a setter function and a native property setter can be thought as follows:

  • A setter function is primarily still a function, hence the reader assumes it executes certain action using its arguments; being actually a setter is then just a convention.
  • A native property setter is primarily a way to write a value into some assumed backing storage / into the backing object; there's no implied notion of executing an action even though the hidden implementation details of the setter may work like that.

Many practicle ramifications of using property accessors (getters and setter) were discussed in this question and its answers.

Community
  • 1
  • 1
Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
0

Prefer properties. Actually it depends on your language. If you develop Python that all attributes are public in Python.

previousdeveloper
  • 315
  • 2
  • 6
  • 12