SlideShare una empresa de Scribd logo
1 de 25
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

Más contenido relacionado

La actualidad más candente

ATPG Methods and Algorithms
ATPG Methods and AlgorithmsATPG Methods and Algorithms
ATPG Methods and Algorithms
Deiptii Das
 

La actualidad más candente (20)

ATPG Methods and Algorithms
ATPG Methods and AlgorithmsATPG Methods and Algorithms
ATPG Methods and Algorithms
 
Transition fault detection
Transition fault detectionTransition fault detection
Transition fault detection
 
2019 5 testing and verification of vlsi design_fault_modeling
2019 5 testing and verification of vlsi design_fault_modeling2019 5 testing and verification of vlsi design_fault_modeling
2019 5 testing and verification of vlsi design_fault_modeling
 
Fault simulation
Fault simulationFault simulation
Fault simulation
 
ATPG flow chart
ATPG flow chart ATPG flow chart
ATPG flow chart
 
VLSI testing and analysis
VLSI testing and analysisVLSI testing and analysis
VLSI testing and analysis
 
Vlsi testing
Vlsi testingVlsi testing
Vlsi testing
 
Design for Testability DfT Seminar
Design for Testability DfT SeminarDesign for Testability DfT Seminar
Design for Testability DfT Seminar
 
Introduction of testing and verification of vlsi design
Introduction of testing and verification of vlsi designIntroduction of testing and verification of vlsi design
Introduction of testing and verification of vlsi design
 
Spyglass dft
Spyglass dftSpyglass dft
Spyglass dft
 
1.Week1.pptx
1.Week1.pptx1.Week1.pptx
1.Week1.pptx
 
implementation of BIST
implementation of BISTimplementation of BIST
implementation of BIST
 
11 static timing_analysis_2_combinational_design
11 static timing_analysis_2_combinational_design11 static timing_analysis_2_combinational_design
11 static timing_analysis_2_combinational_design
 
Applications of ATPG
Applications of ATPGApplications of ATPG
Applications of ATPG
 
SOC design
SOC design SOC design
SOC design
 
Verification flow and_planning_vlsi_design
Verification flow and_planning_vlsi_designVerification flow and_planning_vlsi_design
Verification flow and_planning_vlsi_design
 
Tutorial getting started with RISC-V verification
Tutorial getting started with RISC-V verificationTutorial getting started with RISC-V verification
Tutorial getting started with RISC-V verification
 
I2C BUS PROTOCOL
I2C BUS PROTOCOLI2C BUS PROTOCOL
I2C BUS PROTOCOL
 
BUilt-In-Self-Test for VLSI Design
BUilt-In-Self-Test for VLSI DesignBUilt-In-Self-Test for VLSI Design
BUilt-In-Self-Test for VLSI Design
 
system verilog
system verilogsystem verilog
system verilog
 

Similar a Design for Testability

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
Daniel Egan
 

Similar a Design for Testability (20)

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Refactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopRefactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_Workshop
 
L06 Using Design Patterns
L06 Using Design PatternsL06 Using Design Patterns
L06 Using Design Patterns
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID Principles
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
 
The art of architecture
The art of architectureThe art of architecture
The art of architecture
 
Introduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKennaIntroduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKenna
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandt
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_ppt
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

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