Software Design - Single Responsibility Principle

This post is in continuation to my older post on Single Responsibility principle. At that time, I provided solution where we refactored FileParser and moved validation logic to FileValidationUtils and also composed Parser interface with various implementation viz. CSVFileParser, XMLFileParser and JsonFileParser (A sort of Strategy Design pattern). and validation code was moved to FileValidationUtils java file. You can see the old example code on Github.

This was roughly 2 years ago :).

I though of improving this code further. We can completely remove FileValidationUtils by using Java 8 features making following code change in Parser interface.

public interface Parser {
public void parse(File file);

public FileType getFileType();

public default boolean canParse(File file) {
return Objects.nonNull(file) && file.getName().endsWith(getFileType().getExtension());
}
}
public class FileParser {
private Parser parser;

public FileParser(Parser parser) {
this.parser = parser;
}

public void setParser(Parser parser) {
this.parser = parser;
}

public void parseFile(File file) {
if (parser.canParse(file)) {
parser.parse(file);
}
}
}

The full example code is available on Github.



Tags: SOLID principles, Single Responsiblity Principle, SRP, class design principles, Software Design

← Back home