Reputation: 15
The operations in my two methods are the same, but the input parameter types are different, so how can I optimize these two methods, it seems that they are not so repetitive? Because their operations are the same, but the parameter types are different, what should I do to make this code more elegant?
public class Main {
public static void main(String[] args) {
BaseStudent baseStudent = new BaseStudent();
baseStudent.setName("base");
NbdStudent nbdStudent = new NbdStudent();
nbdStudent.setName("nbd");
updateName(baseStudent);
updateName(nbdStudent);
}
private static void updateName(BaseStudent student) {
student.setName("update base");
}
private static void updateName(NbdStudent student) {
student.setName("update base");
}
}
Upvotes: 0
Views: 675
Reputation: 1878
You should make your students class extend from the same (abstract) base class or implement the same interface.
Since the two classes are both students you can define a common parent (lets say BaseStudent
is the common parent)
/* BaseStudent.java */
// abstract is optional, depends on if you want
// to make the class instantiable or having some
// methods that are not implemented
abstract class BaseStudent {
public String name;
public void setName(String name) { this.name = name; }
}
/* NbdStudent.java */
class NbdStudent extends BaseStudent { }
/* main file */
public class Main {
public static void main(String[] args) {
BaseStudent baseStudent = new BaseStudent();
baseStudent.setName("base");
NbdStudent nbdStudent = new NbdStudent();
nbdStudent.setName("nbd");
updateName(baseStudent);
updateName(nbdStudent);
}
private static void updateName(BaseStudent student) {
student.setName("update base");
}
}
In a more broad way you can abstract your classes to have a common behaviour but a different implementation
/* Named.java */
interface Named {
public void setName(String name);
}
/* BaseStudent.java */
class BaseStudent implements Named {
public String name;
public void setName(String name) {
// different implementation simple example
if (name == null) { name = "BaseStudent with no name"; }
this.name = name;
}
}
/* NbdStudent.java */
class NbdStudent implements Named {
public String name;
public void setName(String name) { this.name = name; }
}
/* main file */
public class Main {
public static void main(String[] args) {
BaseStudent baseStudent = new BaseStudent();
baseStudent.setName("base");
NbdStudent nbdStudent = new NbdStudent();
nbdStudent.setName("nbd");
updateName(baseStudent);
updateName(nbdStudent);
}
private static void updateName(Named student) {
student.setName("update base");
}
}
Upvotes: 1