SlideShare una empresa de Scribd logo
1 de 8
Descargar para leer sin conexión
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);
}
}
}
}

Más contenido relacionado

Último

SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKUXDXConf
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty SecureFemke de Vroome
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyUXDXConf
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxEasyPrinterHelp
 

Último (20)

SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptx
 

Destacado

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
 

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