SOLID — Design Principles

1. Single Responsibility

public class Book {    private String name;
private String author;
private String text;
//constructor, getters and setters
// methods that directly relate to the book properties
public String replaceWordInText(String word){
return text.replaceAll(word, text);
}
public boolean isWordInText(String word){
return text.contains(word);
}
}
public class Book {
void printTextToConsole(){
// our code for formatting and printing the text
}
}
public class BookPrinter {    // methods for outputting text
void printTextToConsole(String text){
//our code for formatting and printing the text
}
void printTextToAnotherMedium(String text){
// code for writing to any other location..
}
}

2. Open for Extension, Closed for Modification

public class Guitar {    private String make;
private String model;
private int volume;
//Constructors, getters & setters
}
public class SuperCoolGuitarWithFlames extends Guitar {    private String flameColor;    //constructor, getters + setters
}

3. Liskov Substitution

public interface Car {    void turnOnEngine();
void accelerate();
}
public class MotorCar implements Car {    private Engine engine;    //Constructors, getters + setters    public void turnOnEngine() {
//turn on the engine!
engine.on();
}
public void accelerate() {
//move forward!
engine.powerOn(1000);
}
}
public class ElectricCar implements Car {    public void turnOnEngine() {
throw new AssertionError("I don't have an engine!");
}
public void accelerate() {
//this acceleration is crazy!
}
}

4. Interface Segregation

public interface BearKeeper {
void washTheBear();
void feedTheBear();
void petTheBear();
}
public interface BearCleaner {
void washTheBear();
}
public interface BearFeeder {
void feedTheBear();
}
public interface BearPetter {
void petTheBear();
}
public class BearCarer implements BearCleaner, BearFeeder {    public void washTheBear() {
//I think we missed a spot...
}
public void feedTheBear() {
//Tuna Tuesdays...
}
}
public class CrazyPerson implements BearPetter {    public void petTheBear() {
//Good luck with that!
}
}

5. Dependency Inversion

public class Windows98Machine {}
public class Windows98Machine {    private final StandardKeyboard keyboard;
private final Monitor monitor;
public Windows98Machine() {
monitor = new Monitor();
keyboard = new StandardKeyboard();
}
}
public interface Keyboard { }public class Windows98Machine{    private final Keyboard keyboard;
private final Monitor monitor;
public Windows98Machine(Keyboard keyboard, Monitor monitor) {
this.keyboard = keyboard;
this.monitor = monitor;
}
}
public class StandardKeyboard implements Keyboard { }

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store