2

Using properties in Java FX application I come to question regarding understanding of Properties usage: what is a practical difference in using class instance member ...Property against Simple...Property?

public class Foo {

    private IntegerProperty id;

    public Foo(int id) {
        this.id = new SimpleIntegerProperty(id);
    }

    public IntegerProperty idProperty() {
        return this.id;
    }

    public int getId() {
        return id.get();
    }

    public void setId(int id) {
         this.id.set(id);
    }
}

against

public class Foo {

    private SimpleIntegerProperty id;

    public Foo(int id) {
        this.id = new SimpleIntegerProperty(id);
    }

   public SimpleIntegerProperty idProperty() {
       return this.id;
   }

   public int getId() {
       return id.get();
   }

    public void setId(int id) {
       this.id.set(id);
   }
}
Leon
  • 33
  • 3
  • It's the same reason for using `List` rather than `ArrayList`: [programming to the interface](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface). – Slaw Dec 21 '18 at 22:02
  • And the convention is to use `IntegerProperty` (rather than `Property`) because it implements [`NumberExpression`](https://openjfx.io/javadoc/11/javafx.base/javafx/beans/binding/NumberExpression.html) which adds convenient behavior that the `Property` interface doesn't have. – Slaw Dec 21 '18 at 22:08
  • thanks a lot, I did not pay attention IntegerProperty is abstract – Leon Dec 21 '18 at 22:58

1 Answers1

1

Your first implementation is really the good one.

You definitively should use the most abstract type (IntegerProperty in your case) wherever you can.

The main reason is that it allows you to change implementation without having to change your methods' prototype/definition, and so no need to change any caller.

Think about the same situation with a Set, and migrating from HashSet concrete type to LinkedHashSet.

Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
  • Yes, thanks, this time it perfectly works. Let's delete all this comments about upvote, and anwser, because it is no more needed for this Q/A ;) – Bsquare ℬℬ Jan 06 '19 at 21:13