使用继承处理异常时如何减少代码重复?基于Offer异常类场景
Great question! When working with exception classes that share common logic (like handling offer data here), extracting that shared code into a base class is the perfect way to cut down on repetition and keep your code maintainable. Here's how to refactor your code effectively:
Step 1: Create a Reusable Base Class
First, we'll build a BadOfferException base class that handles all the common work—parsing the offer data, storing its properties, and setting up the exception message structure. Subclasses will only need to define the unique error message for their specific case.
class BadOfferException(Exception): def __init__(self, offer): # Extract and store common offer properties once in the base class self.offerName = offer[0] self.offerType = offer[1] # Delegate message construction to a subclass-specific method error_message = self._get_error_message() # Call the parent Exception constructor with the message super().__init__(error_message) def _get_error_message(self): # Default fallback message (can be overridden by subclasses) return f"An unexpected error occurred with offer '{self.offerName}' (type: {self.offerType})."
Step 2: Refactor Your Subclass
Now your IncorrectOfferDetailsOfferException can inherit from the base class and only override the method that generates its specific error message. All the repetitive setup code is handled by the base class.
class IncorrectOfferDetailsOfferException(BadOfferException): def _get_error_message(self): # Only define the unique message for this exception type return ( f"Offer \"{self.offerName}\" could not be completed. It appears to be of type \"{self.offerType}\", " "but this may be what is wrong and causing the exception." )
Why This Works
- Eliminates Duplication: The base class takes care of parsing the offer and initializing the exception, so you don't repeat that code in every offer-related exception.
- Cleaner Subclasses: Each subclass only focuses on its unique error context, making your code easier to read and modify.
- Scalable: If you need to add more offer exceptions later (like
ExpiredOfferExceptionorInvalidOfferTypeException), you just inherit fromBadOfferExceptionand override_get_error_message—no need to reimplement the offer parsing logic.
Example Usage
You can use the exception exactly as before, with no changes to how you raise it:
# Raise the exception just like you did originally raise IncorrectOfferDetailsOfferException(("Summer Sale", "Discount"))
内容的提问来源于stack exchange,提问作者Zeke Marffy

