SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

Dft (design for testability)
Dft (design for testability)Dft (design for testability)
Dft (design for testability)shaik sharief
 
Design-for-Test (Testing of VLSI Design)
Design-for-Test (Testing of VLSI Design)Design-for-Test (Testing of VLSI Design)
Design-for-Test (Testing of VLSI Design)Usha Mehta
 
Design for testability and automatic test pattern generation
Design for testability and automatic test pattern generationDesign for testability and automatic test pattern generation
Design for testability and automatic test pattern generationDilip Mathuria
 
2019 2 testing and verification of vlsi design_verification
2019 2 testing and verification of vlsi design_verification2019 2 testing and verification of vlsi design_verification
2019 2 testing and verification of vlsi design_verificationUsha Mehta
 
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 designUsha Mehta
 
Loc, los and loes at speed testing methodologies for automatic test pattern g...
Loc, los and loes at speed testing methodologies for automatic test pattern g...Loc, los and loes at speed testing methodologies for automatic test pattern g...
Loc, los and loes at speed testing methodologies for automatic test pattern g...eSAT Journals
 
Functional verification techniques EW16 session
Functional verification techniques  EW16 sessionFunctional verification techniques  EW16 session
Functional verification techniques EW16 sessionSameh El-Ashry
 
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...Usha Mehta
 
Automatic Test Pattern Generation (Testing of VLSI Design)
Automatic Test Pattern Generation (Testing of VLSI Design)Automatic Test Pattern Generation (Testing of VLSI Design)
Automatic Test Pattern Generation (Testing of VLSI Design)Usha Mehta
 
6 verification tools
6 verification tools6 verification tools
6 verification toolsUsha Mehta
 
3 test economic_test_equipments_yield
3 test economic_test_equipments_yield3 test economic_test_equipments_yield
3 test economic_test_equipments_yieldUsha Mehta
 
Design for Test [DFT]-1 (1).pdf DESIGN DFT
Design for Test [DFT]-1 (1).pdf DESIGN DFTDesign for Test [DFT]-1 (1).pdf DESIGN DFT
Design for Test [DFT]-1 (1).pdf DESIGN DFTjayasreenimmakuri777
 
SOC Verification using SystemVerilog
SOC Verification using SystemVerilog SOC Verification using SystemVerilog
SOC Verification using SystemVerilog Ramdas Mozhikunnath
 

Mais procurados (20)

Dft (design for testability)
Dft (design for testability)Dft (design for testability)
Dft (design for testability)
 
5. DFT.pptx
5. DFT.pptx5. DFT.pptx
5. DFT.pptx
 
DRCs.pptx
DRCs.pptxDRCs.pptx
DRCs.pptx
 
Design-for-Test (Testing of VLSI Design)
Design-for-Test (Testing of VLSI Design)Design-for-Test (Testing of VLSI Design)
Design-for-Test (Testing of VLSI Design)
 
Burst clock controller
Burst clock controllerBurst clock controller
Burst clock controller
 
Design for testability and automatic test pattern generation
Design for testability and automatic test pattern generationDesign for testability and automatic test pattern generation
Design for testability and automatic test pattern generation
 
2019 2 testing and verification of vlsi design_verification
2019 2 testing and verification of vlsi design_verification2019 2 testing and verification of vlsi design_verification
2019 2 testing and verification of vlsi design_verification
 
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
 
VLSI testing and analysis
VLSI testing and analysisVLSI testing and analysis
VLSI testing and analysis
 
Loc, los and loes at speed testing methodologies for automatic test pattern g...
Loc, los and loes at speed testing methodologies for automatic test pattern g...Loc, los and loes at speed testing methodologies for automatic test pattern g...
Loc, los and loes at speed testing methodologies for automatic test pattern g...
 
system verilog
system verilogsystem verilog
system verilog
 
Transition fault detection
Transition fault detectionTransition fault detection
Transition fault detection
 
Functional verification techniques EW16 session
Functional verification techniques  EW16 sessionFunctional verification techniques  EW16 session
Functional verification techniques EW16 session
 
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...
Deterministic Test Pattern Generation ( D-Algorithm of ATPG) (Testing of VLSI...
 
Automatic Test Pattern Generation (Testing of VLSI Design)
Automatic Test Pattern Generation (Testing of VLSI Design)Automatic Test Pattern Generation (Testing of VLSI Design)
Automatic Test Pattern Generation (Testing of VLSI Design)
 
6 verification tools
6 verification tools6 verification tools
6 verification tools
 
3 test economic_test_equipments_yield
3 test economic_test_equipments_yield3 test economic_test_equipments_yield
3 test economic_test_equipments_yield
 
Design for Test [DFT]-1 (1).pdf DESIGN DFT
Design for Test [DFT]-1 (1).pdf DESIGN DFTDesign for Test [DFT]-1 (1).pdf DESIGN DFT
Design for Test [DFT]-1 (1).pdf DESIGN DFT
 
SOC Verification using SystemVerilog
SOC Verification using SystemVerilog SOC Verification using SystemVerilog
SOC Verification using SystemVerilog
 
04~chapter 02 dft.ppt
04~chapter 02 dft.ppt04~chapter 02 dft.ppt
04~chapter 02 dft.ppt
 

Semelhante a Design for Testability

P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC PrinciplesPavlo Hodysh
 
Refactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopRefactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopMax Kleiner
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
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 PatternNishith Shukla
 
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 PatternsLalit Kale
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3Diane Allen
 
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 PrinciplesMuhammad Raza
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLIDPranalee Rokde
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principlesXiaoyan Chen
 
The art of architecture
The art of architectureThe art of architecture
The art of architectureADDQ
 
Introduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKennaIntroduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKennaopenseesdays
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
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 Fildebrandtmfrancis
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_pptagnes_crepet
 
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...Raffi Khatchadourian
 

Semelhante 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

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Último (20)

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

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