by HumanDrivenDev · 9y ago · 0 comments
I'm open to the idea that setters do have a use case, but I'm not seeing one here.
class Satellite {
Coordinates coordinates;
double celcius;
/*** constructors, etc ***/
public double Celcius() { ... }
public double Kelvins() { ... }
public void Move(...) { /* modifies state */ }
}
Note how none of the methods make any mention of low level operations like setting/getting internal fields.You could make the argument that I do have a getter there, Celcius. But at the risk of pedantry I'd argue it isn't so. The name doesn't imply that it's retrieving the value of a field - ie the internal representation could easily change to Kelvin or Fahrenheit - where as "getCelcius" definitely tells me there's a field there called Celcius.
Hmm, after writing that I wonder what the definition of a setter actually is. I have no problem with a method that just returns a field, as long as it doesn't go out of its way to tell me that's exactly what it's doing. Maybe the distinction I am making is too subtle.
Properties in C#, for example, really just remove the ambiguity in this exact situation. Is it object.Celcius or object.Celcius()? A good C# programmer would use the former. A method would be object.RaiseTemp().
Writing the that example in C#, you'd likely have
public double Kelvins {get; set;};
public double Celsius {
get { ... };
set { ... };
}
and [modern] Javascript could have let kelvins;
get celsius() { ... };
set celsius(c) { ... };
And you'd set both of them with [eg] s.celsius = 5. This is how getters/setter look when a language supports them.Writing and using methods named 'getX' and 'setX' is conventional in Java because support for this feature doesn't exist at the language level, but is essentially implemented by the common IDEs. Probably not the ideal situation, but that's where Java is at.