I got this task I'm supposed to solve: create a class whose constructor parses text in the CSV format (don't have to worry about escaping and quoting for now). The second argument to the constructor is the name of the field by which subsequent searching will be done. Assume that the values in that field are unique. The class should implement interface CSVSearch:
interface CSVSearch {
CSVRecord find(String key); // returns null if nothing is found
}
interface CSVRecord {
String getField(String name);
}
And then I have a sample usage:
CSVSearch csvByName = new YourCSVSearch(
"ip,name,desc\n"+
"10.0.0.1,server1,Main Server\n"+
"10.0.0.5,server2,Backup Server\n",
"name");
csvByName.find("server2").getField("ip") -> "10.0.0.5"
csvByName.find("server9") -> null
The entire code should take between 20-30 lines.
What baffled me here, first of all, is that by implementing CSVSearch interface it supposed to return CSVRecord object. But CSVRecord is an interface, so I can't have it as an object, right?
Second of all, if I'm having interfaces to implement, how am I supposed to chain their methods (csvByName.find("server2").getField("ip")
)?
I started to write my solution:
public class CSVfinder {
public static void main(String[] args) {
CSVparser csvByName = new CSVparser("ip,name,desc\n"
+ "10.49.1.4,server1,Main Server\n"
+ "10.52.5.1,server2,Backup Server\n", "name");
}
}
class CSVparser implements CSVSearch, CSVRecord {
String lines[];
String keys[];
String values[];
public CSVparser(String text, String key_name) {
lines = text.split("\n");
keys = lines[0].split(",");
}
public String getField(String name) {
// TODO Auto-generated method stub
return null;
}
public CSVRecord find(String key) {
// TODO Auto-generated method stub
return null;
}
}
interface CSVSearch {
CSVRecord find(String key); // returns null if nothing is found
}
interface CSVRecord {
String getField(String name);
}
I'm lost here... How would you solve it?