This discussion is archived
2 Replies Latest reply: Nov 13, 2012 1:44 AM by svanimpe RSS

Read-only and constant properties

svanimpe Newbie
Currently Being Moderated
Hi all,

I am wondering what is the correct way to define read-only or constant properties.

For read-only properties I have seen or used the following:

Version 1:
private DoubleProperty x = new SimpleDoubleProperty(0);

public ReadOnlyDoubleProperty xProperty() {
    return x;
}
Version 2:
private ReadOnlyDoubleWrapper x = new ReadOnlyDoubleWrapper(0);

public ReadOnlyDoubleProperty xProperty() {
    return x.getReadOnlyProperty();
}
Version 1 seems simple enough, but I'd guess this isn't safe because the caller can simply cast the return value back to SimpleDoubleProperty and change it ?
Version 2 seems safer, because you cannot cast the return value to a writable type.

I haven't seen any constant properties, but based on the versions above, I could imagine the following:

Version 1:
public static final ReadOnlyDoubleProperty X = new SimpleDoubleProperty(0);
Version 2:
public static final ReadOnlyDoubleProperty X = new ReadOnlyDoubleWrapper(0).getReadOnlyProperty();
Which of these versions is recommended, or is there a better alternative ?
  • 1. Re: Read-only and constant properties
    RichardBair Journeyer
    Currently Being Moderated
    The terminology confusion here is my fault. Do you want to declare a read only property or an immutable (constant) property? For immutable properties we simply provide a final getter, no setter, and no property method (see LinearGradient for example).

    For a read only property (which is read only to the world, but privately or protectedly writable), Version 2 is the correct pattern for the reason you described.

    Richard
  • 2. Re: Read-only and constant properties
    svanimpe Newbie
    Currently Being Moderated
    Thanks Richard.

    With regard to the "constant properties", I was looking for a bindable replacement for public static final variables. Maybe I should have said "bindable constants" because I don't really use a property pattern.

    For example, I replaced:
    public static final double LIMIT_HIGH = 240;
    with:
    public static final ReadOnlyDoubleProperty LIMIT_HIGH = new ReadOnlyDoubleWrapper(240).getReadOnlyProperty();
    I haven't seen anyone else do this, but I figured this might be the way to do it, based on the read-only property pattern. Am I correct, or is there a better way to achieve the same results ?

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points