Skip to main content

Posts

Showing posts with the label SRP

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 Fi

Single Responsibility principle with example

Single Responsibility Principle Single responsibility principle was introduced by Tom DeMarco in his book " Structured Analysis and Systems Specification, 1979 ". Robert Martin reinterpreted the concept and defined the responsibility as a reason to change. A class should have only one reason to change. In this context, responsibility is considered as reason to change. This principle states that if we have two reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handles it. When we need to make a change in the class having more responsibilities the change might affect the other functionality of the classes. Let's see this by example. package com.gauravbytes.srp.parser ; import java.io.File ; class FileParser { public void parseFile ( File file ) { // parse file logic for xml, csv, json