views:

415

answers:

13

I'm a bit confused as to why languages have these. I'm a Java programmer and at the start of my career so Java is the only language I've written in since I started to actually, you know, get it.

So in Java of course we don't have properties and we write getThis() and setThat(...) methods.

What would we gain by having properties?

Thanks.

EDIT: another query: what naming conventions arise in languages with properties?

A: 

Not having to write 'get'!

Andy Mikula
+2  A: 

Two reasons:

  1. Cleaned/terser syntax; and
  2. It more clearly indicates to the user of the class the difference between state (properties) and behaviour (methods).
cletus
I don't understand your point 2 - in C# for example, can't you have arbitrary code in properties?
Yes, but by convention you don't. See http://stackoverflow.com/questions/601621/properties-vs-methods/601648#601648
cletus
@cletus: hehehe quite an useful construct recommended not to use. Well still if it's available it could prove handy ( and abused )
OscarRyz
+7  A: 

Which one looks more natural to you?

// A
person.setAge(25)
// B
person.age = 25;
// or
person.Age = 25; //depending on conventions, but that's beside the point

Most people will answer B.

It's not only syntaxic sugar, it also helps when doing reflection; you can actually make the difference between data and operations without resorting to the name of the methods.

Here is an example in C# for those not familiar with properties:

class Person
{
    public int Age
    {
        set
        {
            if(value<0)
                throw new ArgumentOutOfRangeException();

            OnChanged();
            age = value;
        }

        get { return age; }
    }

    private int age;
    protected virtual void OnChanged() { // ... }
}

Also, most people always use properties rather than promote a public member later for the same reason we always use get/set; there is no need to rewrite the old client code bound to data members.

Coincoin
The part on reflection is right on. It's also semantically more significant to have a property reflecting data of the object.
Bruno Lopes
@COincoin: Why don't just public members? BTW it should still be person.age not person.Age
OscarRyz
public members don't give you the ability to perform validation
TofuBeer
@Oscar...not necessarily...most C# style guides (that I have seen) use "Age" (Pascal casing) for properties, rather than "age" (Camel casing).
Beska
@Beska the question is posted in Java tags not C# tags... naming convention for Java is age.
TofuBeer
@Beska: Yeap, but this is java. I mean, in C# methods names start with uppercase. I mean, it will be better just to keep consistency.
OscarRyz
@TofuBeer: Yes that's what I'm reading on your answer. The validation could be as complex as needed isn't? gee..
OscarRyz
A rather simple and useful example of reflection is XMLEncoder/XMLDecoder. Now you can create save files which are backward and forward compatibile.
Brian
@Oscar and Tofubeer: Updated my answer to address your concerns.
Coincoin
+4  A: 

The syntax is much nicer:

button.Location += delta;

than:

button.setLocation(button.getLocation() + delta);
Jordan Miner
+2  A: 

In Java the getters and setters are in essence properties.

In other modern languages (c#) , etc it just makes the syntax easier to work with/comprehend.

They are unnecessary, and there are workarounds in most cases.

It's really a matter of preference, but if the language you're using supports them I would recommend using them :)

Chris Klepeis
+1  A: 

I struggled with this at first, too, however I've really come to appreciate them. The way I see it, properties allow me to interact with the exposed data in a natural way without losing the encapsulation provided by getter/setter methods. In other words, I can treat my properties as fields but without really exposing the actual fields if I choose not to. With automatic properties in C# 3.0 it gets even better as for most fields -- where I want to allow the consumer to read/write the data -- I have even less to write:

public string Prop { get; set; }

In the case where I want partial visibility, I can restrict just the accessor I want easily.

public string Prop { get; private set; }

All of this can be done with getter/setter methods, but the verbiage is much higher and the usage is much less natural.

tvanfosson
A: 

You can also create derived fields and read-only/write-only fields. Most Properties that I've seen in languages I've worked in allow you to not only assign simple fields, but also full functions to properties.

Chris J
+6  A: 

Edit:

The code below assumes that you are doing everything by hand. In my example world the compiler would generate the simple get/set methods and convert all direct variable access to those methods. If that didn't then the client code would have to be recompiled which defeats a big part of the purpose.

Original:

The main argument for properties is that it removes the need to recompile your code if you go from a variable to a method.

For instance:

public class Foo
{
    public int bar;
}

If we later decided to validation to "bar" we would need to do this:

public class Foo
{
    private int bar;

    public void setBar(final int val)
    {
        if(val <= 0)
        {
            throw new IllegalArgumentException("val must be > 0, was: " + val);
        }

        bar = val;
    }

    public int getBar()
    {
        return (bar);
    }
}

But adding the set/get method would break all of the code. If it was done via properties then you would be able to add the validation after the fact without breaking client code.

I personally don't like the idea - I am much happier with the idea of using annotation and having the simple set/get geterated automatically with the ability to profive your own set/get implementations as needed (but I don't like hidden method calls).

TofuBeer
This would only work if properties are part of bytecode. If it is just syntactic sugar you still need to recompile. C# properties for example are pure syntax and actually create a 'get_prop' type methods. If you change from field to property there, a recompile is still required.
DefLog
Surely with properties the client code still needs to be recompiled (just not rewritten)?
@Deflog beat me to it
Since you mentioned annotations I'm hyping for my hops of getting @Get, @Set and @GetSet (... :)) annotations. Those would mean no need for additional syntactic sugar!
Esko
Esko - the @Get/etc... annotations still don't allow you to pass the property around. You wind up having to pass strings around which makes code fragile and refactoring very error prone.
Kevin Day
imagine you declare an instance variable like "@readonly property int foo; (property would be new keyword). That would have the compiler spit out a getMethod (no set) and since it has the property keyword it would turn all .foo into a call to .getFoo().
TofuBeer
+1  A: 

A general rule of object oriented programming is that you never change an existing interface. This ensures that while in inner content may change for the objects calling the object don't need to know this.

Properties in other languages are methods masquerading as a specific language feature. In Java a property is distinguished only by convention. While in general this works, there are cases where it limits you. For example sometimes you would to use hasSomething instead of isSomething of getSomething.

So it allows flexibility of names, while tools and other code depending on can still tell the difference.

Also the code can be more compact and the get and set are grouped together by design.

DefLog
A: 

Properties provide a simple method to abstract the details behind a set of logic in an object down to a single value to the outside world.

While your property may start out only as a value, this abstraction decouples the interface such that it's details can be changed later with minimal impact.

A general rule of thumb is that abstraction and loose coupling are good things. Properties are a pattern that achieve both.

another average joe
+1  A: 

In Object Oriented Software Construction 2 Bertrand Meyer calls this the "Uniform Access Principle" and the general idea is that when a property goes from a simple one (i.e. just an integer) to a derived one (a function call), the people using it shouldn't have to know.

You don't want everyone using your code to have to change from

int x = foo.y;

to

int x = foo.y();

That breaks encapsulation because you haven't changed your "interface" just your "implementation".

Justus
A: 

Properties at the language level are a bad idea. There's no good convention for them and they hide performance deficits in the code.

Dan Howard
A: 

It's all about bindings

There was a time when I considered properties to just be syntactic sugar (i.e. help the developer by having them type a bit less). As I've done more and more GUI development, and started using binding frameworks (JGoodies, JSR295), I have discovered that language level properties are much, much more than syntactic sugar.

In a binding scenario, you essentially define rules that say 'property X of object A should always be equal to property Y of object B'. Shorthand is: A.x <-> B.y

Now, imagine how you would go about actually writing a binding library in Java. Right now, it is absolutely not possible to refer to 'x' or 'y' directly as language primitives. You can only refer to them as strings (and access them via reflection). In essence, A."x" <-> B."y"

This causes massive, massive problems when you go to refactor code.

There are additional considerations, including proper implementation of property change notifications. If you look at my code, every blessed setter requires a minimum of 3 lines to do something that is incredibly simple. Plus one of those 3 lines includes yet another string:

public void setFoo(Foo foo){
  Foo old = getFoo();
  this.foo = foo;
  changeSupport.firePropertyChange("foo", old, foo);
}

all of these strings floating around is a complete nightmare.

Now, imagine if a property was a first class citizen in the language. This starts to provide almost endless possibilities (for example, imagine registering a listener with a Property directly instead of having to muck with PropertyChangeSupport and it's 3 mystery methods that have to get added to every class). Imagine being able to pass the property itself (not the value of the property, but the Property object) into a binding framework.

For web tier developers, imagine a web framework that can build it's own form id values from the names of the properties themselves (something like registerFormProperties(myObject.firstname, myObject.lastname, someOtherObject.amount) to allow for round-trip population of object property values when the form is submitted back to the server. Right now to do that, you'd have to pass strings in, and refactoring becomes a headache (refactoring actually becomes downright scary once you are relying on strings and reflection to wire things up).

So anyway, For those of us who are dealing with dynamic data updates via binding, properties are a much needed feature in the language - way more than just syntactic sugar.

Kevin Day