Write-only accessors in Actionscript 3: Bad Practice?
I just came 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(F开发者_JAVA百科oodEvent.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.
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
.
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.
精彩评论