4 ms·
I had the same question -- why accessor methods instead of making the fields public, but final. If anything, it seems like a layer of indirection. The only ans
by legerdemain 5y ago
I had the same question -- why accessor methods instead of making the fields public, but final. If anything, it seems like a layer of indirection.
The only answer that makes any sense is this one from Brian Goetz.[1] Namely, that it's a workaround to support mutable fields of otherwise immutable objects.
To be honest, allowing you to override the methods on an immutable, auto-generated class to inject custom accessor logic feels like an immediate retreat from the conceptual goal of providing an immutable record implementation in the first place.
[1] https://stackoverflow.com/questions/66702223/why-do-java-records-have-accessor-methods-instead-of-public-final-fields/66704373#comment117935348_66704373 https://stackoverflow.com/questions/66702223/why-do-java-rec...
- skinkestek 5y ago> why accessor methods instead of making the fields public, but final. The best explanation I have is that it is: - a convention that seemed like a good idea for many people at the time, it even has a name: Javabeans - it allows for a standard non magic way to add logic to be run when reading or updating fields - in a time where source control tools and Java refactoring tools where not as developed as they are today it made sense to make getters and setters everywhere since changing from public fields to accessor methods after it were already in use was probably scary for large teams.
- legerdemain 5y agoThanks for your speculation, but I'd rather take Brian Goetz's word for it. He is, after all, one of the architects of the Java language and the records feature in particular. ...Unless you're Brian Goetz's alt account?
- skinkestek 5y ago> Unless you're Brian Goetz's alt account? I have a policy of saying whether if is true or false. That said you should take his word for why it was designed that way and my word as an historical account of why I did that in 2005-2015.