SlideShare une entreprise Scribd logo
1  sur  8
Télécharger pour lire hors ligne
public class Original { // Coupling: Static Dependencies 1
public void usage() {
BookingService bookingService = new BookingService();
bookingService.bookConference("Big Trouble in Little China");
}
}
public class BookingService {
public BookingResult bookConference(String topic) {
ConferencingServer conferencingServer = new ConferencingServer();
MeetingCalendar meetingCalendar = MeetingCalendar.getInstance();
Date startDate = meetingCalendar.nextPossibleDate();
try {
return conferencingServer.bookConference(topic, startDate);
}
catch (BookingException e) {
return BookingResult.forFailure(e);
}
}
}
class ConferencingServer {
public BookingResult bookConference(String topic, Date startDate) throws
BookingException {
// NOTE: real implementation would connect to
// the conferencing server and book the conference
return BookingResult.forSuccess("0721/480848-000", startDate);
}
}
class MeetingCalendar {
private static final MeetingCalendar instance = new MeetingCalendar();
private MeetingCalendar() {
// enforce Singleton
}
public static MeetingCalendar getInstance() {
return instance;
}
public Date nextPossibleDate() {
// NOTE: real implementation would look up some
// calendar database and calculate the date
return new Date();
}
}
public final class BookingResult {
private final BookingException errorCause;
private final String phoneNumber;
private final Date startDate;
private BookingResult(BookingException errorCause,
String phoneNumber,
Date startDate) {
this.errorCause = errorCause;
this.phoneNumber = phoneNumber;
this.startDate = startDate;
}
public static BookingResult forSuccess(String phoneNumber, Date startDate) {
return new BookingResult(null, phoneNumber, startDate);
}
public static BookingResult forFailure(BookingException error) {
return new BookingResult(error, null, null);
}
public boolean isSuccess() { return errorCause == null; }
public String getPhoneNumber() { return phoneNumber; }
public Date getStartDate() { return startDate; }
public BookingException getErrorCause() { return errorCause; }
}
public class Original { // Coupling: Static Dependencies 2
public void usage() throws BookingException {
// NOTE: the real implementation would create
// these objects at a central place.
BigFatContext bigFatContext = new BigFatContext();
BookingService bookingService = new BookingService(bigFatContext);
bookingService.bookConference("Big Trouble in Little China");
}
}
/**
* NOTE: imagine it is difficult to instantiate this
* class and its collaborators in a test harness.
*/
public final class BigFatContext extends FrameworkClass {
private final Map<String, Object> services = new HashMap<String, Object>();
public BigFatContext() {
// NOTE: the map contains real objects, which are created here
// => how to replace these two with mock objects in a test?
services.put("conferencingServer", new ConferencingServerImpl());
services.put("meetingCalendar", new MeetingCalendarImpl());
}
public ConferencingServer getConferencingServer() {
return (ConferencingServer) services.get("conferencingServer");
}
public MeetingCalendar getMeetingCalendar() {
return (MeetingCalendar) services.get("meetingCalendar");
}
}
public class BookingService {
private final BigFatContext bigFatContext;
public BookingService(BigFatContext bigFatContext) {
this.bigFatContext = bigFatContext;
}
public BookingResult bookConference(String topic) throws BookingException {
MeetingCalendar meetingCalendar = bigFatContext.getMeetingCalendar();
Date startDate = meetingCalendar.nextPossibleDate();
try {
ConferencingServer conferencingServer = bigFatContext.getConferencingServer();
return conferencingServer.bookConference(topic, startDate);
}
catch (BookingException e) {
return BookingResult.forFailure(e);
}
}
}
public class Original { // Coupling: Dynamic Dependencies
public void usage() throws BookingException {
// sample setup
ConferencingServer conferencingServer = new ConferencingServerImpl();
MeetingCalendar meetingCalendar = new MeetingCalendarImpl();
BookingService bookingService = new BookingService(conferencingServer,
meetingCalendar);
NotificationService notificationService = new NotificationService();
// sample usage
BookingResult bookingResult = bookingService.bookConference("Big Trouble in Little
China");
if (bookingResult.isSuccess()) {
List<String> participantUris = asList("sip:Jack.Burton@trucker.com",
"mailto:Egg.Shen@magician.com");
notificationService.notifyParticipants(participantUris,
bookingResult.getStartDate());
}
}
}
public class NotificationService {
public NotificationResult notifyParticipants(List<String> participantUris,
Date startDate) {
// prepare the info text about the conference
String notificationMessage = buildNotificationMessage(startDate);
// notify the participants
NotificationResult result = new NotificationResult();
for (String participantUri : participantUris) {
try {
notifyParticipant(participantUri, notificationMessage);
}
catch (NotificationException e) {
result.addError(participantUri, e);
}
}
return result;
}
private String buildNotificationMessage(Date startDate) {
String text = "Time for Kung-Fu! We will call you at %s.";
return String.format(text, startDate);
}
private void notifyParticipant(String participantUri,
String notificationMessage) throws NotificationException
{
if (participantUri.startsWith("sip:")) {
InstantMessenger instantMessenger = new InstantMessenger();
instantMessenger.sendMessage(participantUri, notificationMessage);
}
else if (participantUri.startsWith("mailto:")) {
EmailSender emailSender = new EmailSender();
emailSender.sendEmail(participantUri, notificationMessage);
}
}
}
public class Original { // Distraction
public void usage() throws Exception {
FtpClient ftpClient = new FtpClient("ftp://my.server.de");
List<String> fileNames = ftpClient.listFiles("*.rec");
for (String fileName : fileNames) {
File localFile = ftpClient.downloadFile(fileName, "Bx3A2v34fhq4367");
}
}
}
public class FtpClient {
private static final int RECONNECT_RETRIES = 3;
private final String serverUrl;
private final Cache<String, List<String>> cachedLists;
public FtpClient(String serverUrl) {
this.serverUrl = serverUrl;
this.cachedLists = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.MINUTES)
.build();
}
public List<String> listFiles(String pattern) throws IOException {
try {
return cachedLists.get(pattern, new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
establishConnection(RECONNECT_RETRIES);
// NOTE: imagine this lists the remote FTP files
// according to the given filename pattern
List<String> remoteFiles = asList("conference-0.rec",
"conference-1.rec");
return remoteFiles;
}
});
}
catch (ExecutionException e) {
throw new IOException(e);
}
}
public File downloadFile(String fileName, String checksum) throws IOException {
establishConnection(RECONNECT_RETRIES);
// NOTE: imagine this downloads the file in /tmp
File localFile = new File("/tmp", fileName);
checkChecksum(localFile, checksum);
return localFile;
}
private void checkChecksum(File localFile, String checksum) throws IOException {
byte[] fileBytes = Files.readAllBytes(localFile.toPath());
HashFunction hashFunction = Hashing.md5();
HashCode expectedHashCode = hashFunction.hashString(checksum);
HashCode actualHashCode = hashFunction.hashBytes(fileBytes);
if (!actualHashCode.equals(expectedHashCode)) {
throw new IOException("Bad checksum after download!");
}
}
private void establishConnection(int retriesLeft) throws IOException {
try {
// NOTE: simulate some connection problems
System.out.println("Connecting to " + serverUrl);
if (Math.random() < 0.2) {
throw new IOException("Connection refused!");
}
}
catch (IOException e) {
if (retriesLeft > 0) {
establishConnection(retriesLeft - 1);
}
else {
throw new IOException("Failed after " + RECONNECT_RETRIES + " retries", e);
}
}
}
}

Contenu connexe

Dernier

The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Hiroshi SHIBATA
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 

Dernier (20)

The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 

En vedette

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

En vedette (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Refactoring for Tests - Handout

  • 1. public class Original { // Coupling: Static Dependencies 1 public void usage() { BookingService bookingService = new BookingService(); bookingService.bookConference("Big Trouble in Little China"); } } public class BookingService { public BookingResult bookConference(String topic) { ConferencingServer conferencingServer = new ConferencingServer(); MeetingCalendar meetingCalendar = MeetingCalendar.getInstance(); Date startDate = meetingCalendar.nextPossibleDate(); try { return conferencingServer.bookConference(topic, startDate); } catch (BookingException e) { return BookingResult.forFailure(e); } } } class ConferencingServer { public BookingResult bookConference(String topic, Date startDate) throws BookingException { // NOTE: real implementation would connect to // the conferencing server and book the conference return BookingResult.forSuccess("0721/480848-000", startDate); } } class MeetingCalendar { private static final MeetingCalendar instance = new MeetingCalendar(); private MeetingCalendar() { // enforce Singleton } public static MeetingCalendar getInstance() {
  • 2. return instance; } public Date nextPossibleDate() { // NOTE: real implementation would look up some // calendar database and calculate the date return new Date(); } } public final class BookingResult { private final BookingException errorCause; private final String phoneNumber; private final Date startDate; private BookingResult(BookingException errorCause, String phoneNumber, Date startDate) { this.errorCause = errorCause; this.phoneNumber = phoneNumber; this.startDate = startDate; } public static BookingResult forSuccess(String phoneNumber, Date startDate) { return new BookingResult(null, phoneNumber, startDate); } public static BookingResult forFailure(BookingException error) { return new BookingResult(error, null, null); } public boolean isSuccess() { return errorCause == null; } public String getPhoneNumber() { return phoneNumber; } public Date getStartDate() { return startDate; } public BookingException getErrorCause() { return errorCause; } }
  • 3. public class Original { // Coupling: Static Dependencies 2 public void usage() throws BookingException { // NOTE: the real implementation would create // these objects at a central place. BigFatContext bigFatContext = new BigFatContext(); BookingService bookingService = new BookingService(bigFatContext); bookingService.bookConference("Big Trouble in Little China"); } } /** * NOTE: imagine it is difficult to instantiate this * class and its collaborators in a test harness. */ public final class BigFatContext extends FrameworkClass { private final Map<String, Object> services = new HashMap<String, Object>(); public BigFatContext() { // NOTE: the map contains real objects, which are created here // => how to replace these two with mock objects in a test? services.put("conferencingServer", new ConferencingServerImpl()); services.put("meetingCalendar", new MeetingCalendarImpl()); } public ConferencingServer getConferencingServer() { return (ConferencingServer) services.get("conferencingServer"); } public MeetingCalendar getMeetingCalendar() { return (MeetingCalendar) services.get("meetingCalendar"); } } public class BookingService { private final BigFatContext bigFatContext; public BookingService(BigFatContext bigFatContext) { this.bigFatContext = bigFatContext; }
  • 4. public BookingResult bookConference(String topic) throws BookingException { MeetingCalendar meetingCalendar = bigFatContext.getMeetingCalendar(); Date startDate = meetingCalendar.nextPossibleDate(); try { ConferencingServer conferencingServer = bigFatContext.getConferencingServer(); return conferencingServer.bookConference(topic, startDate); } catch (BookingException e) { return BookingResult.forFailure(e); } } }
  • 5. public class Original { // Coupling: Dynamic Dependencies public void usage() throws BookingException { // sample setup ConferencingServer conferencingServer = new ConferencingServerImpl(); MeetingCalendar meetingCalendar = new MeetingCalendarImpl(); BookingService bookingService = new BookingService(conferencingServer, meetingCalendar); NotificationService notificationService = new NotificationService(); // sample usage BookingResult bookingResult = bookingService.bookConference("Big Trouble in Little China"); if (bookingResult.isSuccess()) { List<String> participantUris = asList("sip:Jack.Burton@trucker.com", "mailto:Egg.Shen@magician.com"); notificationService.notifyParticipants(participantUris, bookingResult.getStartDate()); } } } public class NotificationService { public NotificationResult notifyParticipants(List<String> participantUris, Date startDate) { // prepare the info text about the conference String notificationMessage = buildNotificationMessage(startDate); // notify the participants NotificationResult result = new NotificationResult(); for (String participantUri : participantUris) { try { notifyParticipant(participantUri, notificationMessage); } catch (NotificationException e) { result.addError(participantUri, e); } } return result; } private String buildNotificationMessage(Date startDate) {
  • 6. String text = "Time for Kung-Fu! We will call you at %s."; return String.format(text, startDate); } private void notifyParticipant(String participantUri, String notificationMessage) throws NotificationException { if (participantUri.startsWith("sip:")) { InstantMessenger instantMessenger = new InstantMessenger(); instantMessenger.sendMessage(participantUri, notificationMessage); } else if (participantUri.startsWith("mailto:")) { EmailSender emailSender = new EmailSender(); emailSender.sendEmail(participantUri, notificationMessage); } } }
  • 7. public class Original { // Distraction public void usage() throws Exception { FtpClient ftpClient = new FtpClient("ftp://my.server.de"); List<String> fileNames = ftpClient.listFiles("*.rec"); for (String fileName : fileNames) { File localFile = ftpClient.downloadFile(fileName, "Bx3A2v34fhq4367"); } } } public class FtpClient { private static final int RECONNECT_RETRIES = 3; private final String serverUrl; private final Cache<String, List<String>> cachedLists; public FtpClient(String serverUrl) { this.serverUrl = serverUrl; this.cachedLists = CacheBuilder.newBuilder() .expireAfterAccess(1, TimeUnit.MINUTES) .build(); } public List<String> listFiles(String pattern) throws IOException { try { return cachedLists.get(pattern, new Callable<List<String>>() { @Override public List<String> call() throws Exception { establishConnection(RECONNECT_RETRIES); // NOTE: imagine this lists the remote FTP files // according to the given filename pattern List<String> remoteFiles = asList("conference-0.rec", "conference-1.rec"); return remoteFiles; } }); } catch (ExecutionException e) { throw new IOException(e); } }
  • 8. public File downloadFile(String fileName, String checksum) throws IOException { establishConnection(RECONNECT_RETRIES); // NOTE: imagine this downloads the file in /tmp File localFile = new File("/tmp", fileName); checkChecksum(localFile, checksum); return localFile; } private void checkChecksum(File localFile, String checksum) throws IOException { byte[] fileBytes = Files.readAllBytes(localFile.toPath()); HashFunction hashFunction = Hashing.md5(); HashCode expectedHashCode = hashFunction.hashString(checksum); HashCode actualHashCode = hashFunction.hashBytes(fileBytes); if (!actualHashCode.equals(expectedHashCode)) { throw new IOException("Bad checksum after download!"); } } private void establishConnection(int retriesLeft) throws IOException { try { // NOTE: simulate some connection problems System.out.println("Connecting to " + serverUrl); if (Math.random() < 0.2) { throw new IOException("Connection refused!"); } } catch (IOException e) { if (retriesLeft > 0) { establishConnection(retriesLeft - 1); } else { throw new IOException("Failed after " + RECONNECT_RETRIES + " retries", e); } } } }