patternjavaMajor
Check whether address criteria contain only certain fields or more
Viewed 0 times
addresscriteriacontainfieldscertainmorecheckwhetheronly
Problem
I have a method that checks whether an
I'm uncertain what the best way to write my if statement is. As far as I can tell, I see 2 options:
Single if statement:
Multiple if statements:
Maybe there's a 3rd or 4th option that I am unaware of?
addressCriteria contains only certain fields or more. If it contains more fields, it should return false, otherwise true.I'm uncertain what the best way to write my if statement is. As far as I can tell, I see 2 options:
- Write them in 1 if statement
- Write each check in a different if statement
Single if statement:
private boolean isShortAddress(AddressCriteria addressCriteria) {
if((null != addressCriteria.getCity() && !addressCriteria.getCity().isEmpty()) ||
(null != addressCriteria.getNumber() && !addressCriteria.getNumber().isEmpty()) ||
(null != addressCriteria.getState() && !addressCriteria.getState().isEmpty()) ||
(null != addressCriteria.getZipCode() && !addressCriteria.getZipCode().isEmpty())) {
return false;
}
return true;
}Multiple if statements:
private boolean isShortAddress(AddressCriteria addressCriteria) {
if(null != addressCriteria.getCity() && !addressCriteria.getCity().isEmpty()) {
return false;
}
if(null != addressCriteria.getNumber() && !addressCriteria.getNumber().isEmpty()) {
return false;
}
if(null != addressCriteria.getState() && !addressCriteria.getState().isEmpty()) {
return false;
}
if(null != addressCriteria.getZipCode() && !addressCriteria.getZipCode().isEmpty()) {
return false;
}
return true;
}Maybe there's a 3rd or 4th option that I am unaware of?
Solution
I would be compelled to write a helper that accepts a variable number of address fields and and returns true if all of the address fields are not null and not empty.
I did not test this code, but you should catch the drift.
private boolean isShortAddress(AddressCriteria addressCriteria) {
return hasFields( addressCriteria.getCity(),
addressCriteria.getNumber(),
addressCriteria.getState(),
addressCriteria.getZipCode() );
}
private boolean hasFields( addressField... args )
{
for( addressField arg:args)
{
if( null == arg || arg.isEmpty() )
return false;
}
return true;
}I did not test this code, but you should catch the drift.
Code Snippets
private boolean isShortAddress(AddressCriteria addressCriteria) {
return hasFields( addressCriteria.getCity(),
addressCriteria.getNumber(),
addressCriteria.getState(),
addressCriteria.getZipCode() );
}
private boolean hasFields( addressField... args )
{
for( addressField arg:args)
{
if( null == arg || arg.isEmpty() )
return false;
}
return true;
}Context
StackExchange Code Review Q#29127, answer score: 35
Revisions (0)
No revisions yet.