What Properties in Java Should Have Looked Like

There’s an awful lot of sound and fury right now about adding syntax support for properties to Java 7. However, all the proposals are vastly too complex for what little benefit they offer. They need new keywords, operators, rules, and best practices. Could we have done better? Yes. Can we still do better? Maybe. Let’s find out.

The proper design of properties was invented in Eiffel over a decade ago, (or possibly some other language, but Eiffel is where I first saw it) and it’s really simple and obvious. All you need are public fields.

Oh my god! Public fields! The ultimate evil of object oriented programming that will bring about chaos, catastrophe, and the heat death of the universe! He can’t be possibly be serious, can he? Well, yes I can, because public fields don’t have to be bad.

Why Public Fields Are Bad

First, you have to understand the real problems with public fields. There are at least two. First you can’t change the implementation without breaking all client code. For example, suppose you have a Point class like this one:

public class Point {

  public double x;
  public double y;

}

Now suppose later you discover that the points are occupying quite a lot of memory, and you don’t really need the extra precision of a double, so you’d rather use floats instead. You can’t. You’re stuck with doubles because that’s part of the interface. But suppose instead you had added an additional layer of indirection with getter and setter methods like so:

public class Point {

  private double x;
  private double y;

  public double getX() {
    return this.x;
  }

  public double getY() {
    return this.y;
  }

  public void setY(double y) {
    this.y = y;
  }

  public void setX(double x) {
    this.x = x;
  }

}

Then you can easily change the private implementation while keeping the public interface the same, like so:

public class Point {

  private float x;
  private float y;

  public double getX() {
    return this.x;
  }

  public void setX(double x) {
    this.x = (float) x;
  }

  public double getY() {
    return this.y;
  }

  public void setY(double y) {
    this.y = (float) y;
  }

}

The second, even more important problem with public fields is that you can’t check constraints. For example, suppose you have the very reasonable constraint that the x and y fields of a point can’t be NaN or Inf. If the fields are public there’s nothing to prevent anyone from doing this:

p.x = 7.5/0.0;

However if the fields are private the constructors and setter methods can enforce any such constraints, like so:

  public void setY(double y) {
    if (Double.isInfinite(y)) {
      throw new IllegalArgumentException("Infinite magnitude");
    }
    else if (Double.isNaN(y)) {
      throw new IllegalArgumentException("Not a number");
    }
    this.y = y;
  }

Using setter and getter methods instead of public fields enables you to both change the internal implementation without breaking client code and to check constraints.

What Java Should Have Done About Public Fields

Can we add this ability to public fields? Yes. We simply have the compiler recognize that if there’s a setter, then p.x = 5 is really just a call to p.setX(5). I.e. the setter method overrides the assignment operator for fields. Similarly, if there’s a getter method double foo = p.y is just a shorthand for double foo = p.getY(). If there isn’t a setter or getter, then these statements read and write the field directly.

Suppose you want a read-only or write-only property? Just add a private getter or setter method like so:

  private void setY(double y) {
    this.y = (float) y;
  }

Indeed this is more flexible than the current proposals because it would allow you to do things like create a property that is read-only to the general public but writable by subclasses:

  public double getY() {
    return this.y;
  }

  protected void setY(double y) {
    this.y = (float) y;
  }

Notice that this technique requires no new keywords, syntax, or operators. Can we do this? Sadly no; I don’t think we can. The ship has sailed. This would break existing badly designed code that uses both public fields and a getter or setter. I don’t think there’s a lot of code like that out there, but there is some. The most prominent example is java.awt.Point. Not coincidentally, that’s also the poster child for the campaign to eliminate public fields.

Can we get close enough to this ideal that it’s worth doing? Maybe.

What Java Can Still Do With Public Fields

The ground rules are:

  1. We have to introduce as little syntax as possible, ideally none, but just enough that we don’t change the meaning of any existing code.
  2. We don’t want to have to write getters and setters for the simple cases. We want the compiler to autogenerate these, but we do want to be able to provide our own if necessary.
  3. We want client code to be able to follow the standard Java naming conventions we all know. That is foo = p.getX() and p.setX(2.3) should work.
  4. We want client code to be able to follow the standard Java naming conventions we all know. That is foo = p.x and p.x = 2.3 should also work, and do the same thing.

I see two possible solutions.

A New Keyword

The first possible solution is to add a single property keyword to a field declaration like so:

public class Point {

  property double x;
  property double y;

}

property would be an access specifier and fits in the grammar right where private, public, and protected do now.

This tells the compiler to autogenerate getters and setters for the field, but only if there are no such methods present already. (This is like how javac handles the default constructor now.) Furthermore, it indicates that calls that appear to be direct public field accesses should be dispatched to the getter and setter methods instead.

The downside to this approach is that we could only use the p.x syntax for new classes. We couldn’t use it for existing classes that do have getter and setter methods that follow the JavaBeans naming conventions but have not been retrofitted with properties.

New methods

The second possibility is to add methods whose sole purpose is to override access to fields. These could begin with $ character, which is currently allowed in method names by the Java VM, but not allowed by the compiler. (Some byte code obfuscators use this trick to prevent decompilation.) This would avoid any accidental conflicts with old code. For example,

public class Point {

  public double x;
  public double y;

  public double $x() {
    return this.x;
  }

  public void $x(double x) {
    this.x = (float) x;
  }

  public double $y() {
    return this.y;
  }

  public void $y(double y) {
    this.y = (float) y;
  }
  

}

However, the compiler would only use these methods for field access if they were present. Otherwise it would read and write the fields directly.

The problem is that I don’t see how to easily fit the existing setFoo and getFoo methods into this scheme. These methods could certainly still be present, but there’s no way to autogenerate them. This improves new classes, but does little for use of existing bean classes.

Neither solution seems clean enough to make me sure it ‘s worth the cost, but these are the best I’ve come up with; and I think they’re better than the other proposals I’ve seen. They involve fewer changes to the language, and are more powerful, especially in that they allow greater programmer control over access to properties.

In the end, I think the only reasonable solution is a clean break. Go to a full-on Eiffel solution where methods with the same name as a field override the access to the field:

public class Point {

  private float x;
  private float y;

  public double x() {
    return this.x;
  }

  public double y() {
    return this.y;
  }

  public void y(double y) {
    this.y = (float) y;
  }

  public void y(double x) {
    this.x = (float) x;
  }

}

Anything else is just a half measure that will cause more confusion than it solves. Sometimes to fix a broken bone that’s set wrong, you have to break it again first. In many ways, Java has set wrong. Property access is just one example. Sooner or later we’re going to have to admit that it’s time to start over and create a new Java 3 that makes a clean break with the past and is no longer limited by backwards compatibility. Otherwise, Java is just going to become a confusing mess of compromises that will be less and less accessible to anyone who didn’t grow up with the language.

40 Responses to “What Properties in Java Should Have Looked Like”

  1. Martin Boel Says:

    Great idea, the proposed syntax looks like a simple operator overloading mechanism for set/get.

    But why not allow generic operator overloading, so we can do getters/setters AND equals, plus, minus e.t.c.?

  2. Curt Cox Says:

    To me, the value of language support for properties lies with bound properties. Language changes that don’t reduce the effort required to implement bound properties hold considerably less appeal.

    http://java.sun.com/docs/books/tutorial/javabeans/properties/bound.html

  3. Elliotte Rusty Harold Says:

    User-defined operator overloading is a very bad idea that leads to unmaintainable code, as C++ has proven by example. This is completely different from languages reusing the same operators, as almost all languages do. (adding both ints and doubles with the plus sign, for example). Symbols should mean the same thing in all programs in the language. A + sign should not mean something different in your program than it means in mine.

  4. Kevin Klinemeier Says:

    I agree with the assertion in the article: It’s past time for a clean break.

  5. John Roth Says:

    As long as you accept that a new property mechanism won’t magically retrofit to old code, there’s a much simpler solution that shouldn’t break any reasonably designed module.

    Just give the field, the getter and the setter the same name. Forget this idiotic get and set prefix thing. It’s only useful to tell tools that use reflection that you intend the method to be a getter or setter.

    Additionally, the field must have private or protected access; the compiler will insure that it can only be accessed directly from within the getter or setter method.

    BTW – I disagree about operator overloading. C++ did not “prove” that it was a bad idea, what it proved is that novices can’t handle powerful facilities. This is news? What may be news is that a lot of people being paid princely saleries have never gotten out of the novice category.

    Python works quite well with both multiple inheritance and operator overloading. Both facilities are very useful for specific purposes if handled with some intelligence.

    John Roth

  6. Augusto Says:

    Lack of operator overloading is one of those fundamental things in Java that was touted as a feature, not something that was missing or could be added later.

    One can blame inexperienced developers all day for problems with that feature, but it is a confusing mess. It’s just not reasonable to have operators mean different things at the whim of whoever wrote a certain library. I remember endless nights debugging commercial crap software that tried to be cute by overriding the new and delete operators and leaking memory all over the place, without really making it clear that they had overridden those operators. No thanks.

    Elliote, I really like your suggestions, the “property” keyword sounds great and I don’t really seem to think it’s a big problem that you can’t retrofit it to existing classes (although that would be desirable).

    Java 3 sounds like a good idea eventually, maybe instead of patching things up, it’s time for a reboot …

  7. Dereck Says:

    Great post!

    I use C# everyday for work, and I’ve always felt something was wrong with the whole property usage there – though I couldn’t really put my finger on the sources of my uneasiness. Properties seem to break so many rules at once (intuitively) that one is hard-pressed to say succintly what the issues really are. As I was learning C# well I vaccilated between thinking that C# properties were ‘brilliant’ and ‘just wrong’ on the same day!

    Your article here puts the whole think in sharp relief, since encapsulation is the heart of the issue. Thanks!

  8. John Cowan Says:

    I think you need two coupled changes:

    1) Add the property keyword as you describe it. Note that “property final” will not generate a setter. (The NetREXX language, which compiles to the JVM, has been doing exactly this under the name of “indirect” since Java 1.1 came out.)

    2) Induce the compiler to interpret p.x references from outside p’s class as calls to getters and setters if and only if there is no such public field in p’s class. These were errors before, so there is no backward-compatibility problem.

    Existing code will work as before. New classes can be called from old code using the standard bean conventions. Old classes can be called from new code in either way, and produce the expected results. Stupid old classes (both getter/setter and public field) will use the public field with p.x syntax and the getter/setter with method call syntax; the compiler could warn about uses of p.x against such classes.

    (Personally I think Points should be immutable, for the same reason that Integers are.)

  9. Ed Davies Says:

    “The downside to this approach is that we could only use the p.x syntax for new classes. We couldn’t use it for existing classes that do have getter and setter methods that follow the JavaBeans naming conventions but have not been retrofitted with properties.”

    If an old class or interface has a public getX method but no public x field, why can’t a new class’s code x = p.x; not compile as if it was written x = p.getX();? Ditto for assignment and setX(), of course. This seems like syntactic sugar which is well within the remit of the compiler rather than a matter of a change to the byte codes. Java is sufficiently statically typed that this should be safe, I think.

  10. Elliotte Rusty Harold Says:

    The problem with inducing the “compiler to interpret p.x references from outside p’s class as calls to getters and setters if and only if there is no such public field in p’s class” is that the compiler doesn’t always know if there are no such public fields in p’s class. Because of dynamic linking and polymorphism, it would have to compile a reference something like this:

    try {
      x = p.foo;
    }
    catch (NoSuchFieldError err) {
      x = p.getFoo();
    }
    catch (IllegalAccessError err) {
      x = p.getFoo();
    } 
  11. Masklinn Says:

    Elliotte >

    i overall agree with your final proposal, and I also think it’s pretty much the only way to keep java-the-language in a fairly clean state, but I see 3 potential issues:

    * How does the class itself differentiate `x-the-field` and `x-the-accessor`? Method-call syntax from inside the class (this.x calls the field, this.x() calls the getter, this.x(y) calls the getter)? Can the breakage of uniform access be acceptable (the same symbol would have a different meaning from the inside the object than the one it has from the outside)?

    * How do you link properties to interfaces? Do you do it crappy-C#-style where properties are little better than Java’s getters/setters (you can’t refactor public accessors into private accessors + properties) or does `public` become a ruby-style syntactic shortcut for
    private float x;
    public float x() { return this.x; }
    public void x(float val) { this.x = val }

    which would allow the usage of interfaces over `public` fields (which wouldn’t be, really) as well as the refactoring of existing public fields into properties, or of existing but useless properties into `public` fields?

    * What happens when you create properties with no actual corresponding field? How would java behave when faced with

    public String foo() { return (this.bar + ‘:’ + this.baz) }
    public void foo(String in) {
    String[] slt = in.split(‘:’,2);
    this.bar = slt[0];
    this.baz = slt[1];
    }

    does it create overloaded methods as it currently does? Or does it magically detect that this should be a property? Or does it just blow up? Or does it create both a property and a pair of overloaded methods? (ouch)

    > Elliotte Rusty Harold Says:
    > User-defined operator overloading is a very bad idea that leads to unmaintainable code, as C++ has proven by example.

    No, what C++ has proved is that beginners can’t cope with operators overloading

    > A + sign should not mean something different in your program than it means in mine.

    Do you disagree with Java’s usage of “+” to append strings together then? Who’s right, the half of the languagespace using “+” for string concatenation, or the other half using it exclusively for numbers addition? And what happens to languages such as OCaml who accept “+” only for _Integer_ addition, and require the use of another operator (+.) for floats addition?

    Now if “+” should only be used for numbers addition, why couldn’t I use it if I define a class of numbers, say a class of Complex numbers? Because last time i checked if I don’t have operators overloading I’m missing it for _everything_, not just for the cases in which it doesn’t make sense.
    And if “+” can also be used for String concatenation, why couldn’t it also be used for Lists concatenation or Array concatenation? Many languages interpret strings as arrays or lists of characters after all. And if it could, why couldn’t I define it for _my_ arrays or lists types?

  12. Masklinn Says:

    By the way would it be possible to have something like a link to a page explaining how to post in here? The syntax for code snippets and such? I haven’t managed to find any indication on how to do it and it’s fairly annoying, especially since your comments show that it’s possible.

  13. Slava Pestov Says:

    What’s wrong with operator overloading?

  14. Naiden GOchev Says:

    I read the fallowing C# idea for automatic properties http://aabs.wordpress.com/2007/01/29/c-automatic-properties-semantic-changes-to-help-cope-with-poor-syntax/
    it’s not so bad
    for me using symbols like ~$%@$# are BAD 🙂 and ugly and break existing code;
    the idea is to use annotations like @Property
    for example :
    @property(name=”test”,returnType=”int”)
    int myCrazyPropertyTest;
    or
    @property(name=”test”,useCustomGetterSetter=trye);
    int myCrazyProperty;
    public void setTest(int aTest) { /… }
    public void getTest() { return myCrazyProperty ; }
    or you can leave the idea of the name=”test” argument
    another VERY very nice proposal is :
    http://weblogs.java.net/blog/forax/archive/2007/01/a_property_prop_1.html
    idea :
    Simple properties :
    public class PropertyPoint {
    property int x;
    property int y;
    }

    custom properties :
    public class PropertyPoint {
    abstract property double x;
    abstract property double y;

    property double rho;
    property double theta;

    public double getX() {
    return rho*cos(theta);
    }
    public void setX(double x) {
    double rho = hypot(x, y);
    theta = atan2(y, x);
    this.rho = rho;
    }

    public double getY() {
    return rho*sin(theta);
    }
    public void setY(double y) {
    double rho = hypot(x, y);
    theta = atan2(y, x);
    this.rho = rho;
    }
    }

  15. evanx Says:

    As much as i’m used to point.setX(1), i think point.x.set(1) or point.x(1) looks neater, because the property name remains uncapitalised. And point.x = 1 is neat, just we have to understand that the equals is overloading set() if it exists. String overloads plus and operator overloading is handy eg. i would like to have it for numeric math expressions (involving BigDecimal et al).

  16. dvholten Says:

    if properties are so important – why is the noise about them so current? shouldnt the demand have been in times of jdk1.1.8 ?? i am perfectly happy with my ide generating setters and getters as i need them. i can make them public, protected or private – or omit them. i can put them in interfaces, i can overload them, and i can reflect on them. I see no additional (valuable) functionality in properties, which would justify the added complexity. IMO, properties are as useful as static imports….

  17. Masklinn Says:

    > if properties are so important – why is the noise about them so current? shouldnt the demand have been in times of jdk1.1.8 ?

    I guess that’s because there are now Java people discovering non-java languages while still wanting to code in Java.

    So they discover properties, and they want them in their favorite language.

    Or they discovered properties with C# getting them. Same result.

  18. Curt Cox Says:

    Properties are seeing a renewed interest because desktop Java is seeing a renewed interest. There are currently several JSRs aimed at desktop Java. There has been demand for properties since the introduction of the original JavaBeans spec–and probably before. Given the incredible state of IDEs today, many people wonder why building a simple GUI in Java isn’t much easier.

  19. B. K. Oxley (binkley) Says:

    To avoid the problem of Point having both public fields and accessors for the same, simply teach the compiler to recognize that condition and leave it alone.

    Alternatively, add an annotation to instruct the compiler to do nothing with the class. Something like @LegacyProperties or whatnot.

    Lastly, make the compiler smarts apply only with a given annotation rather than apply by default, say with @Properties or @Bean or whatnot.

  20. Mark Says:

    I understand ‘why public fields are bad’, but I have no idea why the first reason doesn’t apply to properties. If anyone can explain, please.

  21. dvholten Says:

    >Properties are seeing a renewed interest because desktop Java is seeing a renewed interest.
    >… Given the incredible state of IDEs today, many people wonder why building a simple GUI in Java isn’t much easier.

    some years ago i programmed in vb6 – yes its easy to write gui-programs with that. i think, it is because their world is (? was..) flat : you drop your controls in some snap-to-grid panel and fill out the onEvent-handlers. no layout-manager. no round-trip from gui-designer to code to gui-designer. no class-structure. and access the database from the client…

  22. George Says:

    When I read your books I knew you were in-touch with Java, I wish they would listen to engineers like you and not destroy the language. Excellent work as usual, my compliments. For everyone else, OMG LISTEN.

  23. Dan Howard Says:

    OR do nothing since properties at the language level is ghey.

  24. Masklinn Says:

    > I understand ‘why public fields are bad’, but I have no idea why the first reason doesn’t apply to properties. If anyone can explain, please

    Is the first reason the “type of the interface” part? Well it doesn’t apply to properties for the same reason it doesn’t apply to regular getters/setters.

    Properties are syntactic sugar for getters and setters, with a twist when they’re done well (which is _not_ the case of C#): public properties can be transparently swapped with standard public fields (sometimes this really happens e.g. in Python, other times the language doesn’t actually have public fields and “public fields” declaration are really declarations for basic “pass-through” properties stubs which you can later on replace with fleshed out properties if you happen to need them e.g. in Ruby). The important part of this is “transparently swapped”, this means that, in a statically typed language (Java or C#), public fields should be part of the interface and their impact on the interface of the class should be exactly the same as the impact of a property.

  25. Serhiy Says:

    Why don’t you listen to the what people think. Nobody need any additional “properties” in java.
    Please see http://today.java.net/pub/pq/141
    Why don’t we focus on something really important and necessary???

  26. Mark Says:

    > Is the first reason the “type of the interface” part?

    Partly. The principle at stake here is that changing the implementation should not break the interface. A property mixes implementation (the variable holding a value) and interface (how the property is accessed), just like a public variable. Getters/setters separate interface from implementation. That’s why ‘the first reason doesn’t apply to regular getters/setters’, but does apply to properties. Or am I missing something here?

  27. Hallvard Trætteberg Says:

    If I understand you correctly, what you want is the simplicity of the dot syntax (p.x) with the power of methods (including overloading). In the Common Lisp Object System (CLOS), a field (call slot) definition generated getter and setter methods (collectively called accessor methods), so you could use the power of methods to handle constraints, update dependent fields etc. Normally you would use these methods, but you could also set the field directly using a special, low-level method. If you redefined an accessor method, I believe you could call the auto-generated one from the redefinition (but not from outside), so it wasn’t completely overwritten.

    If you take the idea of mapping primitive syntax to method, you could also define that [] mapped to elementOf (or whatever name you choose) and [] = mapped to setElementOf, and was legal for any class, so Maps and List could use the same syntax as arrays. I believe Dylan (an language which tried to make Common Lisp look more like a standard language) did this, and this resulted in quite nice code to both write and read.

    I know this looks a bit like operator overloading, but it’s different from and not as dangerous as overloading the mathematical operators (like + and -), where you expect certain rules from algebra to apply.

    A meta comment: It seems to me that some people participating in this (and other) discussions assume Java’s designers were ignorant of these problems and/or their possible solutions. I think that’s wrong, e.g. Guy Steele co-wrote the Common Lisp specification, and was at Sun early enough to influence the design of Java. There are so many opinions about these things that it’s good that they didn’t make decisions about them too early. Whether we can reach consensus on adding keywords like property (which I think is a good idea, based on my experience with CLOS) now is a different question. It will also be interesting to see if the open sourcing of Java makes the process more open to such suggestions (as long as they’re compatible with the JVM).

  28. Daniel Serodio Says:

    There should be operator overloading for BigInteger and BigDecimal. Reading code that uses these classes hurts

  29. Johann Thomas Says:

    just another style of property syntax:

    Borland Delphi Pascal also has properties (wasn’t it, that the one how developed this language also was the creator of C#) and you can define the names of the getter and setter methods. These will be called, even if you access the property field directly:

    [tt]
    mybook.count = 3 ; // still calls setCount(…)
    // for following declaration

    type
    Book = class
    private
    // User defined attributes
    title: Char;
    FCount: Integer;
    // User defined methods
    procedure setCount(cnt: Integer); virtual;

    public

    // Access methods
    function getTitle: Char;
    procedure setTitle(newTitle: Char);
    // Properties
    property count: Integer read FCount write setCount;

    implementation

    [/tt]

  30. Masklinn Says:

    > That’s why ‘the first reason doesn’t apply to regular getters/setters’, but does apply to properties. Or am I missing something here?

    Yes you are, because a property is not a public field, it doesn’t even have to _back_ a public field.

    Let’s give a trivial and non-existent example: you’ve got a property a on your object A.

    This means that you can, of course, call A.a and have a result back. Your property is a simple pass-through (ie you could’ve made your `a` field a public field and it would be the same. It _should_ be the same, in fact).

    Now you realize that you should change your implementation, and that your private field `a` should really be replaced by a computation based on `b` and `c`, because your `a` private field really doesn’t pull its weight. Are you locked? Nope, just replace your passthrough interface by a computing one: instead of `return a` write `return compute(b, c)` and instead of `a=value` write `b, c = someInverseComputation(value)`. Boom, you’re done. And it’s very often what’s done in Python or Ruby. The _point_ of interface is that they _look_ like public fields (I like to call them “virtual public fields”) but they’re not. This really means that your interface is independent from the implementation, and the only reason why you use a property or a method is whether or not it makes sense.

    And if properties and public fields behave the same at the interface-level (meaning that you can declare a public field in an interface, or a property, and they’re declared the same way, as long as there’s either a public field or a property that satisfies the contract everything’s ok) then you don’t have to wrap everything in getters and setters “just in case”, uselessly boosting the number of indirections and making the code less clear: you use public fields, and if you need to “hide” them or change your implementation, just swap them with properties.

  31. Frits Jalvingh Says:

    Thanks for so far the best observation on how properties should work in Java! The current proposals using “->” and such are all crap, and muck up the language. I like your variant using the ‘property’ keyword best; the ‘$’ names look like a kludge.

    I agree that it would be a really good idea to reduce the importance of “backwards compatibility” in these discussions. The need for it is often only perceived and not really needed. Take the “Generics” implementations for instance: lots of older code does not compile with -source 1.5. Which is no problem _at all_ because we _have_ -source 1.4! You can easily compile “legacy” code with a legacy version of the language; the only thing you need to keep “backwards compatibility” is to maintain the ability within the JVM to handle the generated code. This is how most “older” code is compiled nowadays anyway.

    A good way to see how perceived “backwards compatibility” can really hurt is the Generics implementation. The moronic braindead idiot that allowed for type erasure should be shot! It has reduced the Generics system to a barely functional syntactic layer only, with really stupid limitations (why on EARTH would anyone in his right mind accept a generics implementation which is unable to do class … new T()” ) AND huge reduced functionality around Reflection and metaprogramming. And the reason for this enormous crappy cludge: they wanted to be backwards compatible with JVM 1.4… Which they aren’t anyway. Horror.

    I would also make another point for all the people that do not want to extend the language because they think there are already other (usually more verbose ways) of doing whatever needs to be done. Think for instance about the “enum” functionality introduced in 1.5. A computer language is a way to express a problem solution. How effective you can be in expressing such a solution is a direct advantage: if you have to write “boilerplate” for very common solutions this is a problem of the language! It reduces the visibility of the “real” problem *and* it often reduces the knowledge that the compiler has about the actual thing being done – leading to lousy (or no) error messages or reduced code quality.
    To me the plethora of stupid “getXxx” and “setXxx” methods is an indication of a blunder in language design. Saying I can do something in a language does not make it the right way because a good language is supposed to make common things easy.

    I would advice people to look at C# for some examples of good language design, not only wrt to the language but also wrt the process: don’t be too afraid for changes.

  32. Eamonn McManus Says:

    This is just a nitpick, but the Java compiler does allow an identifier to begin with $, and always has.

  33. albert bulawa Says:

    Properties are bad and should not be allowed in Java. Of course, it *looks* nice to be able to say foo.x = 4 instead of foo.setX(4) but it’s all there is. All other things being downsides.

    1. Public field access is mostly understood as a fast, failsafe operation but “property access” is NOT. With such a syntax you have to prepare yourselves for a = operator (or, in case of the getter, worse still, the . “operator”) throwing at least runtime exceptions. But why disallow checked exceptions on accessors? And the fast bit: property access may use a database ot a webservice or whatever gizmo you can imagine and it may last seconds, not nanoseconds as we are mentally prepared with public fields.
    2. What about x = y = z? Setters are void, and for a good reason, but you can’t have x = y = z without breaking this. It is a minor issue, though… and I like this syntax to disappear anyway
    3. It’s next to impossible to get this right in the compiler. You should be able to replace the class with properties (a version using simple passthrough or plain public fields to a version using accessors or the other way around) without breaking its clients’ binary or source code. That means the compiler has to use indirection anyway because it cannot know whether or when you’re going to replace that library JAR.
    4. This must be transparent as well to the Reflection API, and consistently with the source code. Look at how badly it’s broken in C#.

    More and more C# programmers are warning adepts *not to use* properties and to write explicit accessors instead. Come to think of it, this was meant to be a real advantage and boost over Java and now most experienced C# programmers prefer and evangelize the Java way in C#.

    So please leave the properties where their place is: in the “failed experiments” drawer.

  34. JavaSPEKTRUM Blogosphäre » Blog Archiv » Blogosphäre (aus JavaSPEKTRUM 02/07) Says:

    […] Eine gewaltige Debatte hat JavaSE-Plattform-Chef Danny Corward mit seinem Vorschlag angestoßen, Java um das Konzept von Eigenschaften (Properties) zu erweitern, den Zugriff auf “öffentliche” Attribute also nicht über die JavaBean-Konvention von get- und set-Methoden, sondern über eine spezielle Syntax zu kapseln. Vielfach wird die konkret vorgeschlagene Syntax – ein Pfeil (”->”) wie beim Zeigerzugriff in C++ – kritisiert, so z.B. von Kirk Pepperdine. Weniger syntaktisch, sondern inhaltlich betrachtet Cay Horstmann das Thema. Er zeigt, wie sich 64 Zeilen Code auf 12 zusammenschrumpfen lassen und versucht, die typischen Gegenargumente (”meine IDE generiert die Bean-Methoden für mich”, “Getter und Setter sind sowieso schlechtes Design”) zu entkräften. Elliotte Rusty Harold beschreibt, wie Java Properties aussehen sollten — aber auch, warum man sie seiner Meinung nach gar nicht braucht: Seiner Meinung nach reichen die bestehenden Sprachmittel völlig aus. Zustimmung dazu gibt es von Dave Megginson (Achtung Schockgefahr: Er vergleicht den Vorschlag mit einer kosmetischen Operation und illustriert die Analogie mit einem Bild eines Popstars, das man Minderjährigen lieber ersparen sollte.) Megginsons und Harolds Ansicht nach sollte man aufhören, Java um immer neue Elemente zu erweitern. Wer andere Konzepte will, möge doch einfach eine andere Sprache verwenden. Mike Champion, bei Microsoft für XML-Standards verantwortlich, verweist in einem Kommentar auf die Analogie zu C#: Völlig unwichtig, welche Merkmale Microsoft zu Visual Basic hinzufügt, C#-Entwickler fragen immer nur danach, wann sie diese auch in ihrer Umgebung nutzen können. Wer all den Links gefolgt ist, die unzähligen Kommentare gelesen hat und immer noch nicht befriedigt ist, dem seien die Diskussionen bei InfoQ und JavaLobby empfohlen. […]

  35. Chad Grant Says:

    “More and more C# programmers are warning adepts *not to use* properties and to write explicit accessors instead. Come to think of it, this was meant to be a real advantage and boost over Java and now most experienced C# programmers prefer and evangelize the Java way in C#.”

    That’s just a flat out lie. There are no c# programmers evangelizing properties as Java does, and if you find one, they’re a moron. Properties are a very important part of the whole .net framework. C# coders live in that framework and to code in the backassward way as the framework would be ignorant.

  36. Sean Noble Says:

    Based on blog post http://cafe.elharo.com/blogroll/what-properties-in-java-should-have-looked-like/:

    “Properties are bad and should not be allowed in Java” – LOL no properties (have to laugh)

    “Public field access is mostly understood as a fast, failsafe operation but “property access” is NOT” – I’m afraid I have to be the one to tell you that’s the whole point (abstraction at the cost of performance – let the developers decide the intended use) LOL

    “I like this syntax to disappear anyway” – So why you bringing it up as a point? LOL

    “It’s next to impossible to get this right in the compiler” – Really? Heard of .NET? LOL

    “Look at how badly it’s broken in C#” – Um, reflection works like a charm – we emit code and properties at runtime. More than 10 people seem to be ok with the system, so I’d say that it’s not really broken LOL

    “More and more C# programmers are warning adepts *not to use* properties and to write explicit accessors instead” Yeah right! LOL

    … Thanks very much for providing my entertainment for the day (this post and the comments). Ah man, I couldn’t stop laughing. I have to give them props, if Java “programmers” do have one useful skill, if nothing else, it’s that they sure are funny. Next thing you know they’ll be recommending to not JIT anything and go backwards by always compiling at runtime.

    -Sean Noble

    ———–
    This blog post comment is designed offer humorous reflection upon why in the world Java 7 still doesn’t have properties. Shows why Java’s not nearly as popular as it could be. Seriously though, good luck getting intelligent people in place as the decision makers. Seems like yall have your work cut out for you. Best wishes.

  37. Önder Teker Says:

    I think there may be a way to support properties in the simplest form, that’s using ‘.’ instead of ‘set’ or ‘get’. There may be an annotation such as ‘@PropertySupported’ and if a class has this annotation it’s properties could be called in the simple form. An alternative to this is to support properties by default and mark old classes with problems such as java.awt.Point with an annotation such as ‘@PropertyUnsupported’. In general, I support every feature simplifying the syntax because I believe the only reason for the other languages to exist is simplicity in their syntax. If Java had a simpler syntax, nobody would care about the other languages, especially scripting ones. All of their white paper or documentation talks about simple their syntax.

  38. When the community kills innovation | ICaffeine Says:

    […] Once again, I’m impressed. The above is from a comment in this blog post. I remember admiring java for what it offered back then: innovation, garbage collection to the […]

  39. Ramon J Santiago Says:

    While I agree that there should be/have been a way to do “property” For Java, I have learned to appreciate the value of setter-less coding.

    class Foo {
    public final IBar Bar;
    public final IBaz Baz;

    Foo(IBar Bar, IBaz Baz) { this.Bar = Bar; this.Baz = Baz }

    }

    and that’s all.

    Usage is;

    IBar bar = InstanceOfFoo.Bar;

    Coding conventions and garbage collection be damned.
    Go Fluent if you have too many constructor args.

  40. hansi Says:

    i’ve never used it myself, but you might want to take a look at lombok which can autogenerate a lot of this for you
    http://projectlombok.org/index.html it adds the getters and setters at compile time, and also generates the often forgotten hash and tostring methods.

    also play framework 1.x had a similar feature,
    but i believe they did it at runtime instead (not sure though)