what is IntegerProperty and why does it need to be imported - java

So in class we always use the following syntax. Correct me if i am wrong but this is a bean because it class use getters/setters. It has an nullary constructor and the class implements serializable.
// option 1
private int customerID ;
public CustomerDTO ()
{
this(0);
}
public CustomerDTO(int customerID) {
setCustomerID(customerID);
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public int getCustomerID() {
return customerID;
}
But today i came across something similar like this. i needed to import
import javafx.beans.property.SimpleStringProperty;
But what is the main difference between option 1 and 2.
When should i use option 1 or option 2
And which one is better or does it depends on the situation.
// option 2
private final IntegerProperty customerID;
public CustomerDTO ()
{
this(null);
}
public CustomerDTO(IntegerProperty customerID) {
this.customerID = new SimpleIntegerProperty();
}
public IntegerProperty getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID.set(customerID);
}

Option 2 is used when you are building JavaFX application and want to bind your model with gui.
Example:
public class Foo {
private final StringProperty foo = new SimpleStringProperty();
public String getFoo() {
return foo.get();
}
public StringProperty fooProperty() {
return foo;
}
public void setFoo(String foo) {
this.foo.set(foo);
}
}
public class FooController {
#FXML
private TextField fooTextField;
private final Foo foo = new Foo();
#FXML
public void initialize() {
foo.fooProperty().bindBidirectional(fooTextField.textProperty());
}
}

public CustomerDTO(IntegerProperty customerID) { makes no sense, a property is a final class member which encapsulates a value, this value can be set via setters and get via setters, in JavaFX controller classes it is advisable to also implement a getter for the ReadOnlyObjectProperty or ReadOnlyIntegerProperty in your case, this can be done via ReadOnlyIntegerWrapper and its getReadOnlyProperty method. This enables the developor to bind to values from other classes whilst also ensuring that the value exists at any time, JavaFX Bindings are a pretty elegant and object-oriented method of data-encapsulation.
Your "option 2" actually is flawed since it allows property-redefinition which breaks this concept and makes the property itself useless. It will also break GUI functionality except if the property itself can not be redefined, see the accepted answer

Related

Finding non-referenced class attributes in Eclipse

I wonder if there are another ways to find attributes in specific class are non-referenced by other classes (I mean, non used attributes).
My way is like that, for example I have a class like:
public class EABHeaderInformation implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4986763088497593972L;
//BargainFinder - AlternateBooking
private int multiTicketSequencdNmbr;
private String resBookDesigCode;
private LocalDateTime departureDate;
private LocalDateTime lastTicketingDate;
private List<String> text;
private String validatingCarrierCode;
public String getValidatingCarrierCode() {
return validatingCarrierCode;
}
public void setValidatingCarrierCode(String validatingCarrierCode) {
this.validatingCarrierCode = validatingCarrierCode;
}
public int getMultiTicketSequencdNmbr() {
return multiTicketSequencdNmbr;
}
public void setMultiTicketSequencdNmbr(int multiTicketSequencdNmbr) {
this.multiTicketSequencdNmbr = multiTicketSequencdNmbr;
}
public String getResBookDesigCode() {
return resBookDesigCode;
}
public void setResBookDesigCode(String resBookDesigCode) {
this.resBookDesigCode = resBookDesigCode;
}
public LocalDateTime getDepartureDate() {
return departureDate;
}
public void setDepartureDate(LocalDateTime departureDate) {
this.departureDate = departureDate;
}
public LocalDateTime getLastTicketingDate() {
return lastTicketingDate;
}
public void setLastTicketingDate(LocalDateTime lastTicketingDate) {
this.lastTicketingDate = lastTicketingDate;
}
public List<String> getText() {
return text;
}
public void setText(List<String> text) {
this.text = text;
}}
It's a simple POJO with getter and setters. I check every getter and setter with 'Open Call Hierarchy' in Eclipse, to find out if the attribute is used by others or not. But it takes a lot of time when I work on bigger classes than this.
So, is there a faster way to do this? Thanks for replies.
Eclipse can already create a warning or error for unused private members, but for public ones the Eclipse stance has always been that it's not a valuable feature. I tend to disagree, because many users have a limited scope that would be useful (specifically, all, or a subset of, the projects in the workspace). See this feature request, this one, and this one.
There are some third party options, such as UCDetector and this simple plug-in example.
See also this SO question and the answers.

Memento pattern drawbacks

So, here is an typical implementation of Memento pattern (skipped getters and setters).
public class Employee {
private String name;
private String phone;
public EmployeeMemento save() {
return new EmployeeMemento(name, phone);
}
public void revert(EmployeeMemento memento) {
this.name = memento.getName();
this.phone = memento.getPhone();
}
}
public class EmployeeMemento {
private final String name;
private final String phone;
public EmployeeMemento(String name, String phone) {
this.name = name;
this.phone = phone;
}
}
public class Caretaker {
private Stack<EmployeeMemento> history;
public Caretaker() {
history = new Stack<>();
}
public void save(Employee employee) {
history.push(employee.save());
}
public void revert(Employee employee) {
employee.revert(history.pop());
}
}
All implementations of this pattern that I found are more or less equal to the one above. But there are some problems about this kind of implementation, that I don't like:
It's possible to triger both employee.revert() and caretaker.revert(employee). I would like to have only one access point.
If we want to change EmployeeMemento, we have to make changes in Employee class also (because of revert method).
Is there a way to overcome this?
Or maybe I pay too much attention, and this details are not so important?
1) Note that Caretaker is supposed to take care of holding Mementos, not necessarily take care of Undo/Redo. If you look at the various implementations on Internet (For example here), you'll see that Caretaker does not have revert() but usually something like getMemento(). So the class that takes care of Undoing, is someone else which calls getMemento() on Caretaker and then revert() on Subject.
Even if you want Caretaker to take care of Undoing, note that employee.revert() is a method that's solely created to be used by caretaker.revert(), because in this design, no one else has access to Mementos. You can reduce it's visibility to be visible by only Caretaker. (If this was C++, it would be easily done by use of friend, but in Java you have to be creative and use package visibility or some other way.)
2) In Memento pattern, a class and its Memento are tightly coupled. Actually it's only the class itself that has access to Memento's internals and no one else should see how Memento is composed. So it does not matter if a change to class, propagates to its Memento.
Then again If you want to isolate changes, you can be creative again. For example instead of duplicating name and phone in both Class and its Memento, you could extract another class which contains these fields (let's say by the name of State) and then use this State in both the original class and its Memento. This way, when you have changes to state of the class, you need only to modify State.
Side note: It's better to define Memento as a nested static class inside the Subject.
So my design, that addresses your issues, would be something like this:
public class Employee {
private State state;
public Memento save() {
return new Memento(state);
}
public void revert(Memento memento) {
this.state = memento.state;
}
public static class Memento {
private final State state;
public Memento(State state) {
this.state = state;
}
}
public static class State {
private String name;
private String phone;
}
}
public class Caretaker {
private Stack<Employee.Memento> history;
public Caretaker() {
history = new Stack<>();
}
public void addMemento(Employee.Memento memento) {
history.push(memento);
}
public Employee.Memento getMemento() {
return history.pop();
}
}
public class UndoHandler {
Employee employee;
Caretaker caretaker;
public void snapshot() {
caretaker.save(employee.save());
}
public void undo() {
employee.revert(caretaker.getMemento());
}
}

What's more efficient: Class object or Object[] (object array)?

I'm not sure if a class object to transfer data will be more efficient than an object array.
My goal is to know which option is the most efficient and which option is the best practice.
Consider this is a web application served to thousands of users.
Here the two sample cases:
A)
Model.java
public class Model {
public Contact getContact(long id)
{
// some logic
return new Contact(...);
}
}
Contact.java
public class Contact
{
private long id;
private String name;
private String surname;
private String email;
private int session;
private byte[] avatar;
// Constructor
public Contact(long id, String name, ...)
// Getters and Setters
}
B)
Model.java
public class Model {
public Object[] getContact(long id)
{
// some logic
Object[] myReturningContact = new Object[n];
myReturningContact[0] = rs.getLong("id");
// ...
myReturningContact[n] = rs.getBytes("avatar");
return myReturningContact;
}
}
SomeController.java
public class SomeController
{
public void someAction()
{
// Option A
this.setSomeTextTo(contact.getName());
// Option B
this.setSomeTextTo(String.valueOf(returningObject[n]));
}
}
Option A is best practice, unless you have a speed requirement that it can't meet, and Option B can.
Note that Option A will probably be a little faster if you make your fields public and final and don't use getters.
Also note that if you have many primitive fields, the cost of boxing and unboxing will slow down Option B, as may String.valueOf on Strings

Suggestions on how to create a changewatcher on a SlingModel to enable persistence to the JCR

We are currently attempting to implement an extension to SlingModels, to allow a slingmodel to be persisted to the JCR directly.
Our strategy has 2 considered starting conditions:
1. A new object that is to be persisted
2. An object that has been retrieved from the JCR, altered, and is then to be persisted again
For situation 1, we are using reflection to examine the object, create a new node for the model, insert properties for any of the primitive variables found, and recursively use the same persistence approach for any complex model objects found as variables, and collections.
My question on best approach relates to situation 2. If we pull out an object from the repository, we cannot be guaranteed that the node will not be synchronously changed in the meantime. Thus, we would like to implement a change watcher on the SlingModel that keeps a transaction journal on any changes made. The transactions can then be used to set the relevant properties when persisting the object back to the JCR again.
I have considered using an observer pattern, but this would mean that we would need to implement a function within the setter on each SlingModel, which is not ideal at all, as it requires a developer to remember to add the code and do it correctly.
Ideally, I would like to implement something like an interceptor directly on the variable, or if not possible, on the setter itself, and mandate that each model would then need to use a getter/setter for each variable. We can configure code scanning tools to enforce developers to implement getter/setters.
What would the be the best way to approach the change watcher here?
import java.util.List;
public class Teacher {
private String userName;
private String cource;
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCource() {
return cource;
}
public void setCource(String cource) {
this.cource = cource;
}
}
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ClassFacadeCglib implements MethodInterceptor{
private Object target;
public Object getInstance(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
// callback method
enhancer.setCallback(this);
// create proxy object
return enhancer.create();
}
#Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
if(method.getName().startsWith("set")){
System.out.println(method.getName()+" start");
proxy.invokeSuper(obj, args);
System.out.println(method.getName()+" end..");
}
if(method.getName().startsWith("get")){
System.out.println(method.getName()+" start");
proxy.invokeSuper(obj, args);
System.out.println(method.getName()+" end");
}
return null;
}
}
public class Main {
public static void main(String[] args) {
ClassFacadeCglib cglib=new ClassFacadeCglib();
Teacher teacher=(Teacher)cglib.getInstance(new Teacher());
teacher.setCource("Math");
teacher.getUserName();
}
}
Note :
cglib-full-2.0.2.jar is required for running.
see https://repo1.maven.org/maven2/cglib/cglib-full/2.0.2/

Get Object from Field

CLARIFICATION:
I do not know the objects name. That is where the problem comes in. I am creating an object like such:
`new Object(String attributes);
I am trying to run code in another class such as:
***.getStuff();
the trick to it is, there is no name for the Object. but i do know what String attributes is
The question: Is there any way to accomplish this without using the dreaded for loop?
This question is a bit tricky to word, but I will try my best. What I want to is get an object that matches a particular field without making a messy for loop. Something along the lines of:
Object A has the field String name.
String nameObj = "Tickle";
Object A has the name "Tickle"
if(nameObj.equals(Object A)){
//bla bla
}
Very confusing wording, yes. Sorry about that. I want to use Object A in my code without having to figure out which object it is, assuming all I have is its name. I am looking for a shortcut around using a for loop, I suppose.
Feel free to ask questions about what I am looking for. Sorry about the terribly worded question.
Poor coding, but this is what I am looking for...
nameObj.getName().getObjectA();
If you have a bunch of objects with names, and you want to grab an object by its name, I suggest you look up the class HashMap. HashMap lets you put in objects under keys, and when you give the hash map a key it returns the object associated with that key. So in your example, the keys would be string names.
Take at this implementation, that demonstrates what #Patashu said, create a map to the objects, in this case I just add an abstract class at the top of all.
import java.util.HashMap;
public class FindMeBaby {
public static void main(String[] args) {
Factory.add(new NiceGuy("first one"));
Factory.add(new FirstChild("ok im late"));
System.out.println(Factory.get("first one")
.getVeryImportantInformationThatOnlyThisClassKnows());
}
}
abstract class ParentOfAll {
protected String id;
public ParentOfAll(String id) {
this.id = id;
}
public String getId(){
return id;
}
public abstract String getVeryImportantInformationThatOnlyThisClassKnows();
}
class FirstChild extends ParentOfAll {
public FirstChild(String id) {
super(id);
}
public String getVeryImportantInformationThatOnlyThisClassKnows() {
return "this is a secret";
}
}
class NiceGuy extends ParentOfAll {
public NiceGuy(String id) {
super(id);
}
public String getVeryImportantInformationThatOnlyThisClassKnows() {
return "to say the true, i'm not that nice :)";
}
}
class Factory {
private static HashMap allTheObjects = new HashMap();
public static Object add(ParentOfAll object) {
allTheObjects.put(object.getId(), object);
return object;
}
public static ParentOfAll get(String key) {
return (ParentOfAll) allTheObjects.get(key);
}
}
This is another version, of the same implementation with a more transparent aproach, without the Factory class, the Parent itself will keep track of the instances and save in a list.
import java.util.HashMap;
public class FindMeBaby {
public static void main(String[] args) {
NiceGuy foo = new NiceGuy("first one");
FirstChild bar = new FirstChild("ok im late");
System.out.println(ParentOfAll.get("first one")
.getVeryImportantInformationThatOnlyThisClassKnows());
}
}
abstract class ParentOfAll {
protected String id;
public ParentOfAll(String id) {
this.id = id;
add(this);
}
public String getId() {
return id;
}
public abstract String getVeryImportantInformationThatOnlyThisClassKnows();
private static HashMap allTheObjects = new HashMap();
private static Object add(ParentOfAll object) {
allTheObjects.put(object.getId(), object);
return object;
}
public static ParentOfAll get(String key) {
return (ParentOfAll) allTheObjects.get(key);
}
}
class FirstChild extends ParentOfAll {
public FirstChild(String id) {
super(id);
}
public String getVeryImportantInformationThatOnlyThisClassKnows() {
return "this is a secret";
}
}
class NiceGuy extends ParentOfAll {
public NiceGuy(String id) {
super(id);
}
public String getVeryImportantInformationThatOnlyThisClassKnows() {
return "to say the true, i'm not that nice :)";
}
}

Categories

Resources