开发者

Sending failure messages between classes

开发者 https://www.devze.com 2023-03-26 09:08 出处:网络
Ok, so this is really just a conceptual question I\'m having a bit of trouble with rather than a coding problem. I\'m building a simple, weekly time tracker to automate some admin in a game. So, I hav

Ok, so this is really just a conceptual question I'm having a bit of trouble with rather than a coding problem. I'm building a simple, weekly time tracker to automate some admin in a game. So, I have a TimeSheet class and a TimeBlock class. Here is the Timesheet class with a comment where I'm not sure what to do.

class Timesheet():
    def __init__(self,person,week):
        self.person = person
        self.week = week
        self.hours = 168
        self.time_blocks = []

    def add_time_block(self,time_block):
    ##Test that the time_block actually fits in this week
        if sum([x.hours for x in self.time_blocks]) >= self.hours-time_block.hours:
            self.time_blocks.append(time_block)
        else: ##This is where I'm not sure what I should do.

This isn't a show-stopping error, it's probably a PEBKAC error, so I think the Exception class is out. What I want 开发者_StackOverflow中文版a way for the TimeSheet to say 'no' without coupling it to a specific interface (so I could use this with just CLI for now but eventually add a GUI once I learn to code GUIs or a web interface once one that I like ports to 3.0). This shouldn't break the program, but it should alert the user that they've attempted something that cannot be done and they need to shorten that timeblock before they try to insert it, modify some other timeblocks to make this one fit, or just submit their timesheet because the timesheet is full. What are some clean, elegant ways to do that?


I would use an Exception. You can always wrap the function call from within the CLI supporting code in a try...except block and react there appropriately; I see no drawbacks using this methodology.


You could provide an event listener interface, where "interested parties" can register to get events that you generate for example in your else above. Having an agreed-upon Event interface allows you to then react on these intelligently, e.g. have an event type (enumeration) or a UserAlertEvent subclass.

0

精彩评论

暂无评论...
验证码 换一张
取 消