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

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Dernier (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

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); } } } }