How can I reduce multiple methods that take one parameter of different type?

I have the following code:

public final boolean doesExistById(Long id) {
    return dataAccessObject.findById(id) != null;
}

public final boolean doesExistByName(String name) {
    return dataAccessObject.findByName(name) != null;
}

public final boolean doesExistByDisplayName(String displayName) {
    return dataAccessObject.findByDisplayName(displayName) != null;
}

public final boolean doesExistByWebId(String webId) {
    return dataAccessObject.findByWebId(webId) != null;
}

      

My class Product

has properties id, name, displayName, wedId

.
dataAccessObject.findBy____()

returns an object of type Product

if it can be found in the data store, or null

if it cannot.

I would like to reduce this piece of code if possible, because I have a lot of objects that require a template doesExist()

as above. The client code will only know one of these properties.


A possible solution I was thinking would do this:

public final boolean doesExist(Long id, String name, String displayName, String webId) {..}

      

and then call it with null

for unknown fields using operators if

to determine which field has a value. But is there an even more elegant way?

+3


source to share


2 answers


You realize that the "ByXxx" part of all these methods "really exists" is exactly the same, and this forces you not to repeat it, but the "ByXxx" part of these methods is completely different.

What you have is much better than you think. Please do not change your method signature to require callers to supply null values ​​for all but one argument. This is highly error prone as it does not contain compile-time errors for the various ways that people might misuse method signatures.

One thing you might want to consider is splitting the "is" part into your mechanism:



public final Optional<MyObj> byId(Long id) {
    return Optional.ofNullable(dataAccessObject.findById(id));
}

      

So instead of speaking service.doesExistById(123)

, you will say service.byId(123).isPresent()

. This means the same meaning semantically, but it breaks down into separate parts, which means you can reuse byId()

, byName()

etc. For other purposes where you need the actual object, not just to know if it exists.

+7


source


You can write a method that takes an object type. I recommend that you check out this page. What is reflection and why is it useful?



-2


source







All Articles