0

I created a LoginFieldsController custom controller that inherits from the VBox class. Later in the programs I use this controller as an ordinary node like Button, TextFiled, etc. Please note that I only write pure Java code, I do not use FXML.

Question: is it better to declare LoginFieldsController nodes as the fields of the LoginFieldsController class, or inside the LoginFieldsController constructor? Outside the constructor I was doing nothing.

In other words, it would be better like this:

public class LoginFieldsController extends VBox {
    private TextField loginField;
    private TextField passwordField;

    public LoginFieldsController( ... ) {
        loginField = new TextFeild("Login");
        passwordField = new TextFeild("Password"); 
        this.addAll(loginField, passwordField);
        ...
}

Or that:

public class LoginFieldsController extends VBox {

    //no fields in that class

    public LoginFieldsController( ... ) { 
        TextField loginField = new TextFeild("Login");
        TextField passwordField = new TextFeild("Password"); 

        this.addAll(loginField, passwordField);
        ...
}
Jo45
  • 15
  • 2

2 Answers2

0

It's good to keep them outside the constructor, especially if you need access to them later (to get their current value for example )

0

I would strongly suggest declaring them outside the constructor, as fields. This way, you can access them in other methods when you need to do something with them. You can use the constructor to inject those fields if you need to do it at object instantiation, or you can have setters to inject them later.

Consider the following code:

Class Example{

  public Example(...){
    TextField text1 = new TextField();
    //some other code
  }

  public boolean checkData(){
    //text1 is not visible here
  }

On the other hand:

Class Example{

  TextField text1; 

  public Example(...){
    text1 = new TextField();
    //some other code
  }

  public boolean checkData(){
    //text1 is visible here
  }

On a sidenote, I would use graphic elements (such as a VBox in your example) only for the view part (guessing you use MVC, since you are using controllers) and write a separate controller class.

Ivan Kukic
  • 425
  • 4
  • 14
  • >On a sidenote, I would use graphic elements only for the view part. Not really understood here, do you mean that I have to write another class that would handle user actions with nodes in LoginFieldsController? – Jo45 Feb 18 '19 at 15:02
  • 1
    @Jo45 you don't _have to_. It's just good practice, and also the S in SOLID, a set of principles. Let the view show your data, let your model keep the data, and have your controller react to actions made either on the view or the model. – Ivan Kukic Feb 18 '19 at 15:06