I'm new to Java and I have come to having the following problem:
I have created several classes which all implement the interface "Parser". I have a JavaParser, PythonParser, CParser and finally a TextParser.
I'm trying to write a method so it will take either a File or a String (representing a filename) and return the appropriate parser given the extension of the file.
Here is some psuedo-code of what I'm basically attempting to do:
public Parser getParser(String filename)
{
String extension = filename.substring(filename.lastIndexOf("."));
switch(extension)
{
case "py": return new PythonParser();
case "java": return new JavaParser();
case "c": return new CParser();
default: return new TextParser();
}
}
In general, is this the right way to handle this situation? Also, how should I handle the fact that Java doesn't allow switching on strings? Should I use the .hashcode() value of the strings?
I feel like there is some design pattern or something for handling this but it eludes me. Is this how you would do it?
You can simply use several if
statements one after another.
You can create special enum
for your languages and use it in your switch statement.
You can use Map
where languages are keys and parser's prototypes are values.
3rd option looks interesting as for me. The code will look like:
return parsers.get(extention).newInstance();
And here is a little tricky implementation of the 2nd option with enum:
enum Language {
JAVA {
public Parser getParser () {
return new JavaParser ();
}},
PYTHON {
public Parser getParser () {
return new PythonParser ();
}},
TEXT {
public Parser getParser () {
return new TextParser ();
}};
public Parser getParser () {
return null;
}
public static Language getLanguage (String extention) {
try {
return valueOf (extention);
} catch (IllegalArgumentException e) {
return TEXT;
}
}
}
...
public Parser getParser(String filename) {
String extension = filename.substring(filename.lastIndexOf("."));
return Language.getLanguage (extension).getParser ();
}
This is called the Factory method pattern and it seems like a pretty good way to handle your problem. One way you can get around the "Java doesn't allow switching on strings" problem is by using an if
...else
statement.
if (extension.equals("py")) {
return new PythonParser();
}
else if(extension.equals("java")) {
return new JavaParser();
}
else ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With