6 ms·
Sorry to ask, but as a noob who just picked up Java, how do other languages address this issue? What's wrong with getters and setters?
by memonkey 12y ago
Sorry to ask, but as a noob who just picked up Java, how do other languages address this issue? What's wrong with getters and setters?
- hugozap 12y agoFor c# just: public int Age{get;set;} no need to declare private variable, get or set methods.
- Tloewald 12y agoAnd you can replace it with a virtual property in the future (changing the underlying implementation) without breaking anything. And user code ends up simpler and more readable too: foo.baz += foo.bar; vs. foo.setBaz( foo.getBaz() + foo.getBar() );
- HanyouHottie 12y agoThat example reminds me of this recent post on The Old New Thing: http://blogs.msdn.com/b/oldnewthing/archive/2014/08/14/10549885.aspx http://blogs.msdn.com/b/oldnewthing/archive/2014/08/14/10549... Interesting behavior.
- Tloewald 12y agoOf course, setters don't protect you from this either.
- redtrackker 12y agoWhat's wrong with getters and setters? It's just redundant code. Most of the time developers don't actually need to override the basic get/set operation on a variable. Yet you have to write the get/set methods over and over. How do other languages address this issue? Scala does a good job. You don't need to actually write a get/set method. But if you wanted to modify getFoo() you would simply implement the method with your custom getter
- deleted 12y ago[deleted]
- deleted 12y ago[deleted]
- Tloewald 12y agoThe purpose of a getter or setter is to abstract the implementation out from the usage. Computed properties (e.g. C#'s ability to replace a concrete property with a virtual property without breaking any code) do this without requiring mindless implementation (boilerplate code) for the common case (a property that is exactly what it seems to be). As an added bonus, you don't need to write foo.getBar(), you can just write foo.bar and it Just Works, whether foo.bar is a concrete implementation or a computed property. Look at this blog post for example: http://java.dzone.com/articles/java-properties-without http://java.dzone.com/articles/java-properties-without The sad thing is the request here is for something more ugly than what is really wanted (this is just automatic getter/setter implementation -- computed properties are better both for developers and consumers of their output.
- bassman7755 12y agoThe problem is that you cant add computed accessor methods to java without breaking code backwards compatibility. This is because a public fields and a public methods have different inheritance semantics - public field access does not trigger polymorphic resolution. Hence auto replacing it with a access method would break any code that relies on the static resolution of the public field (i.e. resolution by referencing type). To fair there probably isnt much code out there that would fall foul of this since there isnt any good reason to write code that relies on public field "hiding" by subclasses, but it would be technically non backwards compatible.
- aikah 12y agoC# introduces the concepts of fields and properties. I dont remember which is which but I think properties are in fact getters and setters,without the verbose "object.getProperty()" syntax , you just write "object.property" and it's call a getter function or a setter function. Basically you keep states encapsulated without have to manually write methods,you just write methods when you need then. Java verbosity on that matter is totally unecessary. Granted when one use an IDE refactoring features can help,but still... A great strenght of the Java language is its stability.But stability doesnt mean a language needs to be that verbose.
- pjmlp 12y ago> C# introduces the concepts of fields and properties. This goes back to at least Eiffel (1985).
- TylerE 12y agoIn python the default is that things that look like attributes/properties REALLY are direct access. If you later need to shim them out into a function you use the @property decorator (and foo.setter if you need read/write) class Blah(object): foo = 2 # A normal property. Direct access @property def bar(self): return self.some_lookup_method() @bar.setter def bar(self, value): self.set_the_bar(value)
- rch 12y agoThanks for mentioning this. I've found the Python approach works really well in practice.
- mythz 12y agoIMO Dart has the best implementation of properties, which you can start out as normal fields, e.g: class Rectangle { num left, top, width, height, right bottom; } and can access like normal: var height = rect.bottom - rect.top; But can later be changed into a computed property without affecting the above callsites, e.g: class Rectangle { num left, top, width, height; num get right => left + width; set right(num value) => left = value - width; num get bottom => top + height; set bottom(num value) => top = value - height; } C# is a close 2nd, but it's not binary (or reflection) compatible to change from a field to a property for call-sites (i.e. it's only source-compatible).
- mateuszf 12y agoafaik scalas properties are as good as in case of dart. Also, operations like + are also normal methods on numbers.
- srgpqt 12y agoRuby is quite similar. attr_accessor :left, :top, :width, :height, :right, :bottom And you can change these to computed properties (regular methods) later without affecting the callsites
- tieTYT 12y agoWhy does it matter if it's binary compatible? How does that affect the programmer? I guess I don't understand the difference/significance between binary and source compatibility? I'm surprised to hear that it's not reflection compatible. As a Java programmer, I assumed that was the main point of C# properties: Create a property now because there's no logic needed, but if you need logic in the future you can change the code and nobody outside needs to be aware of the change.
- mythz 12y agoBinary compatibility is important when accessing properties of a type defined in another Assembly, i.e. if an Assembly was updated where a Field was changed to a Property it would break access from dependent Assemblies. In .NET Reflection, Fields and Properties have distinct API's, i.e. fields can be accessed with `type.GetFields()` and properties with `type.GetProperties()`. The API's are basically wrappers around how they work, i.e. Fields let you get/set an instance's field value whereas with Properties you're instead invoking the properties getter/setter method accessors.
- muchabi 12y agoTo add another example to the list, Ruby lets you list which attributes can be read/written and which ones can only be read on top. Something like. class Car attr_reader :model, :company # only read attr_accessor :color # read and write end
- dopamean 12y agoIt's worth noting that in Ruby the difference between attr_reader and attr_writer is not the same as read only and write only. You can write to something set with attr_reader. All attr_writer does is allow complete reassignment of that particular instance variable. This is pretty trivial so bear with me... If you have something that looks like this... class Person attr_reader :children def initialize @children = [] end end You can then do this... x = Person.new x << "Bobby" You will have then altered the value of @children without completely reassigning it.
- malisper 12y agoThe problem with getters and setters is that the code for them is nearly identical, yet they have to be written in nearly every single class: // Sorry if there are any mistakes, I have not // written any Java code for quite some time. public class Point { private int x; private int y; . . public int getX() { return x; } public int getY() { return y; } public void setX(int newX) { x = newX; } public void setY(int newY) { y = newY; } } Look at how long the class definition is for something so basic! In Common Lisp there are two ways to define classes/structures, defstruct and defclass. Defstruct[0] automatically automatically defines everything for you: (defstruct point x y) will define the procedures make-point, point-x, point-y, (setf point-x), and (setf point-y). The cool thing is that they are all procedures. It easily change the class definition without changing the code that uses it. There are also some additional options for defstruct to specify default values, how to print the structure, as well as what prefix to use (the default is the name of the structure, 'point' in this case). Defclass[1], while much more verbose than defstruct, is much more powerful: (defclass point () (x :writer set-x :initarg :x) (y :reader get-y :initarg :y) (z :accessor z)) will define procedures, set-x, get-y, z, and (setf z). Set-x and (setf z) are the setters, while get-x and z are the getters. To construct a point that is defined this way, one has to use the procedure make-instance which will take keyword parameters[2] :x and :y, for x and y respectively. [0] http://www.lispworks.com/documentation/lw445/CLHS/Body/m_defstr.htm [1] http://clhs.lisp.se/Body/m_defcla.htm [2] http://www.gigamonkeys.com/book/functions.html