1

I have some common methods for two classes and maybe for others in the future. Therefore I do not want to copy same methods in all classes. I thought to create a utility class and put these methods inside and send the necessary data as a parameter. But I read about using utility class violate OOP.

As a second, I was thinking to apply strategy pattern but I do not need to change behaviour of the method in the runtime, it will work same for both classes therefore it looks it does not suit to my problem.

Do you have any idea what could be the best approach for this situation or which design pattern could be applied?

user1474111
  • 1,356
  • 3
  • 23
  • 47

2 Answers2

2

It's not bad to violate OOP for something that is really a utility class.

Almost all frameworks (spring, hibernate you_name_it) do that to some extend.

Furthermore, if you later plan to support your code, composition is much easier to refactor / support than to maintain inheritance in your classes.

WeMakeSoftware
  • 9,039
  • 5
  • 34
  • 52
1
public class Baseclass
{
    public Baseclass(){
        //init baseclass;
    }

    public void commonMethod(){
        //do stuff;
    }
}


public class AnyObject extends Baseclass
{
    public AnyObject(){
        super();
    }
}

Simple example

JohannisK
  • 535
  • 2
  • 10