patternjavaMinor
Optimizing code block using Switch Case
Viewed 0 times
caseblockoptimizingusingcodeswitch
Problem
I have a implementation of following code block,
I might need to add more options in
public class FileFormatConversion {
public static enum File_TYPES {
PDF, PNG, OTHERS, ALL
}
public static void processOtherFileType(String arg1) {
System.out.println("Other file output -- " + arg1 + " file");
}
public static void processPNGPDFALL(String arg1, String arg2) {
System.out
.println("General block for processing PDF/PNG or ALL other file format -- "
+ arg2
+ "\\"
+ arg1
+ " parameter validation/check file availability");
}
public static void processPDF(String arg1, String arg2) {
System.out.println("Block for processing PDF file -- " + arg2 + "\\"
+ arg1 + ".pdf");
}
public static void processALL(String arg1, String arg2) {
System.out.println("Block for processing ALL file types -- " + arg2
+ "\\" + arg1 + ".all");
}
public static void processPNGALL(String arg1, String arg2) {
System.out
.println("Common block for manipulating file formats such as PNG or ALL files");
}
/**
* @param args
*/
public static void main(String[] args) {
args = new String[3];
args[0] = "ALL";
args[1] = "fileName";
args[2] = "C:\\filePath";
File_TYPES fileFormatInput = File_TYPES.valueOf(args[0]);
if (File_TYPES.OTHERS == fileFormatInput) {
processOtherFileType(args[1]);
} else {
processPNGPDFALL(args[1], args[2]);
if (File_TYPES.ALL == fileFormatInput
|| File_TYPES.PNG == fileFormatInput)
processPNGALL(args[1], args[2]);
if (File_TYPES.ALL == fileFormatInput)
processALL(args[1], args[2]);
if (File_TYPES.PDF == fileFormatInput)
processPDF(args[1], args[2]);
}
System.out.println("Completed");
}I might need to add more options in
ENUM in future. so using if-else will make it complex while debugging/adding. Is there any better alternatSolution
To avoid the messy
Then, for each type of file, make a subclass that implements
switch block, you should probably create an interface or abstract class called FileConversionHandler:public abstract class FileConversionHandler {
public abstract void process(File f);
}Then, for each type of file, make a subclass that implements
process() differently.Code Snippets
public abstract class FileConversionHandler {
public abstract void process(File f);
}Context
StackExchange Code Review Q#32219, answer score: 7
Revisions (0)
No revisions yet.