Main Contents

Getter and Setters in Ruby verus Java

software development

I came across a post on a Ruby feature that Todd Huss would like to see in Java:

Native getter/setter support: declaring a list of variables as attr_reader or attr_writer allows getter/setter functionality of a variable without writing/maintaining any redundant getter/setter code, yet if necessary, you can override the default getter/setter behaviour without affecting the API. In Java it drives me crazy that we waste time and clutter our classes unnecessarily with hundreds of lines of getter/setter methods that all do the same thing. Java really needs a construct for default getter/setter behaviour on selected variables that can be overriden when necessary.

I agree that all the clutter and extra lines from getter/setter methods are really annoying within Java code. My preference though is to simply drop the getter/setter methods altogether and make the variable public. Better yet keep it private and don’t expose it to anything, it should be data only the class makes use of to implement behavior.

Allen Holub has an article entitled Why Getters and Setters Are Evil that argues that the getter/setter idiom in java is really not a good idea. If you haven’t read it basically it argues that the getter/setter methods are procedural hangovers that should largely be abandoned.

I remember back when I taught an Intro to Java course or two that there was a wonderful discussion of encapsulation and that one of the examples were the getter/setter methods that encapsulated the private variables. Everytime I covered this topic I felt it was a really weak argument. If you have a private instance variable, but then you just implement default public getter/setter methods, esentially you’re making the variable public again. If that’s the case why not just use the dot syntax and make the instance variable public.

Holub talks about this in his article, but the obvious thing is that the getter/setter paradigm has become standard in Java both by procedural programmers who were used to objects that look like just collections of data and by the default JavaBean implementation. Indeed I occasionally try to leave off getter/setter methods only to find in many frameworks like Struts, Spring, and others that they assume they can use reflection and the get/set methods to implement functionality.

I sat through a session as SD 2005 this year and found Allen’s presentation pretty refreshing since he was taking on established practices in Java. What was amazing was the amount of flak he took for bringing this up from much of the audience.

Anyway I still end up implementing a lot of get/set methods since a lot of frameworks require it, even if it isn’t very object oriented.

Ed Gibbs @ July 13, 2005

2 Comments

  1. Todd Huss July 15, 2005 @ 11:05 pm

    The disadvantage of making a variable public in Java is that you have no option to override the functionality at a later date without breaking the API. For example I may introduce a public variable called yards in my first naive implementation but then later decide that my underlying implementation should be metric because I want to internationalize it. With getters/setters ala Ruby you can easily have default getter/setter behaviour with no code initially that simply sets the “yards” variable without writing any code. Then you can later override the yards setter to convert the value to metric while keeping a backwards compatible API. In Java to get this same flexibility we have to fully implement the getter/setter manually from the get go.

  2. Indrek Altpere March 11, 2008 @ 4:02 pm

    After I have been coding in C#, I just don’t get it why Java as a language does not alrady have some special property type construct.

    The meaning of getter and setter methods were meant to make things easier (easier to change implementations etc). But having them as simple regular methods makes some things actually worse. For example, you cannot use short operands (++, –, +?, -=, *=, /=, &=, |= etc) with them at all.

    For example obj.var += 3; when used with current developer-invented “getter/setter”, you will have to write obj.setVar(obj.getVar() + 3); and as for ++ for example, you’d still write obj.setVar(obj.getVar() + 1).

    No offense, the idea of setter/getter is good, but just the current implementation (invented by developers and not officially a language construct at all) is way too poor and tedios and too verbose. You have to write too much code to make simple += 3; And here I thought that those short operands were made to make life easier, but now it seems that current getter/setter methodology stips off all of those short operands :(

    Not to mention that sometimes people tend to name get methods of boolean fields with “is” prefix instead of “get” and thus making things even more complex (data type based methodname prefixing).

    And reflectioning is not so good either, since the getter/setter arent native language stuff but rather just “reinvented methods”. If you know a fieldname (myField), to get the value with reflection, you have to convert first char to uppercase (no uppercasefirst function in java, you need to reinvent it or download some 3rd party library specially for it :P). Then prepend “get” string to it and try to find a methos with the name you just conscructed that has no parameters. And if you’re not reflecting your classes, to be sure, you may need to check with “is” prefix also. same uppercasefirst, prepend-”set” logic applies to setters.

    All that constant first car upper/lower and then prepending stuff, is too tedious for such a modern language in my opinion.

    For example properyes in C# (and also VB) are separate things, you have all the extensibility support plus you have the usage of all short operands (including equal sign). So writing +=3; for a property is just as simple and readable as it was meant to be in first place. Same goes for reflection, since properties are special objects, they can be gotten via reflection easily. Withoud any need to mess around with uppercase/lowercase and prefixing.

    I have asked around and told java developers the difference that is so obvios for me and asked their opinion about the matter.
    Two main answer types I have gotten:
    a) MS stinks, C# is MS poduct, ergo C# stinks and it’s property implementation stinks too plus using getField() and setField() like methods makes my program a true OOP program, not like C#
    b) my IDE can generate the getter and setter methods for me, so I don’t have to type them in myself at all

    My answers:
    a) try to code in one language and in the other, on the level of getter and setter, C# is far more convienient than java, and yes I do know that java runs on all op systems but that is lame excuse for defending the old way of getter and setter that make short operands obsolete and introduce way too much verbosity in your code
    b) well, visual studio can create the property nicely too, I type prop, select type, enter private field name, property name and done. Main point is still the incompatibility with short operators and not to mention the simple “=”.

    If setter and getter are meant to make some things easier (and they do in C#) then how come they don’t in java and why isn’t anything done about it ?
    Are the big decision makers realy of type a or b or worse, both ?

    Any one who has coded in C# can confirm that natively supporter properties are much better than reinventing them with some specifically named methods (which in my opinion is just a ugly hack, a workaround, but has somehow become very widespred).

    Of course, the problem with C# like properties in java is the naming convention in java, all methods and valiables need to start with lower case char, so you cannot use private int myInt; and expose it as a property named myInt at the same time, only viable solution would be to change naming convention so that properties would start with uppercase char or with underscore etc.

    Just a few thoughts that have been rolling around in my head for a while :)

Leave a comment


Feed