Single Responsibility Principle - Improved Example

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 get hold of old code on Github.

This was roughly 2 years ago :).

I though of improving this code further. We can completely remove FileValidationUtils by 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);
    }
  }
}

We introduce default method in Parser interface ( Java 8 features) which checks if the file could be parsed which could be overridden by the concrete implementations. You can check the full example code on Github.

1 comment :