Search code examples
javamethodsrecycle

Recycling methods that need certain objects in Java


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!


Solution

  • 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.