adam bien's blog

Java's Getters And Setters are evil, JavaFX Script's not always 📎

The reaction for the posts Getters and setters: an antipattern. JavaBeans and OO and Summary: Public getters and setters should be considered as an antipattern caused some interesting discussions and comments. There was one common sense: exposing private attributes over getters and setters is neither objectoriented, nor domain driven style. An interesting solution for this problem offers JavaFX script, sample:


A class customer with 2 members and one update method:


import java.lang.System;

class Customer{

private attribute firstName: String?;

private attribute lastName: String?;

operation update(newFirstName:String,newLastName:String);

}

 

operation Customer.update(newFirstName:String,newLastName:String){

firstName = newFirstName;

lastName = newLastName;

}


The interesting part of the source code are "Replace Trigger" which can be associated with attributes: 


trigger on Customer.firstName[oldValue] = newValue{

System.out.println("Old value was: {oldValue}, the new value is: {newValue}");

}

 

trigger on Customer.lastName[oldValue] = newValue{

System.out.println("Old value was: {oldValue}, the new value is: {newValue}");

}

 

The construction of an FX object:

 

var dukeCustomer = Customer{

firstName: "duke"

lastName: "mighty"

};



Causes the following output:


Old value was: , the new value is: duke
Old value was: , the new value is: mighty


The call of the following update method: 


dukeCustomer.update('java','javafx');


writes the lines below:


Old value was: duke, the new value is: java
Old value was: mighty, the new value is: javafx



So JavaFX Script allows, only if neccessary, the definition of "interceptors" called triggers, which can be used for validation etc.

I like the idea, because most of the Java-Getters/Setters are empty. I'm curious, why these triggers aren't called "update aspects".

It would be much better for the marketing :-).

The method update isn't necessary, it is also allowed to access the attributes directly. It seem's like JavaFX now ignores the "private" keyword...


Hint: to see the system output from the JavaFXPad, you have to activate the "Java Console" in the JNLP settings (System Settings, Java under Windows).