Interface Segregation / Dependency Inversion

Slides:



Advertisements
Similar presentations
Design Patterns: Structural Design Patterns
Advertisements

Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
SOLID Principles in Software Design
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Version Control Systems
Auto Mapping Objects SoftUni Team Database Applications
Static Members and Namespaces
Databases basics Course Introduction SoftUni Team Databases basics
Abstract Classes, Abstract Methods, Override Methods
Sets, Hash table, Dictionaries
C# Basic Syntax, Visual Studio, Console Input / Output
OCP and Liskov Principles
Services & Dependency Injection
Data Structures Course Overview SoftUni Team Data Structures
Introduction to MVC SoftUni Team Introduction to MVC
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
Reflection SoftUni Team Technical Trainers Java OOP Advanced
C# Database Fundamentals with Microsoft SQL Server
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Processing Sequences of Elements
EF Relations Object Composition
Entity Framework: Code First
Repeating Code Multiple Times
Inheritance Class Hierarchies SoftUni Team Technical Trainers C# OOP
Java OOP Overview Classes and Objects, Members and Class Definition, Access Modifier, Encapsulation Java OOP Overview SoftUni Team Technical Trainers.
Databases advanced Course Introduction SoftUni Team Databases advanced
Install and configure theme
Balancing Binary Search Trees, Rotations
Debugging and Troubleshooting Code
Entity Framework: Relations
Fast String Manipulation
Functional Programming
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Best Practices and Architecture
Best practices and architecture
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
Making big SPA applications
Manual Mapping and AutoMapper Library
Functional Programming
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Exporting and Importing Data
Introduction to TypeScript & Angular
CSS Transitions and Animations
Iterators and Comparators
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Spring Data Advanced Querying
Software Quality Assurance
Building Rock-Solid Software
Version Control Systems
JavaScript Frameworks & AngularJS
Polymorphism, Interfaces, Abstract Classes
/^Hel{2}o\s*World\n$/
CSS Transitions and Animations
Multidimensional Arrays
Presentation transcript:

Interface Segregation / Dependency Inversion Building Solid Code Advanced Java SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents Dependency Inversion Interface Segregation * Table of Contents Dependency Inversion The Problem (Button  Lamp) How to Invert Dependencies Application Layering Interface Segregation "Fat" Interfaces vs "Role" Interfaces Solving Problems (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

sli.do #JavaOOP-Advanced Questions sli.do #JavaOOP-Advanced © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Dependency Inversion Flip Dependencies

Dependency Inversion Principle "Dependency Inversion Principle says that high-level modules should not depend on low-level modules. Both should depend on abstractions." "Abstractions should not depend on details. Details should depend on abstractions." Agile Principles, Patterns, and Practices in C# Goal: decoupling between modules through abstractions

Dependencies and Coupling What happens when modules depend directly on other modules

Dependencies and Coupling (2) The goal is to depend on abstractions

The Problem Button  Lamp Example – Robert Martin Button depends on Lamp High-level / Client Button poll() Lamp turnOn() turnOff() Low-level / Server © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Dependency Inversion Solution Find the abstraction independent of details Button poll() Lamp SwitchableDevice <interface> turnOn() turnOff() implements uses Client defines interfaces

Dependency Examples A dependency is any external component / system: Framework Configuration Third party library The new keyword Database Static method File system Global function Email Random generator Web service System.in / System.out System resource (e.g. clock)

How to DIP? Constructor injection Dependencies are passed through constructors Pros Classes self-documenting requirements Works well without container Always valid state Cons Many parameters Some methods may not need everything

Constructor Injection – Example public class Copy { private Reader reader; private Writer writer; public Copy(Reader reader, Writer writer) { this.reader = reader; this.writer = writer; } public void copyAll() {}

How to DIP? (2) Setter Injection Dependencies are passed through setters Pros Can be changed anytime Very flexible Cons Possible invalid state of the object Less intuitive

Setter Injection – Example public class Copy { private Reader reader; private Writer writer; public void setReader(Reader reader) {} public void setWriter(Writer writer) {} public void copyAll() {} }

How to DIP? (3) Parameter injection Dependencies are passed through method parameters Pros No change in rest of the class Very flexible Cons Many parameters Breaks the method signature public class Copy { public copyAll(Reader reader, Writer writer) {} }

Problem: System Resources You are given a GreetingClock if hour < 12, prints "Good morning…" if hour < 18, prints "Good afternoon…" else prints "Good evening…" Refactor so it conforms to DIP * Introduce Strategy Design Pattern © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Solution: System Resources Inject interfaces TimeProvider and Writer <Writer> +println(String):void <TimeProvider> +getHour():int GreetingClock +greet():void uses © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Problem: Services You are given some classes Follow DIP to invert dependencies *Introduce Composite Design Pattern OnlineStoreOrder +process():void SmsNotificationService +isActive():Boolean +sendNotification():void EmailNotificationService uses © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Solution: Services OnlineStoreOrder +process():void <NotificationService> +isActive():Boolean +sendNotification():void EmailNotificationService © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Layering Traditional programming High-level modules use low-level modules UI Layer Data Access Layer Business Layer

Layering (2) Dependency Inversion Layering High and low-level modules depend on abstractions Client defines interfaces UI Layer Data Access Layer Business Layer <BL Interface> <DAL Interface>

Problem: Employee Info You are given some classes Refactor the code so that it conforms to DIP Main EmployeeDatabase EmployeeInfoProvider ConsoleFormatter © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Solution: Employee Info ConsoleClient EmployeeDatabase EmployeeInfoProvider ConsoleFormatter <Formatter> <InfoProvider> <Database>

Dependency Inversion Principle Live Exercises in Class (Lab)

Interface Segregation Clients Require Cohesive Interfaces

ISP – Interface Segregation Principle "Clients should not be forced to depend on methods they do not use." Agile Principles, Patterns, and Practices in C# Segregate interfaces Prefer small, cohesive interfaces Divide "fat" interfaces into "role" interfaces

Fat Interfaces Classes whose interfaces are not cohesive have "fat" interfaces public interface Worker { void work(); void sleep(); } Class Employee is OK public class Robot implements Worker { void work() {} void sleep() { throw new UnsupportedOperationException(); }

"Fat" Interfaces Having "fat" interfaces: Classes have methods they do not use Increased coupling Reduced flexibility Reduced maintainability

How to ISP? Solutions to broken ISP Small interfaces Cohesive interfaces Let the client define interfaces – "role" interfaces

Cohesive Interfaces Small and Cohesive "Role" Interfaces public interface Worker { void work(); } public interface Sleeper { void sleep(); } public class Robot implements Worker { void work() { // Do some work… }

<Rechargeable> Problem: Recharge You are given some classes Refactor the code so that it conforms to ISP * Consider the case that you don't own the library New feature (A) Worker Robot Employee <Rechargeable> Recharge Station Current library © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Solution: Rechargeable Multiple Inheritance (If you own the library) (A) Worker Robot Employee <Rechargeable> Recharge Station <Sleeper>

Solution: Rechargeable (2) Adapter Pattern (If you don't own the library) <Rechargeable> Recharge Station RobotAdapter (A) Worker Employee Robot

Problem: Security Door You are given some classes Refactor the code so that it conforms to ISP PinCodeCheck <SecurityUI> +requestKeyCard():String +requestPinCode():int KeyCardCheck (A) SecurityCheck © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Solution: Security Door PinCodeCheck <SecurityUI> KeyCardCheck (A) SecurityCheck <PinCodeUI> ++requestPinCode():int <KeyCardUI> +requestKeyCard():String © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Summary Use dependency injection and abstractions * Summary Use dependency injection and abstractions High and low-level modules should depend on abstractions Abstractions should not depend on details Let the client define the interfaces Prefer "role" interfaces (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

DIP and ISP https://softuni.bg/courses/programming-fundamentals © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license "C# Part I" course by Telerik Academy under CC-BY-NC-SA license "C# Part II" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.