SlideShare a Scribd company logo
Design Code That's Easy to Test
Design for Testability
Better safe than sorry
It is better to do something carefully in advance than to su er later
Insu icient testing
No documentation
This never ends well
Eeasy to ignore or shortchange,
especially on projects with a
tight budget
Poor code quality
Smells really bad!
Technical debt
The implied cost of additional rework caused by choosing an easy
solution now instead of a better approach that would take longer
"Design the so ware to make it more easy to test"
Design for Testability
" The degree to which a system facilitates
the establishment of test criteria and the
performance of tests to determine whether
those criteria have been met "
IEEE, 1990 " Having reliable and convenient
interfaces to drive the execution
and verification of tests "
B. Pettichord
" Characteristic of a so ware
which allows it to be easily
and e iciently tested "
(Bach 1999, Gelperin 1999)
Testability
Which code is easier to test?
public class MyCalendar {
public boolean isWeekDay(){
int day = Calendar.getInstance()
.get(Calendar.DAY_OF_WEEK);
return day Calendar.SATURDAY
day Calendar.SUNDAY;
}
}
public class MyCalendar {
public boolean isWeekDay(Calendar calendar){
int day = calendar.get(Calendar.DAY_OF_WEEK);
return day Calendar.SATURDAY
day Calendar.SUNDAY;
}
}
Types of Testing
Unit Testing Integration Testing System Testing Acceptance Testing
and many others more
01 02 03 04
Map the issue to the
solution
Instantiating a class
and invoke methods
Isolation from dependencies Verify interactions
When writing unit tests we usually face some issues, such as
Dependency injection
A process used in unit testing when the unit being tested has external
dependencies. It aims to isolate and focus on the code being tested and not on
the behavior or state of the external dependencies
Mocking
A design pattern in which an object or function receives other objects or
functions that it depends on. It aims to separate the concerns of constructing
objects and using them, leading to a loosely coupled program
What would you do to easily instantiate classes
and invoke methods during testing?
Dependency injection Mocking Write clean code and avoid
private, final, and static
Question 1/3
Map the issue to a possible solution
Question 2/3
How would you prevent a class from
instantiating its own dependencies?
Dependency injection Mocking
Map the issue to a possible solution
Write clean code and avoid
private, final, and static
Question 3/3
How would you simulate the behavior of the real
object and eventually verify its interactions?
Dependency injection Mocking
Map the issue to a possible solution
Write clean code and avoid
private, final, and static
Congratulations!
Start over?
🎉
Be pragmatic and precise while doing it
Write Clean and
SOLID Code
1
Clean code
A code than any developer can read and change easily
Testable
Simple
Establish a baseline behaviour
and makes it easier to change
Increasing complexity makes the
code error-prone and di icult to
maintain
Focused
A piece of code should solve
only a specific problem
Beware Code Smells
Symptoms of poor design or implementation choices. Classes that experience those symptoms
are more change- and fault-prone than others
Bloaters
Hard to work with due to their
incresed proportions
Couplers
Contribute to excessive
coupling between classes
Long Method Large Class
Long Parameter List
Feature Envy Message Chain
Refactoring
It's always worth investigating if we can refactor our code to
make it more testable
Test early and o en
Instil a culture of
testing
2
" All so ware will be tested - either by you and your
team or by the eventual users - so you might as well
plan on testing it thoroughly "
Andrew Hunt, The Pragmatic Programmer
Test-driven development (TDD)
A so ware development approach in which test cases are developed to specify
and validate what the code will do
The TDD cycle
public class MyCalendar {
public boolean isWeekDay(Calendar calendar){
int day = calendar.get(Calendar.DAY_OF_WEEK);
return day Calendar.MONDAY day Calendar.TUESDAY
day Calendar.WEDNESDAY day Calendar.THURSDAY
day Calendar.FRIDAY;
}
}
void testIsWeekDay(){
var calendar = Calendar.getInstance()
.set(2022, 8, 2);
assert new MyCalendar().isWeekDay(calendar);
}
}
public class MyCalendar {
public boolean isWeekDay(Calendar calendar){
return false;
}
}
public class MyCalendar {
public boolean isWeekDay(Calendar calendar){
int day = calendar.get(Calendar.DAY_OF_WEEK);
return day Calendar.SATURDAY day Calendar.SUNDAY;
}
}
TDD forces you to think about design for testability upfront
TDD forces you to think about design for testability upfront
Not a silver bullet: still focuses on development than testing
Not a silver bullet: still focuses on development than testing
No better way to fix errors than preventing them
No better way to fix errors than preventing them
vs
Test early and o en
Instil a culture of
testing
2
Inject
Dependencies
3Yet, depend on abstractions, not on concretions
public class MyApp {
GithubService githubService = new GithubService();
public int countRepos(String token){
List<String> repos = new ArrayList ();
try{
githubService.authenticate(token);
repos = githubService.collectRepos();
}catch(TimeoutExceeded e){
;
}
return repos.size();
}
}
public class GithubService {
void authenticate(String token) throws TimeoutExceeded {
if(new Random().nextInt(5) 0)
throw new TimeoutExceeded();
Do something, e.g. set APIs quota
}
public List<String> collectRepos(){
return List.of("sdp/myrepo");
}
}
@Test
void testCollectRepos(){
MyApp app = MyApp();
assert app.countRepos("mytoken") 1;
}
@Test
void testCollectReposTimeoutExceeded(){
MyApp app = MyApp();
assert app.countRepos("mytoken") 0;
}
MyApp GithubService
Hard-coded dependency
If we want to switch to a different service in the future, e.g., a GitlabService or a
BitbucketService, it will require code changes in MyApp. This makes our
application hard to extend
Testing the application will be very difficult since our application is directly
instantiating the service. There is no way we can mock that object in our tests
Client
Service
ServiceInterface
Injector
4 Roles
depends on
implements
uses
injects
public class
public class MyApp {
MyApp {
GithubService githubService
GithubService githubService;
;
public
public MyApp(
MyApp(GithubService service
GithubService service){
){
githubService = service;
githubService = service;
}
}
public
public List<String>
List<String> collectRepos
collectRepos(String token){
(String token){
List<String> repos =
List<String> repos = new
new ArrayList ();
ArrayList ();
try
try{
{
githubService.authenticate(token);
githubService.authenticate(token);
repos = githubService.collectRepos()
repos = githubService.collectRepos()
}
}catch
catch(TimeoutExceeded e){
(TimeoutExceeded e){
;
;
}
}
return
return repos.size();
repos.size();
}
}
}
}
public class GithubService {
}
class LazyGithubService extends GithubService {
@Override
void authenticate(String token){
throw new TimeoutExceeded("You know I'm lazy :)");
}
}
@Test
void testCollectReposTimeoutExceeded(){
MyApp app = MyApp(new LazyGithubService());
var repos = app.countRepos("mytoken");
assert repos 0;
}
MyApp
GithubService
implementation
RepoHostingService
interface
GitlabService
implementation
public class GithubService implements RepoHostingService
{
@Override
void authenticate(String token){ };
}
public class GitlabService implements RepoHostingService
{
@Override
void authenticate(String token){ };
}
public class
public class MyApp {
MyApp {
RepoHostingService
RepoHostingService service
service;
;
public
public MyApp(
MyApp(RepoHostingService
RepoHostingService service){
service){
this.
this.service = service;
service = service;
}
}
}
}
public interface
public interface RepoHostingService {
RepoHostingService {
void
void authenticate
authenticate(String token);
(String token);
}
}
@Test
void testCollectGithubRepos(){
RepoHostingService service = new GithubService();
MyApp app = MyApp(service);
var repos = app.countRepos("mygithubtoken");
assert repos 1;
}
@Test
void testCollectGitlabRepos(){
RepoHostingService service = new GitlabService();
MyApp app = MyApp(service);
var repos = app.countRepos("mygitlabtoken");
assert repos 1;
}
@Test
void testCollectReposTimeoutExceededMock(){
String token = "mytoken";
RepoHostingService service = mock(GithubService.class);
doThrow(new TimeoutExceeded()).when(service)
.authenticate(token);
MyApp app = MyApp(service);
var repos = app.countRepos(token);
assert repos 0;
}
MyApp RepoHostingService
Injector GithubService
public class ServiceInjector {
public MyApp getConsumer(String hostingService) {
var service = switch(hostingService) {
case "github" new GithubService();
case "gitlab" new GitlabService();
}
return new MyApp(service);
}
}
Eases testing by enabling mocking and stubbing
Eases testing by enabling mocking and stubbing
Eases extension by depending on abstractions
Eases extension by depending on abstractions
vs
With frameworks like Spring, boilerplate code is reduced
With frameworks like Spring, boilerplate code is reduced
If overused can lead to management issues
If overused can lead to management issues
Many compile-time errors are pushed to run-time
Many compile-time errors are pushed to run-time
Tricky to understand at the beginning
Tricky to understand at the beginning
Yet, depend on abstractions, not on concretions
Inject
dependencies
3
Avoid private &
static
4When possible
Protected methods are accessible by the unit test if it is
located in the same package as the unit to test, though
still under a di erent root directory
Turning private
into protected
Avoid static methods
Static methods can't be overridden and replaced and
therefore are harder to fake; they require a combination of
frameworks to be tested
Write clean and SOLID code
Following good design
practices leads to a more
testable system
Avoid private & static
Private and static methods can't
be overridden and replaced and
therefore are harder to fake
Inject dependencies
This will allow fakes to be
inserted instead of real logic,
making isolation easy
Instil a culture of testing
Early testing guides
(re)design
Design for Testability Recommendations
Avoid code smells
And investigate refactoring
before taking design
decisions
No one-size-fits-all
Excercise judgement when designing and testing by considering the
interactions between them, and pros and cons of each decision
What are the recommedation
most import to you...
Create your own standings by sorting the boxes
Avoid code smells
Instil a culture of testing
Inject dependencies
Write clean code
1)
2)
3)
4)
5) Avoid statics & privates
and your questions?
Oops not correct
Try again!

More Related Content

Similar to Design for Testability

Unit Testing
Unit TestingUnit Testing
Unit Testing
Stanislav Tiurikov
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!
Paco van Beckhoven
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Testing in android
Testing in androidTesting in android
Testing in android
jtrindade
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
Godfrey Nolan
 
Webinar: Whats New in Java 8 with Develop Intelligence
Webinar: Whats New in Java 8 with Develop IntelligenceWebinar: Whats New in Java 8 with Develop Intelligence
Webinar: Whats New in Java 8 with Develop Intelligence
AMD Developer Central
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Ukraine
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
Jitendra Zaa
 
Rspec
RspecRspec
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
Software Testing
Software TestingSoftware Testing
Software Testing
AdroitLogic
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
liminescence
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Flutter Agency
 
How I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeHow I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy Code
Gene Gotimer
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
Eugene Dvorkin
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD Techniques
David Rodenas
 

Similar to Design for Testability (20)

Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Testing in android
Testing in androidTesting in android
Testing in android
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
 
Webinar: Whats New in Java 8 with Develop Intelligence
Webinar: Whats New in Java 8 with Develop IntelligenceWebinar: Whats New in Java 8 with Develop Intelligence
Webinar: Whats New in Java 8 with Develop Intelligence
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
Rspec
RspecRspec
Rspec
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
How I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeHow I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy Code
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD Techniques
 

More from Stefano Dalla Palma

Introduction to Mutation Testing
Introduction to Mutation TestingIntroduction to Mutation Testing
Introduction to Mutation Testing
Stefano Dalla Palma
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural Networks
Stefano Dalla Palma
 
Decision Tree learning
Decision Tree learningDecision Tree learning
Decision Tree learning
Stefano Dalla Palma
 
Introduction to Machine Learning with examples in R
Introduction to Machine Learning with examples in RIntroduction to Machine Learning with examples in R
Introduction to Machine Learning with examples in R
Stefano Dalla Palma
 
Introduction to Machine Learning concepts
Introduction to Machine Learning conceptsIntroduction to Machine Learning concepts
Introduction to Machine Learning concepts
Stefano Dalla Palma
 
Apache Mahout Architecture Overview
Apache Mahout Architecture OverviewApache Mahout Architecture Overview
Apache Mahout Architecture Overview
Stefano Dalla Palma
 
An Empirical Study on Bounded Model Checking
An Empirical Study on Bounded Model CheckingAn Empirical Study on Bounded Model Checking
An Empirical Study on Bounded Model Checking
Stefano Dalla Palma
 
UML, ER and Dimensional Modelling
UML, ER and Dimensional ModellingUML, ER and Dimensional Modelling
UML, ER and Dimensional Modelling
Stefano Dalla Palma
 
VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...
VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...
VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...
Stefano Dalla Palma
 
Detecting controversy in microposts: an approach based on word similarity wit...
Detecting controversy in microposts: an approach based on word similarity wit...Detecting controversy in microposts: an approach based on word similarity wit...
Detecting controversy in microposts: an approach based on word similarity wit...
Stefano Dalla Palma
 
Prolog in a nutshell
Prolog in a nutshellProlog in a nutshell
Prolog in a nutshell
Stefano Dalla Palma
 

More from Stefano Dalla Palma (11)

Introduction to Mutation Testing
Introduction to Mutation TestingIntroduction to Mutation Testing
Introduction to Mutation Testing
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural Networks
 
Decision Tree learning
Decision Tree learningDecision Tree learning
Decision Tree learning
 
Introduction to Machine Learning with examples in R
Introduction to Machine Learning with examples in RIntroduction to Machine Learning with examples in R
Introduction to Machine Learning with examples in R
 
Introduction to Machine Learning concepts
Introduction to Machine Learning conceptsIntroduction to Machine Learning concepts
Introduction to Machine Learning concepts
 
Apache Mahout Architecture Overview
Apache Mahout Architecture OverviewApache Mahout Architecture Overview
Apache Mahout Architecture Overview
 
An Empirical Study on Bounded Model Checking
An Empirical Study on Bounded Model CheckingAn Empirical Study on Bounded Model Checking
An Empirical Study on Bounded Model Checking
 
UML, ER and Dimensional Modelling
UML, ER and Dimensional ModellingUML, ER and Dimensional Modelling
UML, ER and Dimensional Modelling
 
VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...
VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...
VCCFinder: Finding Potential Vulnerabilities in Open-Source Projects to Assis...
 
Detecting controversy in microposts: an approach based on word similarity wit...
Detecting controversy in microposts: an approach based on word similarity wit...Detecting controversy in microposts: an approach based on word similarity wit...
Detecting controversy in microposts: an approach based on word similarity wit...
 
Prolog in a nutshell
Prolog in a nutshellProlog in a nutshell
Prolog in a nutshell
 

Recently uploaded

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
NishanthaBulumulla1
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 

Recently uploaded (20)

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 

Design for Testability

  • 1. Design Code That's Easy to Test Design for Testability
  • 2. Better safe than sorry It is better to do something carefully in advance than to su er later
  • 3. Insu icient testing No documentation This never ends well Eeasy to ignore or shortchange, especially on projects with a tight budget Poor code quality Smells really bad! Technical debt The implied cost of additional rework caused by choosing an easy solution now instead of a better approach that would take longer
  • 4. "Design the so ware to make it more easy to test" Design for Testability
  • 5. " The degree to which a system facilitates the establishment of test criteria and the performance of tests to determine whether those criteria have been met " IEEE, 1990 " Having reliable and convenient interfaces to drive the execution and verification of tests " B. Pettichord " Characteristic of a so ware which allows it to be easily and e iciently tested " (Bach 1999, Gelperin 1999) Testability
  • 6. Which code is easier to test? public class MyCalendar { public boolean isWeekDay(){ int day = Calendar.getInstance() .get(Calendar.DAY_OF_WEEK); return day Calendar.SATURDAY day Calendar.SUNDAY; } } public class MyCalendar { public boolean isWeekDay(Calendar calendar){ int day = calendar.get(Calendar.DAY_OF_WEEK); return day Calendar.SATURDAY day Calendar.SUNDAY; } }
  • 7. Types of Testing Unit Testing Integration Testing System Testing Acceptance Testing and many others more 01 02 03 04
  • 8. Map the issue to the solution Instantiating a class and invoke methods Isolation from dependencies Verify interactions When writing unit tests we usually face some issues, such as
  • 9. Dependency injection A process used in unit testing when the unit being tested has external dependencies. It aims to isolate and focus on the code being tested and not on the behavior or state of the external dependencies Mocking A design pattern in which an object or function receives other objects or functions that it depends on. It aims to separate the concerns of constructing objects and using them, leading to a loosely coupled program
  • 10. What would you do to easily instantiate classes and invoke methods during testing? Dependency injection Mocking Write clean code and avoid private, final, and static Question 1/3 Map the issue to a possible solution
  • 11. Question 2/3 How would you prevent a class from instantiating its own dependencies? Dependency injection Mocking Map the issue to a possible solution Write clean code and avoid private, final, and static
  • 12. Question 3/3 How would you simulate the behavior of the real object and eventually verify its interactions? Dependency injection Mocking Map the issue to a possible solution Write clean code and avoid private, final, and static
  • 14. Be pragmatic and precise while doing it Write Clean and SOLID Code 1
  • 15. Clean code A code than any developer can read and change easily Testable Simple Establish a baseline behaviour and makes it easier to change Increasing complexity makes the code error-prone and di icult to maintain Focused A piece of code should solve only a specific problem
  • 16. Beware Code Smells Symptoms of poor design or implementation choices. Classes that experience those symptoms are more change- and fault-prone than others Bloaters Hard to work with due to their incresed proportions Couplers Contribute to excessive coupling between classes Long Method Large Class Long Parameter List Feature Envy Message Chain
  • 17. Refactoring It's always worth investigating if we can refactor our code to make it more testable
  • 18. Test early and o en Instil a culture of testing 2
  • 19. " All so ware will be tested - either by you and your team or by the eventual users - so you might as well plan on testing it thoroughly " Andrew Hunt, The Pragmatic Programmer
  • 20. Test-driven development (TDD) A so ware development approach in which test cases are developed to specify and validate what the code will do
  • 21. The TDD cycle public class MyCalendar { public boolean isWeekDay(Calendar calendar){ int day = calendar.get(Calendar.DAY_OF_WEEK); return day Calendar.MONDAY day Calendar.TUESDAY day Calendar.WEDNESDAY day Calendar.THURSDAY day Calendar.FRIDAY; } } void testIsWeekDay(){ var calendar = Calendar.getInstance() .set(2022, 8, 2); assert new MyCalendar().isWeekDay(calendar); } } public class MyCalendar { public boolean isWeekDay(Calendar calendar){ return false; } } public class MyCalendar { public boolean isWeekDay(Calendar calendar){ int day = calendar.get(Calendar.DAY_OF_WEEK); return day Calendar.SATURDAY day Calendar.SUNDAY; } }
  • 22. TDD forces you to think about design for testability upfront TDD forces you to think about design for testability upfront Not a silver bullet: still focuses on development than testing Not a silver bullet: still focuses on development than testing No better way to fix errors than preventing them No better way to fix errors than preventing them vs Test early and o en Instil a culture of testing 2
  • 23. Inject Dependencies 3Yet, depend on abstractions, not on concretions
  • 24. public class MyApp { GithubService githubService = new GithubService(); public int countRepos(String token){ List<String> repos = new ArrayList (); try{ githubService.authenticate(token); repos = githubService.collectRepos(); }catch(TimeoutExceeded e){ ; } return repos.size(); } } public class GithubService { void authenticate(String token) throws TimeoutExceeded { if(new Random().nextInt(5) 0) throw new TimeoutExceeded(); Do something, e.g. set APIs quota } public List<String> collectRepos(){ return List.of("sdp/myrepo"); } } @Test void testCollectRepos(){ MyApp app = MyApp(); assert app.countRepos("mytoken") 1; } @Test void testCollectReposTimeoutExceeded(){ MyApp app = MyApp(); assert app.countRepos("mytoken") 0; }
  • 25. MyApp GithubService Hard-coded dependency If we want to switch to a different service in the future, e.g., a GitlabService or a BitbucketService, it will require code changes in MyApp. This makes our application hard to extend Testing the application will be very difficult since our application is directly instantiating the service. There is no way we can mock that object in our tests
  • 27. public class public class MyApp { MyApp { GithubService githubService GithubService githubService; ; public public MyApp( MyApp(GithubService service GithubService service){ ){ githubService = service; githubService = service; } } public public List<String> List<String> collectRepos collectRepos(String token){ (String token){ List<String> repos = List<String> repos = new new ArrayList (); ArrayList (); try try{ { githubService.authenticate(token); githubService.authenticate(token); repos = githubService.collectRepos() repos = githubService.collectRepos() } }catch catch(TimeoutExceeded e){ (TimeoutExceeded e){ ; ; } } return return repos.size(); repos.size(); } } } } public class GithubService { } class LazyGithubService extends GithubService { @Override void authenticate(String token){ throw new TimeoutExceeded("You know I'm lazy :)"); } } @Test void testCollectReposTimeoutExceeded(){ MyApp app = MyApp(new LazyGithubService()); var repos = app.countRepos("mytoken"); assert repos 0; }
  • 28. MyApp GithubService implementation RepoHostingService interface GitlabService implementation public class GithubService implements RepoHostingService { @Override void authenticate(String token){ }; } public class GitlabService implements RepoHostingService { @Override void authenticate(String token){ }; } public class public class MyApp { MyApp { RepoHostingService RepoHostingService service service; ; public public MyApp( MyApp(RepoHostingService RepoHostingService service){ service){ this. this.service = service; service = service; } } } } public interface public interface RepoHostingService { RepoHostingService { void void authenticate authenticate(String token); (String token); } }
  • 29. @Test void testCollectGithubRepos(){ RepoHostingService service = new GithubService(); MyApp app = MyApp(service); var repos = app.countRepos("mygithubtoken"); assert repos 1; } @Test void testCollectGitlabRepos(){ RepoHostingService service = new GitlabService(); MyApp app = MyApp(service); var repos = app.countRepos("mygitlabtoken"); assert repos 1; } @Test void testCollectReposTimeoutExceededMock(){ String token = "mytoken"; RepoHostingService service = mock(GithubService.class); doThrow(new TimeoutExceeded()).when(service) .authenticate(token); MyApp app = MyApp(service); var repos = app.countRepos(token); assert repos 0; }
  • 30. MyApp RepoHostingService Injector GithubService public class ServiceInjector { public MyApp getConsumer(String hostingService) { var service = switch(hostingService) { case "github" new GithubService(); case "gitlab" new GitlabService(); } return new MyApp(service); } }
  • 31. Eases testing by enabling mocking and stubbing Eases testing by enabling mocking and stubbing Eases extension by depending on abstractions Eases extension by depending on abstractions vs With frameworks like Spring, boilerplate code is reduced With frameworks like Spring, boilerplate code is reduced If overused can lead to management issues If overused can lead to management issues Many compile-time errors are pushed to run-time Many compile-time errors are pushed to run-time Tricky to understand at the beginning Tricky to understand at the beginning Yet, depend on abstractions, not on concretions Inject dependencies 3
  • 33. Protected methods are accessible by the unit test if it is located in the same package as the unit to test, though still under a di erent root directory Turning private into protected
  • 34. Avoid static methods Static methods can't be overridden and replaced and therefore are harder to fake; they require a combination of frameworks to be tested
  • 35. Write clean and SOLID code Following good design practices leads to a more testable system Avoid private & static Private and static methods can't be overridden and replaced and therefore are harder to fake Inject dependencies This will allow fakes to be inserted instead of real logic, making isolation easy Instil a culture of testing Early testing guides (re)design Design for Testability Recommendations Avoid code smells And investigate refactoring before taking design decisions
  • 36. No one-size-fits-all Excercise judgement when designing and testing by considering the interactions between them, and pros and cons of each decision
  • 37. What are the recommedation most import to you... Create your own standings by sorting the boxes Avoid code smells Instil a culture of testing Inject dependencies Write clean code 1) 2) 3) 4) 5) Avoid statics & privates and your questions?