0

I have a method:

    private Replace ReplaceType(final ReplaceTypeDao replaceTypeDao, final Long key) {
        final Optional<ReplaceType> replaceTypeEntry = replaceTypeDao.findById(key, true);

        if (!replaceTypeEntry.isPresent()) {
            throw new TypeIsMissing(key);
        }
        return replaceTypeEntry.get();
    }

which is exactly the same in other classes but from different packages. I could create class (but in which package?) with method replaceTypeProcess, then call new class constructor and newClassInstance.replaceTypeProcess() but I don't like this solution. How to do it in best manner?

Michu93
  • 5,058
  • 7
  • 47
  • 80
  • 1
    You could make it a static method of the `Replace` class? That way you can be assured that the types are correctly referenced/imported and you would not need to worry about making new instances of the object before calling the method (Depending on where `TypeIsMissing` comes from you might have to re-think your error/throw). – sorifiend Jul 28 '21 at 07:14

1 Answers1

2

You can create a package utility And put some common classes in it.

You can also look this link on how to remove duplicate method.

And as you mentionned it you can make a static method. Here is a very nice post about the use of static methods.

T.K
  • 434
  • 7
  • 14
  • 1
    I thought about Util class but good practice is to have static method there. Is there a way without static? – Michu93 Jul 28 '21 at 07:47
  • I will edit my post with a nice post on when you should or not use static method. In your case if you don't want to use static and don't want to add a utility package I don't really know what you can do. – T.K Jul 28 '21 at 08:01