Reputation: 183
Is there a best practice regarding the two options below to get variables from, in this case, the MainScene class ? I actually have many more variables to get so I would end up with many other methods or 2-3 switch methods.
class MainScene
Option 1 - Multiple Methods
public TextField getLoadTxt(){
return loadTxt;
}
public TextField getdownTxt(){
return downTxt;
}
public TextField getflightTxt(){
return flightTxt;
}
public TextField getacTxt(){
return acTxt;
}
public TextField getairportTxt(){
return airportTxt;
}
Option 2 - One Method with Switch
public TextField getTextField(String textField){
TextField text = new TextField();
text.setText("Default");
switch(textField){
case "loadTxt": return loadTxt;
case "downTxt": return downTxt;
case "flightTxt": return flightTxt;
case "acTxt": return acTxt;
case "airportTxt": return airportTxt;
default: return text;
}
}
Upvotes: 1
Views: 341
Reputation: 1209
For the option 1, you can use lombok, which helps generate all the getter functions. For the option 2, you can use reflection.
If using Maven, including
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
</dependency>
and here's the code:
import lombok.Data;
public @Data
class ReflectionTest {
String str = "abc";
String str2 = "ecd";
public void get() {
try {
System.out.println(this.getClass().getDeclaredField("str").get(this));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class App {
public static void main(String[] args) {
ReflectionTest reflectionTest = new ReflectionTest();
// get value by option 2
reflectionTest.get();
// get value by option 1
System.out.println(reflectionTest.getStr2());
}
}
Upvotes: 2
Reputation: 27966
In general you should have one 'getter' method for each variable. However if you have a larger number of variables that represent different attributes of the same type then you might want to consider using an attribute enumeration:
public enum Field {
LOAD, DOWN, FLIGHT, AC, AIRPORT;
}
public MainScene {
private final EnumMap<Field,TextField> fields = new EnumMap<>(Field.class);
public TextField getField(Field field) {
return fields.get(field);
}
}
Upvotes: 1
Reputation: 44844
Usually Option 1, and most (all?) IDE can auto-generate setters/getter methods.
Also, if you let an IDE do all the work, easier and less chances of introduced bugs.
Upvotes: 1