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?
One of the answers I got over was this, from user StriplingWarrior
:
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 sayservice.byId(123).isPresent()
. This represents the same meaning semantically, but it's broken into separate parts, which means you can reusebyId()
,byName()
, etc., for other purposes where you need the actual object, and not just to know whether it exists.
My ultimate question is, aside from the current solution, is there another way to refactor this code block so I don't have so much repeated similar code?