0

I was just wondering if there exists any way to recycle a method in Java that is repeated in sibling classes because they need a specific object.

Let's see an example:

public void refreshSearch(){
    try{
        String search = bookDialog.getTxtBrowser().getText();
        bookBusiness.searchByString(search, bookDialog
            .selectedItemToString(bookDialog.getCmbBrowser())); 
        bookDialog.getTbBooks()
            .setModel(new BookTableView(bookBusiness));
        setBookTableTitles();
    }
    catch(SQLException ex){System.out.print(ex);}
}

And then:

public void refreshSearch(){
    try{
        String search = studentDialog.getTxtBrowser().getText();
        studentBusiness.searchByString(search, studentDialog
                .selectedItemToString(studentDialog.getCmbBrowser())); 
        studentDialog.getTbStudents()
                .setModel(new StudentTableView(studentBusiness));
        setStudentTableTitles();
    }
    catch(SQLException ex){System.out.println(ex);}
}

The point here is that I have two equal methods just because they require a spicific object type.

The solution that just come to my mind is to recieve a generic Object parameter and then check for the class and create the respective instances, but if this method is used by three different classes, I have to create six objects and only two of them will be used (the other four would be null). Therefore, I would have to create a long structure just for each object.

There exist in Java any way to solve this problem?

Thanks a lot!

Rubzet
  • 189
  • 1
  • 2
  • 15
  • Maybe you could use the Template pattern, for instance `getDialog().getTxtBrowser().getText()` where getDialog is an abstract method overridden in subclasses to return the right kind of object. – Joakim Danielson Nov 30 '18 at 18:59
  • This certainly can be done, but the additional code will be far more work to maintain than just copying those four customized lines into each class. Sometimes, especially with short code, repetition is the better choice. – VGR Nov 30 '18 at 19:51

1 Answers1

0

This can be solved using interfaces. so you could create a Dialog interface that has methods getTxtBrowser() and getTbStudents(), and a Business interface that has searchByString method, and then create implementing classes for that interface for StudentDialog and BookDialog and StudentBusiness and BookBusiness. That way you could create one method that uses the interface and it will execute the methods in your implementing classes.

Justin
  • 1,356
  • 2
  • 9
  • 16
  • Oh thanks, what a quick answer! I had just forgotten about interfaces. Thank's a lot. You helped me so much. – Rubzet Nov 30 '18 at 19:55