简体   繁体   中英

How can I reduce multiple methods that take 1 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 Product class 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 chunk of code, if possible, because I have many objects that require the doesExist() pattern as above. The client code will only know one of these properties.


A possible solution I thought of would be to do this:

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

and then call it with null for unknown fields while using if statements to determine which field has a value. But is there another way that is more elegant?

You are recognizing that the "does exist" part of all of these methods is exactly the same, and that makes you want to avoid repeating it, but the "ByXxx" part of these methods is completely different.

What you've got is far better than what you're thinking of doing. Please don't change your method signature to require callers to provide null values for all but one argument. That is highly error-prone, as it provides no compile-time errors for a variety of different ways that people might use the method signature incorrectly.

One thing you might want to consider doing is separating the "does exist" piece of this into its own mechanism:

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

So instead of saying service.doesExistById(123) , you'd say service.byId(123).isPresent() . This represents the same meaning semantically, but it's broken into separate parts, which means you can reuse byId() , byName() , etc., for other purposes where you need the actual object, and not just to know whether it exists.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM