views:

138

answers:

2

I just can across some code where they've got an implicit setter, but no getter eg:

public class Person {

    //no getter!

    public function set food(value:Food):void {
        // do something with food.
        this.processFood(value);
        this.dispatchEvent(new Event(FoodEvent.EATEN));
    }
}

This smells bad to me. Hacky. What do you think?

edit: Perhaps my issue with write only is that in my experience properties are generally read/write, and unless it's blatantly obvious by the variable name or well documented, it might be confusing as to why the property is write only.

+2  A: 

Generally, there's nothing wrong with set-only properties in OO design. You might use setters to implement dependency injection when you can't inject in the constructor. Setters can help you to break dependency cycles. I would go further and say that there is nothing wrong with set-only properties in other contexts as well, but I know that is a contentious issue.

In this case, as Stefan said, it really ought to be called eatFood.

Daniel Yankowsky
Thanks, that sounds about right to me.
secoif
+1  A: 

One guideline to help you structure you classes has to do with whether you are talking about verbs/actions executed by your objects or the characteristics that describe them. Actions usually are best described by methods while characteristics are best described by properties. The problem with this code is not that it is using a set only property, which as mentioned is perfectly valid, but that it is using a property where it should be using a method.

Julio Garcia
I agree. Thanks
secoif