The before code calls the external service directly without checking if it is available, risking failures. The after code adds an AvailabilityChecker that sends a health check request before calling the service, preventing calls when the service is down.
### Before Availability Checking (naive call)
class ExternalServiceClient:
def get_data(self):
# Directly call external service without checking
response = self.call_service()
return response
def call_service(self):
# Simulate service call
return "data"
### After Applying Availability Checking
import requests
class AvailabilityChecker:
def __init__(self, health_url):
self.health_url = health_url
def is_available(self):
try:
response = requests.get(self.health_url, timeout=1)
return response.status_code == 200
except requests.RequestException:
return False
class ExternalServiceClientWithCheck:
def __init__(self, health_url):
self.checker = AvailabilityChecker(health_url)
def get_data(self):
if not self.checker.is_available():
raise Exception("Service unavailable")
response = self.call_service()
return response
def call_service(self):
# Simulate service call
return "data"