patternjavaModerate
Country selector: if or ternary?
Viewed 0 times
countryternaryselector
Problem
String fileId = "CPP420.A2_2012072416244467745";
String reg1 = "CPP350";
String reg2 = "CPP420.A1";
String reg3 = "CPP420.A2";
String country = "";
if(fileId.startsWith(reg1)) {
country = "CA";
} else if(fileId.startsWith(reg2)) {
country = "US";
} else if(fileId.startsWith(reg3)) {
country = "FR";
} else {
System.out.println("Error invalid file");
}OR
String country = fileId.startsWith(reg1) ? "CA" : "";
country = fileId.startsWith(reg2) ? "US" : "";
country = fileId.startsWith(reg3) ? "FR" : "";
if("".equals(country)) {
System.out.println("No country found");
}Solution
Neither. Note: haven't tried this in and IDE, but you should be able to get the idea.
An implementation like this would allow you to load the
interface RegionID {
boolean isRegionMatch(String fileID);
String getRegionCode();
}
class SimpleMatchRegionID implements RegionID {
private String regionPrefix;
private String regionCode;
public SimpleMatchRegionID(String regionPrefix, String regionCode) {
this.regionPrefix = regionPrefix;
this.regionCode = regionCode;
}
public boolean isRegionMatch(String fileID) {
return fileID.startsWith(regeionPrefix);
}
public String getRegionCode() {
return regionCode;
}
}
RegionID us = new SimpleMatchRegionID("CPP420.A1", "US");
RegionID ca = new SimpleMatchRegionID("CPP350", "CA");
RegionID fr = new SimpleMatchRegionID("CPP350", "FR");
RegionID[] regions = {us, ca, fr};
public String findRegionCode(String fileID) {
for (i = 0; i < regions.length; i++) {
if (regions[i].isRegionMatch(fileID)) {
return regions[i].getRegionCode();
}
}
return "";
}An implementation like this would allow you to load the
regions array from a data file, or with some other run-time mechanism. It would also allow you to implement other strategies for recognizing a region that doesn't follow the same basic pattern.Code Snippets
interface RegionID {
boolean isRegionMatch(String fileID);
String getRegionCode();
}
class SimpleMatchRegionID implements RegionID {
private String regionPrefix;
private String regionCode;
public SimpleMatchRegionID(String regionPrefix, String regionCode) {
this.regionPrefix = regionPrefix;
this.regionCode = regionCode;
}
public boolean isRegionMatch(String fileID) {
return fileID.startsWith(regeionPrefix);
}
public String getRegionCode() {
return regionCode;
}
}
RegionID us = new SimpleMatchRegionID("CPP420.A1", "US");
RegionID ca = new SimpleMatchRegionID("CPP350", "CA");
RegionID fr = new SimpleMatchRegionID("CPP350", "FR");
RegionID[] regions = {us, ca, fr};
public String findRegionCode(String fileID) {
for (i = 0; i < regions.length; i++) {
if (regions[i].isRegionMatch(fileID)) {
return regions[i].getRegionCode();
}
}
return "";
}Context
StackExchange Code Review Q#14997, answer score: 18
Revisions (0)
No revisions yet.