Python: Same or different method names in MVC - python

I am currently writing a booking system and I'm following MVC.
My question is what is considered a better practice:
All methods from the different packages along the line of a single operation to have the same names
Come up with different names for each method?
To clarify my questions, here is an example:
When booking an appointment, that's the current sequence:
The toplevel windows calls root.book_appointment() (root is the "controller" of the view package)
root calls controller.book_appointment()
controller calls model.book_appointment()
model calls database.book_appointment()
I tried to find a convention or opinions somewhere, but I could not find anything.
One way, everything has the same names, even though there is always an identifier before the method call(root, controller, model, database etc). On the other hand for every operation that starts from a panel I need to come up with another 5 method names until I reach the database.
Thanks a lot in advance for your time and answers!
Tried googling for answers, but nothing came up. Most answers were for methods with same names and different parameters.

Related

Tkinter Frames - Classes

So I'm using tkinter to make a GUI and at the moment I have several different frames. The way I programmed it is by just using one massive class but everywhere I look online (like here - https://pythonprogramming.net/change-show-new-frame-tkinter/), people are using a new class for every single "page". Is what I am doing wrong/not efficient or is it fine?
Unfortunately I cannot show my code as it's for a CA but the below is similar:
class App(tk.Frame):
def __init__(self):
tk.Frame.__init(self)
self.PageOne()
def PageOne(self):
coding stuff
def PageTwo(self):
pass
What you are doing is probably fine. I say "probably" because it depends on many factors which you haven't explained in your question.
The tutorial you referenced came from a stackoverflow answer that was explicitly addressing how to switch between two frames. It's not necessarily a recommended way to code, it's simply one of many ways.
That being said, if you have distinct pages then you might find it easier to manage your code if each page was a self-contained object. Doing so gives each page its own namespace, so you don't have to worry that one page is accidentally modifying the data that belongs to some other page. Plus, for larger projects it allows you to implement each page in a separate file so you don't end up with one huge file full of code.
Since not all GUIs are oriented around the concept of pages, this technique isn't a one-size-fits-all solution. It's OK to make each page a class, it's also OK to create each page via a function. The choice depends on many variables, such as your comfort with working with classes, the size of your project, the type of UI you're creating, and so on.

Designing an OOP solution

Im writing code for research purposes, in which I search through a bulk of files and rank them according to their relevance. I call the entire process quickSearching, and it is composed of two serial stages - first I search the file and retrieve a list a candidates files, then I score those candidates and rank them.
So a quicksearch is simply a serial combination of a search method and a score method.
Im planning to implement various searching and scoring methodologies, and I would like to test all possible combinations and evaluate them to see which is the winning combo.
Since the number of combos will grow very fast, It is important to write the code in a good structure and design. I thought about the following designs (Im writing the code in python):
A quickSearcher class that will receive pointers to a searcher and scorer functions
A quickSearcher class that will receive a searcher object and a scorer object
A quickSearcher calss that will inherit from a searcher class and an scorer class
since Im basically an EE engineer, Im not sure how to select between the options and if this a common problem in CS with trivial pattern design.The design i'm looking will hopefully:
Be very code-volume efficient, since some of the searching and scoring methods differ in simply a different value of a parameter or two.
Be very modular and logical errors prone.
Be easy to navigate through
Any other consideration I should take?
This is my first design question so it might not be valid or missing important info, please notify me if it is.
Classes are often overused, especially by programmers coming from languages like Java and C# where they are compulsory. I recommend watching the presentation Stop Writing Classes.
When deciding whether to create a class it is useful to ask yourself the following questions:
1) Will the class need to have multiple methods?
If the class only has a single method (apart from __init__) then you may as well make it a function instead. If it needs to preserve state between calls then use a generator. If it needs to be created in one place with some parameters then called elsewhere you can use a closure (a function that returns another function) or functools.partial.
2) will it need to share state between methods?
If the class does not need to share state between methods then it may be better replaced with either a set of independent functions or smaller classes (or some combination).
If the answer to both questions is yes then go ahead and create a class.
For your example I think option 1 is the way to go. The searcher and scorer objects sound like they if they are classes they will only have a single method, probably called something like execute or run. Make them functions instead.
Depending on your use case, quickSorter itself may be better off as a function or generator as well, so no need for any classes at all.
BTW there is no distinction in Python between a function and a pointer to a function.

Design of a multi-level abstraction software

I'm working on designing a piece of software now, that has a few levels of abstraction. This might be the most complex piece of code I've ever started designing, and it has a requirement for easy upgrading, so I'm wanting to make sure I'm on the right track before I even start coding anything.
Essentially, there will be 3 main levels of classes. These two classes will need to talk with each other.
The first is the input source data. There are currently 2 main types of input data, which produce similar, but not identical output. The main goal of these classes will be to get the data from the two difference sources and convert it into a common interface, for use in the rest of the program.
The second set will be an adapter for an external library. The library has been periodically updated, and I have no reason to suspect that it will not continue to be updated throughout the years. Most likely, each upgrade will remain very similar to the previous one, but there might be some small changes made to support a new library version. This level will be responsible for taking the inputs, and formatting them for a use of an output class.
The last class is the outputs. I don't think that multiple versions will be required for this, but there will need to be at least two different output directories specified. I suspect the easiest thing to do would be to simply pass in an output directory when the output class is created, and that is the only level of abstraction required. This class will be frequently updated, but there is no requirement to support multiple versions.
Set up the code as follows, essentially following a bridge pattern, but with multiple abstraction layers.
The input class will be the abstraction. The currently two different means of getting output will be the two different concrete classes, and more concrete classes can be added if required.
The wrapper class will be a factory pattern. Most of the code should be common between the various implementations, so this should work well to handle minute differences.
The output class will be included as a part of the implementor class. There isn't a pattern really required, as only one version will ever be required for this class. Also, the implementor will likely be a singleton.

Where should I put output field descriptions, controller or model?

I've noticed I have the same piece of code sitting at the top of several of my controllers. They tend to look like this:
def app_description(app):
""" Dictionary describing an app. """
return {'name': app.app,
'id': app.id,
'is_new': app.is_new(),
'created_on': app.created_on.strftime("%m/%d/%Y"),
'configured': app.configured }
I'll call this from a couple different actions in the controller, but generally not outside that controller. It accesses properties. It calls methods. It formats opaque objects (like dates).
My question is: is this controller code, or model code?
The case for controller:
It defines my API.
It's currently only used in that module.
There doesn't seem to be any logic here.
The case for model:
It seems like a description of the data, which the model should be responsible for.
It feels like I might want to use this in other controllers. Haven't gotten there yet, but these functions are still pretty new, so they might.
Attaching a function to the object it clearly belongs to seems better than leaving it as a module-level function.
It could be more succinctly defined on the model. Something like having the top-level model object define .description(), and the subclasses just define a black/whitelist of properties, plus override the method itself to call functions. I'm pretty sure that would be fewer lines of code (as it would save me the repetition of things like 'name': app.name), which seems like a good thing.
Not sure which framework you are using, but I would suggest creating this helper functionality in its own class and put it in a shared folder like lib/
Alternatively you could have an application helper module that just has a bunch of these helpful application-wide functions.
Either way, I'd keep it away from both the model and the controller.
The answer I finally decided on:
In the short term, having these methods is fine in the controllers. If they define the output, then, OK, they can stay there. They're only used in the model.
Theres a couple things to watch out for, which indicate they've grown up, and need to go elsewhere:
In one case, I needed access to a canonical serialization of the object. At that point, it moved into the model, as a model method.
In another case, I found that I was formatting all timestamps the same. I have a standard #ajaxify decorator that does things like sets Content-Type headers, does JSON encoding, etc. In this case, I moved the datetime standard formatting into there -- when the JSON encoder hits a datetime (formerly unserializable), it always treats it the same (seconds since the epoch, for me).
In yet a third case, I realized that I was re-using this function in a couple controllers. For that, I pulled it out into a common class (like another answer suggested) and used that to define my "Web API". I'd used this pattern before -- it makes sense for grouping similarly-used data (like timeseries data, or top-N lists).
I suspect there's more, but basically, I don't think there all as similar as I thought they were initially. I'm currently happy thinking about them as a convention for simple objects in our (small-ish, new-ish) codebase, with the understanding that after a few iterations, a better solution may present itself. In the meantime, they stay in the controller and define my AJAXy-JSON-only interface.

Pythonic way to ID a mystery file, then call a filetype-specific parser for it? Class creation q's

(note) I would appreciate help generalizing the title. I am sure that this is a class of problems in OO land, and probably has a reasonable pattern, I just don't know a better way to describe it.
I'm considering the following -- Our server script will be called by an outside program, and have a bunch of text dumped at it, (usually XML).
There are multiple possible types of data we could be getting, and multiple versions of the data representation we could be getting, e.g. "Report Type A, version 1.2" vs. "Report Type A, version 2.0"
We will generally want to do the same thing action with all the data -- namely, determine what sort and version it is, then parse it with a custom parser, then call a synchronize-to-database function on it.
We will definitely be adding types and versions as time goes on.
So, what's a good design pattern here? I can come up with two, both seem like they may have som problems.
Option 1
Write a monolithic ID script which determines the type, and then
imports and calls the properly named class functions.
Benefits
Probably pretty easy to debug,
Only one file that does the parsing.
Downsides
Seems hack-ish.
It would be nice to not have to create
knowledge of dataformats in two places, once for ID, once for actual
merging.
Option 2
Write an "ID" function for each class; returns Yes / No / Maybe when given identifying text.
the ID script now imports a bunch of classes, instantiates them on the text and asks if the text and class type match.
Upsides:
Cleaner in that everything lives in one module?
Downsides:
Slower? Depends on logic of running through the classes.
Put abstractly, should Python instantiate a bunch of Classes, and consume an ID function, or should Python instantiate one (or many) ID classes which have a paired item class, or some other way?
You could use the Strategy pattern which would allow you to separate the logic for the different formats which need to be parsed into concrete strategies. Your code would typically parse a portion of the file in the interface and then decide on a concrete strategy.
As far as defining the grammar for your files I would find a fast way to identify the file without implementing the full definition, perhaps a header or other unique feature at the beginning of the document. Then once you know how to handle the file you can pick the best concrete strategy for that file handling the parsing and writes to the database.

Categories