31 ms·
I've read a lot of documentation, and I've never been convinced. Maybe it's because I've just never been involved in writing a large Java project, and so never
by Sohcahtoa82 7y ago
I've read a lot of documentation, and I've never been convinced. Maybe it's because I've just never been involved in writing a large Java project, and so never seen the advantages?
Many other languages do just fine without them. What makes Java so different?
- ptx 7y agoOther languages (e.g. Python, C#, Kotlin, even old-school Visual Basic) have actual language support for getters/setters, usually called properties. What makes Java different is that they have properties as a concept (in the Java beans specification) but not as an actual language feature, so you have to implement them manually yourself for every field and every class. (Or let the IDE generate the code, but all that boilerplate is code that wouldn't need to exist in other languages.)
- thu2111 7y agoTwo things: 1. Many other languages let you redefine field assignment syntax to be a function call, which is basically what a 'property' is in Kotlin. Java doesn't. 2. The Java ecosystem distributes software in binary bytecode form and cares about binary/API compatibility. The combination of these two mean that even if you don't want to run any code on field assignment today, if there's any chance you might want it tomorrow you have to plan for it now by using functions instead of naked fields. Changing the latter to the former means updating all the use sites. The big win of language integrated properties is you can go from (in Kotlin): class Thing(val veryLongText: String) to class Thing(text: String) { val veryLongText by lazy { text.toLowerCase() } } without any of the places that use Thing.veryLongText noticing the difference. The first code just stores the string as an ordinary field. In the second, we've decided the text should actually be lower case and that lower-casing should be done on demand then memoized for efficiency. In Java, if you want to do that, you'd have needed to write a getVeryLongText() method from the start, as otherwise you'd have nowhere to add the extra code.