tags:

views:

140

answers:

1

which one of the following is considered better a design and why ?. i have 2 classes , one for the gui components and the other is for it's events.
please put in mind that the eventClass will be implemented so many times, (sometimes to get data from an oracle databases and sometimes mysql databases )

class MainWindow:

    def __init__(self):
        self.myEvents = eventClass()  # the class that has all the events 
        self.button = button # consider it a button from any gui library
        self.menu  = menu  # menu box 

    def bottonEvent(self):
        data = self.myEvents.buttonEvent()
        self.menu.populate(data)

class eventClass:

    def __init__(self):
          pass
    def getData(self):
         return data # return data to puplate in the list

OR

class MainWindow:

    def __init__(self):
        self.myEvents = eventClass(self)  # the class that has all the events 
        self.button = button # consider it a button from any gui library
        self.menu  = menu  # menu box 

    def bottonEvent(self):
        self.myEvents.ButtonEvent()

class eventClass:

    def __init__(self,window):
          pass
    def ButtonEvent(self):
         window.menu.populateData()

please inform me if anything was unclear
please help ,
thanks in advance

+5  A: 

The first choice is better "decoupled": the event class needs and has no knowledge whatsoever about the window object or its menu attribute -- an excellent approach that makes the event class especially easy to unit-test in isolation without any overhead. This is especially nice if many implementations of the same interface need to exist, as you mention they do in your case.

The second choice introduces a mutual dependency -- an event object can't work without a window object, and a window object builds an event object. That may be an acceptable complication in more abstruse cases where it buys you something, but for this specific use it sounds more like an arbitrary extra difficulty without any real plus.

So, I would recommend the first form.

Alex Martelli
thank you very much Mr.Martelli. +1 for the clarification
Moayyad Yaghi
@Moayyad, you're welcome!
Alex Martelli
This is a good answer, but I would say that it's impossible to tell you which is "better" without seeing your entire design
Falmarri
@Falmarri, good point of course: _if_ the OP's hiding some terrible complication occurring elsewhere but crucially relevant to these two classes, then the overall design would _not_ meet my qualification "for this specific use" (since the use would be very much otherwise;-). My A is predicated on there being no big secrets or skeletons hidden in the app's closets;-).
Alex Martelli