class setter's behavior is ambiguous
The value assigned to setter is returned as it is,
Let me take a very inconvenient example. (the sample from [refactoring 2th - 7.3])
class Order{
constructor(data = {priority: "normal"}){
this._priority = new Priority(data.priority);
}
set priority(aString){this._priority = new Priority(aString);}
}
class Priority{
constructor(value){
if(value instanceof Priority) return value;
if(Priority.legalValues().includes(value)) this._value = value;
else console.error(`<${value}> is invalid for Priority`);
}
toString() {return this._value;}
get _index() {return Priority.legalValues().findIndex(s => s === this._value);}
static legalValues() {return ['low', 'normal', 'high', 'rush'];}
equals(other) {return this._index === other._index;}
higherThan(other) {return this._index > other._index;}
lowerThan(other) {return this._index < other._index;}
}
The problem arises with the Client
(new Order().priority = 'normal').priority.higherThan(new Priority("low"));
this code's result is 'undefined' because new Order().priority = 'normal'
return 'nomal'
But.
let orderSet = new Order();
orderSet.priority = "high";
orderSet.priority.higherThan(new Priority("low"));
it's work.
Do you guys agree how uncomfortable and unnatural this is?
AND,
I put the return code in Order Class
class Order{
constructor(data = {priority: "normal"}){
this._priority = new Priority(data.priority);
}
set priority(aString){this._priority = new Priority(aString); return this;}
}
highlight again
set priority(aString){this._priority = new Priority(aString); return this;}
In this statement, return is ignored.
I think this behavior is the same as inducing the writing of bad code like the one below.
class Order{
constructor(data = {priority: "normal"}){
this._priority = new Priority(data.priority);
}
setPriority(aString){this._priority = new Priority(aString); return this;}
}
Client
(new Order().setPriority('normal')).priority.higherThan(new Priority("low"));
This works the way i want
You must make it possible to remove or overwrite the return statement of the set. I think it's better to have no return statement