Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to design a common method for 2 classes

I have 2 separate classes, but they both need to do one thing repetitively, in other words there is a common method. This is the method:

private String createButton (String cls, String value) {
        return "<input type=\"button\" class=\"" + cls + 
                   "\" value=\"" + value + "\" key=\"" + this.id + "\" />";
        }

so this is really just a one line method, so I could copy it into both classes. But I was wondering if there's a better way of doing that. I really don't want to have a super class with just that method, obviously. Also, I think it's silly creating another class just for the button and do: new Button(cls,value), isn't?

Another option I thought about is to have a utility class for the package, with a mix of helper functions. Does that make sense? Is it being done?

like image 894
Moshe Shaham Avatar asked Feb 01 '26 08:02

Moshe Shaham


2 Answers

You could use a utility class... but it might become incohesive.

public class Utilities {

    /* What do these methods have in common? */

    public String createButton(...) {
        return "<input type='button' />";
    }

    public double calculateCircumference(Circle c) {
        return circle.getRadius() * 2 * Math.PI;
    }

}

This is the kind of code that leads down the dark road to a God Object.

Instead, consider scoping the purpose and intent of your "utility" class: consider making it a factory - specifically an Abstract Factory so that it retains cohesiveness.

public class HTMLWidgetFactory implements AbstractWidgetFactory<String> { // the interface might be overkill

    /* Oh! This class is clearly used to create HTML controls! */

    public String createButton(...) {
        return "<input type='button' />";
    }

    public String createImage(...) {
        return "<img src='lena.png' />";
    }

}
like image 173
Richard JP Le Guen Avatar answered Feb 03 '26 20:02

Richard JP Le Guen


Yes, a utility class with helper functions is the right way to go here. You are going to have other requirements come up that will be shared utilities as well. They will all go in the utility class.

like image 40
Furbeenator Avatar answered Feb 03 '26 21:02

Furbeenator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!