OOP and MVC programming style

I am writing some kind of data analysis software and decided to use this approach:

epn:
model / data.py <- Model definition
model / reader.py <- How to read data in model
view / gui.py <- main gui frame (wx)
view / dialogs.py <- various dialogs (wx)
epn. py <-controller

For communication between gui and data, I used wx.lib.pubsub. So when the Modulation Index button is clicked, epn.py catches the message and orders:

self.view.control_panel.displayModulationIndex(self.data.getModulationIndex())

      

where self.data.getModulationIndex ():

def getModulationIndex(self):
  m = self.mean_flux
  f = self.fluxes
  # other things

      

On the other hand, I can write it like:

def getModulationIndex(self, m, f)
  # other things

      

and call it like:

m = self.data.mean_flux
f = self.data.fluxes
self.view.control_panel.displayModulationIndex(self.data.getModulationIndex(m, f))

      

From my point of view, the first example is better (shorter, encapsulated, more error-proof). But it's more difficult to test it - you can't just call the method on some mock objects.

hope it's clear


Chriss thinks

+1


source to share


1 answer


Example 1: "better (shorter, encapsulated, more error-proof)"

Not really.

  • Function call 1 is no less than example 2; you have to set instance variables before calling the function instead of passing values ​​as arguments. This is the same code.

  • Function call 1 is at most encapsulated. Encapsulation is a property of the class as a whole, not of an individual method. Methods are just methods, and they often have arguments to make them clear, obvious, replaceable, and easy to test.

  • Function call 1 is not an error in any sense of the word. You can also forget to set the instance variable as you must forget to pass the instance variable in the function call.

    When you have explicit arguments (example 2), Python can check that you supply the correct number of arguments. Example 1 doesn't check for you.

Example 1: "harder to check"

I agree.



Summary

Instances are special. They reflect the state of being of an object. For model objects, they are serious business because they are often persistent. For GUI objects, they are "what is displayed right now", which is often temporary.

Don't use redundant instance variables. Instance variables must be meaningful and meaningful. Not just junk variables for things that don't have their own home anywhere.

Method functions are just functions. In the OO world, they are still just functions. They map input arguments for displaying results (or object state changes). Pass any arguments that make sense.

+3


source







All Articles