5 ms·
In languages without property support, reflexively writing getters and setters is the only way to make it possible to go back later and add logic to getting and
by whatshisface 6y ago
In languages without property support, reflexively writing getters and setters is the only way to make it possible to go back later and add logic to getting and setting without changing the callsites. Is this a workaround for the combined shackles of mismanaged enterprise environments where changing callsites is impossible for some reason, and legacy language environments where you have to use Java for some reason? Yes, of course. But sometimes you need a workaround.
- slver 6y agoThe real question is why is the convention getFoo() setFoo(foo) and not foo() and foo(foo).
- whatshisface 6y agoNot all languages have overloading.
- slver 6y agoI'm referring to Java.
- whatshisface 6y agoI think the pattern was adopted from languages before Java which didn't have overloading.
- swsieber 6y agoIt makes for easier searching in small code bases with stuff like grep instead of needing full language server / ide support.
- commandlinefan 6y ago> go back later and add logic to getting and setting Which, realistically, you're virtually never going to do - at least not often enough to justify the boilerplate and especially in the case of things like "records" which were probably auto-generated from a schema (with obligatory getters and setters) anyway. If you did, you'd end up confusing all of your callers who probably wrote client code presuming that what they provided in the setter was going to be exactly what they get back in the getter.
- kmonsen 6y agoAgree, for a lot of code you can be pretty sure it will not change. And you should be able to refactor your code base, if not there are larger issues. In general I subscribe to the at first make it as simple as possible, when you have two examples of it being too simple it is time to refactor. Of course when creating libraries it is different. In that case to protect users on the API surface and try to make that stable.
- t-writescode 6y agoThis is true, until you're writing a library that's pulled from a repository and used in several projects. If you can't guarantee you're not going to break someone else's code by changing: foo.x to foo.getX(); then you should stick with properties. Now, for staying inside a single package, or a single compiled unit, then what you say is reasonable enough. I'd still prefer to write the getters and setters, though, especially in cases where it's free, like Kotlin.
- commandlinefan 6y agoIt would be better if the default were to not write setters or getters for any properties by default, but instead to write a logical interface that properly encapsulates the properties. Unfortunately, that ship sailed a long time ago for Java.
- slver 6y agoIt actually happens a lot for me.