I have 3 different types of files in a folder. Every file has same data which is saved into Employee Table.
File Types:
I have written 3 separate classes which have two methods, take a filePath as String parameter and return an EmployeeVO Object or a List<EmployeeVO>.
I want to remove these if else.
List<EmployeeVO> list ;
if(fileName.endsWith(".xml")){
list = XmlReader();
}else if(fileName.endsWith(".EXCEL")){
list = ExcelReader();
}else if(fileName.endsWith(".TXT")){
list = TxtReader();
}
I think that you can use the Command pattern here. It can be used to replace cumbersome switch / if blocks which tend to grow indefinitely as you add new options.
Another option may be the Factory pattern. You include your if / switch in a Factory which takes care of the ugliness and hides the abundance of ifs.
Of course you can combine both. It only depends on your preference and the context where you are using it.
And by the way: don't use patterns just because they are fancy use them where you need them.
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