4 ms·
In my experience, in quite big projects, people had a tendency to mutate objects in the wrong place and in the wrong reasons. A field encapsulated in a getter w
by tigershark 10y ago
In my experience, in quite big projects, people had a tendency to mutate objects in the wrong place and in the wrong reasons.
A field encapsulated in a getter without setter certainly helps.
- chopin 10y agoThat would be a final field. But generally I agree with you and its by far the pattern I use most.
- kuschku 10y agoThe issue is, for example, if you have for example a class encapsulating a bunch of flags, and allowing the user to either set each flag seperately, or a bitfield representing all of it. In C, you might be able to do some magic, but in Java, you’ll need setters and getters there – you can’t even do final fields there. Luckily, in C#, you can just use accessors, and maybe in Java with Lombok, too.
- qwertyuiop924 10y agoBut if it has to be able to be mutated in some cases, you're stuck. This is a place where Scheme's parameterize may be useful: Define a closure with the setter in scope, and write it so that when it's called with a lambda as an arg, it will raise an error unless those certain conditions are met, in which case, it will use parameterize to make the setter available in the lambda's scope. Or I suppose it could pass it in, which would be slightly simpler...