SlideShare a Scribd company logo
Design for testability
Stanislav Tyurikov
Design for testability
«One reasonable definition of good design is testability. It is hard to imagine
a software system that is both testable and poorly designed. It is also hard
to imagine a software system that is well designed but also untestable»
Robert C. Martin.
Design for testability – is improving quality of software design as well
as possibility to write tests for the code.
Symptoms of poor design
• Rigidity – System is hard to change.
• Fragility – Changes causes system to break easily and require other
changes.
• Immobility – Difficult to entangle components that can be reused in
other systems.
• Viscosity – Doing things right is harder than doing things wrong.
• Needless Complexity – System contains infrastructure that has no
direct benefit.
• Needless Repetition – Repeated structures that should have a
single abstraction.
• Opacity – Code is hard to understand.
Symptoms of good design
• Minimal complexity – Avoid making “clever“ designs. Clever designs are usually hard to
understand. Keep it simple.
• Ease of maintenance – it is easy to understand and make changes.
• Loose coupling – Loose coupling means designing so that you hold connections among different
parts of a program to a minimum.
• Extensibility – You should be able to change a piece of the system without causing a huge impact to
other pieces of the system.
• Reusability – less of code duplication, it can be reused in other systems.
• High fan-in – Refers to having a high number of classes that use a given class. High fan-in implies
that a system has been designed to make good use of utility classes at the lower levels in the system.
• Low-to-medium fan-out – a given class should use a low-to-medium number of other classes. High
fan-out (more than about seven) indicates a class uses a large number of other classes and may be
overly complex.
• Portability – program can be run on lot of computers without complex configuration.
• Leanness – no redundant modules/classes/functionalities.
• Stratification – try to keep the levels of decomposition stratified so you can view the system at any
single level without dipping into other levels.
• Standard techniques – Give the whole system a familiar feeling by using standardized, common
approaches.
SOLID design principles
• SRP: Single Responsibility Principle – There should never be more than one reason
for a class to change.
• OCP: Open/Closed Principle – Software entities (classes, modules, functions, etc.)
should be open for extension, but closed for modification.
• LSP: Liskov Substitution Principle – Functions that use pointers or references to
base classes must be able to use objects of derived classes without knowing it.
• ISP: Interface Segregation Principle – Clients should not be forced to depend on
methods that they do not use.
• DIP: Dependency Inversion Principle – 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.
Single Responsibility Principle (SRP)
There should never be more than one reason for a class to change.
Violation example:
public class EntityFactory implements IEntityFactory
{
private Map<String, String> loadPropertiesFromFile(String fileName)
{
...
}
@Override
public Entity createEntity()
{
final Map<String, String> properties = loadPropertiesFromFile("entity.properties");
return new Entity(properties.get("name"));
}
}
Single Responsibility Principle (SRP)
There should never be more than one reason for a class to change.
Violation example:
After refactoring:
public class EntityFactory implements IEntityFactory
{
private Map<String, String> loadPropertiesFromFile(String fileName)
{
...
}
@Override
public Entity createEntity()
{
final Map<String, String> properties = loadPropertiesFromFile("entity.properties");
return new Entity(properties.get("name"));
}
}
public class EntityFactory implements IEntityFactory
{
@Override
public Entity createEntity(final Map<String, String> properties)
{
if (properties == null) {
throw new IllegalArgumentException("Properties must not be null");
}
return new Entity(properties.get("name"));
}
}
Open/Closed Principle (OCP)
Software entities (classes, modules, functions, etc.) should be open for
extension, but closed for modification.
Violation example:
public interface BeanSearcher {
public Bean findById(Long id);
}
public interface BeanSearcher {
public Bean findById(Long id);
public Bean findByName(String name);
}
extension
Open/Closed Principle (OCP)
Software entities (classes, modules, functions, etc.) should be open for
extension, but closed for modification.
Violation example:
After refactoring:
public interface BeanSearcher {
public Bean findById(Long id);
}
public interface BeanSearcher {
public Bean findByQuery(SearchQuery query);
}
public class IdSearchQuery extends SearchQuery {}
public class NameSearchQuery extends SearchQuery {}
public interface BeanSearcher {
public Bean findById(Long id);
public Bean findByName(String name);
}
extension
Liskov Substitution Principle (LSP)
Functions that use pointers or references to base classes must be able to use
objects of derived classes without knowing it.
Violation example:
class Rectangle
{
protected int width;
protected int height;
public void setWidth(int w)
{
this.width = w;
}
public void setHeight(int h)
{
this.height = h;
}
public int calculateRectangleArea()
{
return width * height;
}
}
class Square extends Rectangle
{
@Override
public void setWidth(int w)
{
this.width = w;
this.height = w;
}
@Override
public void setHeight(int h)
{
this.width = h;
this.height = h;
}
}
private Rectangle rectangle = new Square();
@Test
public void rectangle()
{
rectangle.setHeight(2);
rectangle.setWidth(3);
Assert.assertEquals(rectangle.calculateRectangleArea(), 6);
}
Interface Segregation Principle (ISP)
Clients should not be forced to depend on methods that they do not use.
Violation example:
interface ProcessListener
{
public void onProcessStart(Process p);
public void onProcessEnd(Process p);
}
class NewProcessRegistrator implements ProcessListener
{
public void onProcessStart(Process p)
{
registerProcess(p);
}
public void onProcessEnd(Process p)
{
// nothing to do.
}
…
}
Interface Segregation Principle (ISP)
Clients should not be forced to depend on methods that they do not use.
Violation example:
interface ProcessListener
{
public void onProcessStart(Process p);
public void onProcessEnd(Process p);
}
class NewProcessRegistrator implements ProcessListener
{
public void onProcessStart(Process p)
{
registerProcess(p);
}
public void onProcessEnd(Process p)
{
// nothing to do.
}
…
}
interface ProcessStartupListener
{
public void onProcessStart(Process p);
}
interface ProcessShutdownListener
{
public void onProcessEnd(Process p);
}
interface ProcessListener extends
ProcessStartupListener, ProcessShutdownListener
{
}
class NewProcessRegistrator implements ProcessStartupListener
{
public void onProcessStart(Process p)
{
registerProcess(p);
}
…
}
refactoring
Dependency Inversion Principle (DIP)
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.
Violation example:
• Direct instantiation: new SomeObject();
• Static methods: ServiceLocator.getObject();
• Interface contains field on a class: interface A { final Service SERVICE = new Service(); }
CI
CC
II
IC
depends depends
depends depends
A
D
K
E
H
F
G
C
B
Any OOP designed software is a set of interacting objects.
A class instance can have own lifecycle (scope, lifetime).
The problems are:
• Who should take care about instance creation and lifecycle?
• How to share one service instance between many others?
• How to reuse classes in deferent environment ?
use
use
use
use
use
Inversion Of Control and Dependency Injection
1) Create it by yourself.
2) Ask someone to find/create it:
• Locator (for instance)
• Factory (for new instance)
3) Someone puts it to you. («Don’t call us. We’ll call you.»)
A B
use
// direct instantiation.
class A {
private B b = new B();
public void doSomething() {
b.someCall();
}
}
// Ask locator for component
class A {
private B b = Locator.getB();
public void doSomething() {
b.someCall();
}
}
// Create component with
// factory
class A {
private B b =
Factory.createB();
public void doSomething() {
b.someCall();
}
}
// Someone puts component
class A {
private B b;
public A(B b) {
this.b = b;
}
public void doSomething() {
b.someCall();
}
}
Inversion Of Control and Dependency Injection
C
S1
I1 S2
Test
Stub
use
impl
I2
S3
Test
Stub
C
S1
I1 S2
Test
Stub
use
impl
I2
S3
Test
Stub
Runtime configuration: Test configuration:
Some IoC frameworks (for example Spring) make possible to change dependency
configuration without any code modification.
Inversion Of Control and Dependency Injection
<?xml version="1.0" encoding="windows-1251"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="service1" class="com.mycompany.springexample.services.ServiceImpl1" />
<bean id="service2" class="com.mycompany.springexample.services.ServiceImpl2" />
<bean id="client1" class="com.mycompany.springexample.client.Client" >
<property name="service1" ref="service1" />
<property name="service2" ref="service2" />
</bean>
</beans>
<?xml version="1.0" encoding="windows-1251"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="service1" class="com.mycompany.springexample.services.stub.ServiceStub1" />
<bean id="service2" class="com.mycompany.springexample.services.stub.ServiceStub2" />
<bean id="client1" class="com.mycompany.springexample.client.Client" >
<property name="service1" ref=“service1" />
<property name="service2" ref=“service2" />
</bean>
</beans>
Runtime Configuration
Test Configuration
Beans linkage definition
Law of Demeter principle (LoD)
• Each unit should only use a limited set of other units: only units
“closely” related to the current unit.
• “Each unit should only talk to its friends. Don’t talk to strangers.”
Main Motivation: Control information overload. We can only keep a
limited set of items in short-term memory.
Benefits: Loosely coupled classes.
LoD violation example:
A B C A M
B C
D
A knows B’s dependencies A knows
M’s inner structure
Law of Demeter violation code example
class A
{
public String getMessage()
{
return "Message";
}
}
public class Main
{
public static void main(String[] args)
{
new B().printMessage(new A());
}
}
class B
{
public void printMessage(A a)
{
System.out.println(a.getMessage());
}
}
Law of Demeter violation code example
class A
{
public String getMessage()
{
return "Message";
}
}
public class Main
{
public static void main(String[] args)
{
new B().printMessage(new A());
}
}
refactoring
class B
{
public void printMessage(A a)
{
System.out.println(a.getMessage());
}
}
public class Main
{
public static void main(String[] args)
{
A a = new A();
String message = a.getMessage();
new B().printMessage(message);
}
}
class B
{
public void printMessage(String message)
{
System.out.println(message);
}
}
Package design principles
Cohesion
• RREP: Release Reuse Equivalency Principle – The granule of reuse is the granule of release.
Only components that are released through a tracking system can be effectively reused. This
granule is the package.
• CCP: Common Closure Principle – The classes in a package should be closed together against
the same kinds of changes. A change that affects a package affects all the classes in that
package.
• CRP: Common Reuse Principle – The classes in a package are reused together. If you reuse
one of the classes in a package, you reuse them all.
Coupling
• ADP: Acyclic Dependencies Principle – The dependency structure between packages must be
a directed acyclic graph (DAG). That is, there must be no cycles in the dependency structure.
• SDP: Stable Dependencies Principle – The dependencies between packages in a design should
be in the direction of the stability of the packages. A package should only depend upon
packages that are more stable that it is.
• SAP: Stable Abstractions Principle – Packages that are maximally stable should be maximally
abstract. Instable packages should be concrete. The abstraction of a package should be in
proportion to its stability.
TUF & TUC
TUF – Test Unfriendly Features
• Database access
• File system access
• Network access
• Access to side effecting APIs (GUI, etc)
• Lengthy computations
• Inscrutable computations
(computations which are hard to test
because they are difficult to understand)
• Static variable usage
Never hide a TUF within a TUC
TUC – Test Unfriendly Constructs
• Final Methods
• Final Classes
• Static Methods
• Private Methods
• Static Initialization Expressions
• Static Initialization Blocks
• Constructors
• Object Initialization Blocks
• New‐Expressions
GRASP design patterns
• Information Expert – A general principal of object design and responsibility
assignment?
• Creator – Who creates?
• Controller – What first object beyond the UI layer receives and coordinates a
system operation?
• Low Coupling – How to reduce the impact of change?
• High Cohesion – How to keep objects focused, understandable, and manageable?
• Polymorphism – Who is responsible when behavior varies by type?
• Pure Fabrication – Who is responsible when you are desperate, and do not want to
violate high cohesion and low coupling?
• Indirection – How to assign responsibilities to avoid direct coupling?
• Protected Variations – How to assign responsibilities so that the variations or
instability in the elements do not have an undesirable impact on other elements?
GoF design patterns
Behavioral
Chain of responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template method
Visitor
Creational
Abstract factory
Builder
Factory method
Prototype
Singleton
Structural
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
• http://www.oodesign.com/ - Design principles, GoF patterns
• http://en.wikipedia.org/wiki/GRASP_%28Object_Oriented_Design%29 – GRASP patterns.
• http://www.c2.com/cgi/wiki?LawOfDemeter – Law Of Demeter description.
• Working Effectively with Legacy Code; Michael Feathers, 2006.
• Clean Code: A Handbook of Agile Software Craftsmanship; Robert C. Martin, 2008
• Agile Software Development, Principles, Patterns, and Practices; Robert C. Martin
Additional Information

More Related Content

PPTX
Scan insertion
PPTX
Spyglass dft
PDF
Design for Testability
PPTX
Design for testability and automatic test pattern generation
PPT
01 Transition Fault Detection methods by Swetha
PDF
ATPG Methods and Algorithms
PDF
Automatic Test Pattern Generation (Testing of VLSI Design)
Scan insertion
Spyglass dft
Design for Testability
Design for testability and automatic test pattern generation
01 Transition Fault Detection methods by Swetha
ATPG Methods and Algorithms
Automatic Test Pattern Generation (Testing of VLSI Design)

What's hot (20)

PPTX
ATPG flow chart
PDF
Design-for-Test (Testing of VLSI Design)
PDF
Transition fault detection
PPTX
Dft (design for testability)
PPTX
Fault equivalence and fault location
PDF
Fault Simulation (Testing of VLSI Design)
PPTX
Vlsi physical design automation on partitioning
PDF
Synchronous and asynchronous clock
PDF
Static_Timing_Analysis_in_detail.pdf
PDF
2019 5 testing and verification of vlsi design_fault_modeling
ODP
Scan chain operation
PPT
VLSI routing
PPTX
1.Week1.pptx
PDF
Physical design-complete
PDF
Sta by usha_mehta
PPTX
System partitioning in VLSI and its considerations
PDF
Design for Test [DFT]-1 (1).pdf DESIGN DFT
PDF
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...
PPTX
faults in digital systems
PPTX
DRCs.pptx
ATPG flow chart
Design-for-Test (Testing of VLSI Design)
Transition fault detection
Dft (design for testability)
Fault equivalence and fault location
Fault Simulation (Testing of VLSI Design)
Vlsi physical design automation on partitioning
Synchronous and asynchronous clock
Static_Timing_Analysis_in_detail.pdf
2019 5 testing and verification of vlsi design_fault_modeling
Scan chain operation
VLSI routing
1.Week1.pptx
Physical design-complete
Sta by usha_mehta
System partitioning in VLSI and its considerations
Design for Test [DFT]-1 (1).pdf DESIGN DFT
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...
faults in digital systems
DRCs.pptx
Ad

Similar to Design for Testability (20)

PPT
P Training Presentation
PDF
L03 Software Design
PPTX
SOLID & IoC Principles
PDF
Refactoring_Rosenheim_2008_Workshop
PPTX
L06 Using Design Patterns
PPTX
UNIT IV DESIGN PATTERNS.pptx
PPS
Jump start to OOP, OOAD, and Design Pattern
PPT
Jump Start To Ooad And Design Patterns
PPT
Object Oriented Concepts and Principles
PPTX
Unit - I Intro. to OOP Concepts and Control Structure -OOP and CG (2024 Patte...
PDF
Linux Assignment 3
PDF
EKON28 - Beyond Legacy Apps with mORMot 2
PDF
The maze of Design Patterns & SOLID Principles
PPT
Linq To The Enterprise
PPTX
Design principles - SOLID
PPTX
Week 2 SREE.pptx Software reengieering ucp sllides
PDF
Object-oriented design principles
PPTX
The art of architecture
PDF
Introduction to OpenSees by Frank McKenna
PDF
C# Advanced L07-Design Patterns
P Training Presentation
L03 Software Design
SOLID & IoC Principles
Refactoring_Rosenheim_2008_Workshop
L06 Using Design Patterns
UNIT IV DESIGN PATTERNS.pptx
Jump start to OOP, OOAD, and Design Pattern
Jump Start To Ooad And Design Patterns
Object Oriented Concepts and Principles
Unit - I Intro. to OOP Concepts and Control Structure -OOP and CG (2024 Patte...
Linux Assignment 3
EKON28 - Beyond Legacy Apps with mORMot 2
The maze of Design Patterns & SOLID Principles
Linq To The Enterprise
Design principles - SOLID
Week 2 SREE.pptx Software reengieering ucp sllides
Object-oriented design principles
The art of architecture
Introduction to OpenSees by Frank McKenna
C# Advanced L07-Design Patterns
Ad

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Modernizing your data center with Dell and AMD
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Approach and Philosophy of On baking technology
PDF
KodekX | Application Modernization Development
PDF
Empathic Computing: Creating Shared Understanding
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
Teaching material agriculture food technology
Cloud computing and distributed systems.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25 Week I
Understanding_Digital_Forensics_Presentation.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Modernizing your data center with Dell and AMD
Review of recent advances in non-invasive hemoglobin estimation
Reach Out and Touch Someone: Haptics and Empathic Computing
Approach and Philosophy of On baking technology
KodekX | Application Modernization Development
Empathic Computing: Creating Shared Understanding
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Spectral efficient network and resource selection model in 5G networks
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Teaching material agriculture food technology

Design for Testability

  • 2. Design for testability «One reasonable definition of good design is testability. It is hard to imagine a software system that is both testable and poorly designed. It is also hard to imagine a software system that is well designed but also untestable» Robert C. Martin. Design for testability – is improving quality of software design as well as possibility to write tests for the code.
  • 3. Symptoms of poor design • Rigidity – System is hard to change. • Fragility – Changes causes system to break easily and require other changes. • Immobility – Difficult to entangle components that can be reused in other systems. • Viscosity – Doing things right is harder than doing things wrong. • Needless Complexity – System contains infrastructure that has no direct benefit. • Needless Repetition – Repeated structures that should have a single abstraction. • Opacity – Code is hard to understand.
  • 4. Symptoms of good design • Minimal complexity – Avoid making “clever“ designs. Clever designs are usually hard to understand. Keep it simple. • Ease of maintenance – it is easy to understand and make changes. • Loose coupling – Loose coupling means designing so that you hold connections among different parts of a program to a minimum. • Extensibility – You should be able to change a piece of the system without causing a huge impact to other pieces of the system. • Reusability – less of code duplication, it can be reused in other systems. • High fan-in – Refers to having a high number of classes that use a given class. High fan-in implies that a system has been designed to make good use of utility classes at the lower levels in the system. • Low-to-medium fan-out – a given class should use a low-to-medium number of other classes. High fan-out (more than about seven) indicates a class uses a large number of other classes and may be overly complex. • Portability – program can be run on lot of computers without complex configuration. • Leanness – no redundant modules/classes/functionalities. • Stratification – try to keep the levels of decomposition stratified so you can view the system at any single level without dipping into other levels. • Standard techniques – Give the whole system a familiar feeling by using standardized, common approaches.
  • 5. SOLID design principles • SRP: Single Responsibility Principle – There should never be more than one reason for a class to change. • OCP: Open/Closed Principle – Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. • LSP: Liskov Substitution Principle – Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. • ISP: Interface Segregation Principle – Clients should not be forced to depend on methods that they do not use. • DIP: Dependency Inversion Principle – 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.
  • 6. Single Responsibility Principle (SRP) There should never be more than one reason for a class to change. Violation example: public class EntityFactory implements IEntityFactory { private Map<String, String> loadPropertiesFromFile(String fileName) { ... } @Override public Entity createEntity() { final Map<String, String> properties = loadPropertiesFromFile("entity.properties"); return new Entity(properties.get("name")); } }
  • 7. Single Responsibility Principle (SRP) There should never be more than one reason for a class to change. Violation example: After refactoring: public class EntityFactory implements IEntityFactory { private Map<String, String> loadPropertiesFromFile(String fileName) { ... } @Override public Entity createEntity() { final Map<String, String> properties = loadPropertiesFromFile("entity.properties"); return new Entity(properties.get("name")); } } public class EntityFactory implements IEntityFactory { @Override public Entity createEntity(final Map<String, String> properties) { if (properties == null) { throw new IllegalArgumentException("Properties must not be null"); } return new Entity(properties.get("name")); } }
  • 8. Open/Closed Principle (OCP) Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. Violation example: public interface BeanSearcher { public Bean findById(Long id); } public interface BeanSearcher { public Bean findById(Long id); public Bean findByName(String name); } extension
  • 9. Open/Closed Principle (OCP) Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. Violation example: After refactoring: public interface BeanSearcher { public Bean findById(Long id); } public interface BeanSearcher { public Bean findByQuery(SearchQuery query); } public class IdSearchQuery extends SearchQuery {} public class NameSearchQuery extends SearchQuery {} public interface BeanSearcher { public Bean findById(Long id); public Bean findByName(String name); } extension
  • 10. Liskov Substitution Principle (LSP) Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. Violation example: class Rectangle { protected int width; protected int height; public void setWidth(int w) { this.width = w; } public void setHeight(int h) { this.height = h; } public int calculateRectangleArea() { return width * height; } } class Square extends Rectangle { @Override public void setWidth(int w) { this.width = w; this.height = w; } @Override public void setHeight(int h) { this.width = h; this.height = h; } } private Rectangle rectangle = new Square(); @Test public void rectangle() { rectangle.setHeight(2); rectangle.setWidth(3); Assert.assertEquals(rectangle.calculateRectangleArea(), 6); }
  • 11. Interface Segregation Principle (ISP) Clients should not be forced to depend on methods that they do not use. Violation example: interface ProcessListener { public void onProcessStart(Process p); public void onProcessEnd(Process p); } class NewProcessRegistrator implements ProcessListener { public void onProcessStart(Process p) { registerProcess(p); } public void onProcessEnd(Process p) { // nothing to do. } … }
  • 12. Interface Segregation Principle (ISP) Clients should not be forced to depend on methods that they do not use. Violation example: interface ProcessListener { public void onProcessStart(Process p); public void onProcessEnd(Process p); } class NewProcessRegistrator implements ProcessListener { public void onProcessStart(Process p) { registerProcess(p); } public void onProcessEnd(Process p) { // nothing to do. } … } interface ProcessStartupListener { public void onProcessStart(Process p); } interface ProcessShutdownListener { public void onProcessEnd(Process p); } interface ProcessListener extends ProcessStartupListener, ProcessShutdownListener { } class NewProcessRegistrator implements ProcessStartupListener { public void onProcessStart(Process p) { registerProcess(p); } … } refactoring
  • 13. Dependency Inversion Principle (DIP) 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. Violation example: • Direct instantiation: new SomeObject(); • Static methods: ServiceLocator.getObject(); • Interface contains field on a class: interface A { final Service SERVICE = new Service(); } CI CC II IC depends depends depends depends
  • 14. A D K E H F G C B Any OOP designed software is a set of interacting objects. A class instance can have own lifecycle (scope, lifetime). The problems are: • Who should take care about instance creation and lifecycle? • How to share one service instance between many others? • How to reuse classes in deferent environment ? use use use use use Inversion Of Control and Dependency Injection
  • 15. 1) Create it by yourself. 2) Ask someone to find/create it: • Locator (for instance) • Factory (for new instance) 3) Someone puts it to you. («Don’t call us. We’ll call you.») A B use // direct instantiation. class A { private B b = new B(); public void doSomething() { b.someCall(); } } // Ask locator for component class A { private B b = Locator.getB(); public void doSomething() { b.someCall(); } } // Create component with // factory class A { private B b = Factory.createB(); public void doSomething() { b.someCall(); } } // Someone puts component class A { private B b; public A(B b) { this.b = b; } public void doSomething() { b.someCall(); } } Inversion Of Control and Dependency Injection
  • 16. C S1 I1 S2 Test Stub use impl I2 S3 Test Stub C S1 I1 S2 Test Stub use impl I2 S3 Test Stub Runtime configuration: Test configuration: Some IoC frameworks (for example Spring) make possible to change dependency configuration without any code modification. Inversion Of Control and Dependency Injection
  • 17. <?xml version="1.0" encoding="windows-1251"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="service1" class="com.mycompany.springexample.services.ServiceImpl1" /> <bean id="service2" class="com.mycompany.springexample.services.ServiceImpl2" /> <bean id="client1" class="com.mycompany.springexample.client.Client" > <property name="service1" ref="service1" /> <property name="service2" ref="service2" /> </bean> </beans> <?xml version="1.0" encoding="windows-1251"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="service1" class="com.mycompany.springexample.services.stub.ServiceStub1" /> <bean id="service2" class="com.mycompany.springexample.services.stub.ServiceStub2" /> <bean id="client1" class="com.mycompany.springexample.client.Client" > <property name="service1" ref=“service1" /> <property name="service2" ref=“service2" /> </bean> </beans> Runtime Configuration Test Configuration Beans linkage definition
  • 18. Law of Demeter principle (LoD) • Each unit should only use a limited set of other units: only units “closely” related to the current unit. • “Each unit should only talk to its friends. Don’t talk to strangers.” Main Motivation: Control information overload. We can only keep a limited set of items in short-term memory. Benefits: Loosely coupled classes. LoD violation example: A B C A M B C D A knows B’s dependencies A knows M’s inner structure
  • 19. Law of Demeter violation code example class A { public String getMessage() { return "Message"; } } public class Main { public static void main(String[] args) { new B().printMessage(new A()); } } class B { public void printMessage(A a) { System.out.println(a.getMessage()); } }
  • 20. Law of Demeter violation code example class A { public String getMessage() { return "Message"; } } public class Main { public static void main(String[] args) { new B().printMessage(new A()); } } refactoring class B { public void printMessage(A a) { System.out.println(a.getMessage()); } } public class Main { public static void main(String[] args) { A a = new A(); String message = a.getMessage(); new B().printMessage(message); } } class B { public void printMessage(String message) { System.out.println(message); } }
  • 21. Package design principles Cohesion • RREP: Release Reuse Equivalency Principle – The granule of reuse is the granule of release. Only components that are released through a tracking system can be effectively reused. This granule is the package. • CCP: Common Closure Principle – The classes in a package should be closed together against the same kinds of changes. A change that affects a package affects all the classes in that package. • CRP: Common Reuse Principle – The classes in a package are reused together. If you reuse one of the classes in a package, you reuse them all. Coupling • ADP: Acyclic Dependencies Principle – The dependency structure between packages must be a directed acyclic graph (DAG). That is, there must be no cycles in the dependency structure. • SDP: Stable Dependencies Principle – The dependencies between packages in a design should be in the direction of the stability of the packages. A package should only depend upon packages that are more stable that it is. • SAP: Stable Abstractions Principle – Packages that are maximally stable should be maximally abstract. Instable packages should be concrete. The abstraction of a package should be in proportion to its stability.
  • 22. TUF & TUC TUF – Test Unfriendly Features • Database access • File system access • Network access • Access to side effecting APIs (GUI, etc) • Lengthy computations • Inscrutable computations (computations which are hard to test because they are difficult to understand) • Static variable usage Never hide a TUF within a TUC TUC – Test Unfriendly Constructs • Final Methods • Final Classes • Static Methods • Private Methods • Static Initialization Expressions • Static Initialization Blocks • Constructors • Object Initialization Blocks • New‐Expressions
  • 23. GRASP design patterns • Information Expert – A general principal of object design and responsibility assignment? • Creator – Who creates? • Controller – What first object beyond the UI layer receives and coordinates a system operation? • Low Coupling – How to reduce the impact of change? • High Cohesion – How to keep objects focused, understandable, and manageable? • Polymorphism – Who is responsible when behavior varies by type? • Pure Fabrication – Who is responsible when you are desperate, and do not want to violate high cohesion and low coupling? • Indirection – How to assign responsibilities to avoid direct coupling? • Protected Variations – How to assign responsibilities so that the variations or instability in the elements do not have an undesirable impact on other elements?
  • 24. GoF design patterns Behavioral Chain of responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template method Visitor Creational Abstract factory Builder Factory method Prototype Singleton Structural Adapter Bridge Composite Decorator Facade Flyweight Proxy
  • 25. • http://www.oodesign.com/ - Design principles, GoF patterns • http://en.wikipedia.org/wiki/GRASP_%28Object_Oriented_Design%29 – GRASP patterns. • http://www.c2.com/cgi/wiki?LawOfDemeter – Law Of Demeter description. • Working Effectively with Legacy Code; Michael Feathers, 2006. • Clean Code: A Handbook of Agile Software Craftsmanship; Robert C. Martin, 2008 • Agile Software Development, Principles, Patterns, and Practices; Robert C. Martin Additional Information