Im programming a library, I want to structure my code in a way that potential users find it easy to use this library. I have looked at this excellent video of great API design. One of the golden rules is to have a good design pattern. I have two in mind. The Facade design patten and the factory design patten. Both these design pattens are used to achieve a great level of abstraction in program code for users to use.
Im finding it ever so difficult on which or if both to apply. Of course, I would like to avoid having anti-pattens.
The language I am using is Python, which is quite different to Java Which is emphasised in the video link provided above.
How my library would work:
Character class
Window class
Many character objects can be created.
Say if I was to use the facade design pattern I would have both this classes initialised in the facade constructor, so that they can be called in the methods:
class Facade():
__init__(self):
self.character = Character()
self.window = Window()
here I would create methods which represent methods created in the character and window class. These could then easily be called by users:
Facade = Facade()
Facade.methodUsedInCharacterClass()
Facade.methodUsedInCharacterClass()
Facade.methodUsedInWindowClass()
But here is where I see the facade having a problem, you can have two different characters, which you would want to have to do different things. You could do this:
Facade = Facade()
badguy= Facade.methodUsedInCharacterClass()
goodguy= Facade.methodUsedInCharacterClass()
Facade.methodUsedInWindowClass()
You cant then use the badguy or goodguy variables to invoke other behaviours, such as
badguy.rotate()
goodguy.jump()
This is not allowed, but is there a way of doing this?
Also, as the constructor is calling the classes, a factory method could be used, which choses at run time which class to execute by my own understanding. I can only visualise, but in this case how would it apply?
Thanks!
You seem to have misunderstood the purpose of factory and facade patterns.
The factory pattern is used to build things. So you will have a CharacterFactory and a WindowFactory. If customers need to have special characters, they need a way to replace your default CharacterFactory with theirs.
The character factory should then be able to produce different types of characters. This way, you can build default good and bad guys for your game. Customers can then override these methods to modify the defaults.
The facade is used to make an object appear as if it was of a different type. So your window might have a child of type View. A CharacterView would then be a facade which maps information from the character into data for the View interface which the window can then use to display information like health without knowing anything about the character or health.
This means you also need a configuration object that contains the default factories. Customers get one of those from the ConfigFactory.
class ConfigFactory:
def createConfig(self):
config = Config()
config.characterFactory = self.createCharacterFactory()
return config
def createCharacterFactory(self):
return CharacterFactory()
Customers will override this to get their own factory:
class CustomConfigFactory(ConfigFactory):
def createCharacterFactory(self):
return CustomCharacterFactory()
Related
I am writing an application which extracts some data from HTML using BeautifoulSoup4. These are search results of some kind, to be more specific. I thought it would be a good a idea to have a Parser class, storing default values like URL prefixes, request headers etc. After configuring those parameters, the public method would return a list of objects, each of them containing a single result or maybe even an object with a list composed into it alongside with some other parameters. I'm struggling to decouple small pieces of logic that build that parser implementation from the parser class itself. I want to write dozens of parser private utility methods like: _is_next_page_available, _are_there_any_results, _is_did_you_mean_available etc. However, these are the perfect candidates for writing unit tests! And since I want to make them private, I have a feeling that I'm missing something...
My other idea was to write that parser as a function, calling bunch of other utility functions, but that would be just equal to making all of those methods public, which doesn't make sense, since they're implementation details.
Could you please advice me how to design this properly?
I think you're interpreting the Single-Responsibility Principle (SRP) a little differently. It's actual meaning is a little off from 'a class should do only one thing'. It actually states that a class should have one and only one reason to change.
To employ the SRP you have to ask yourself to what/who would your parser module methods be responsible, what/who might make them change. If the answer for each method is the same, then your Parser class employs the SRP correctly. If there are methods that are responsible to different things (business-rule givers, groups of users etc.) then those methods should be taken out and be placed elsewhere.
Your overall objective with the SRP is to protect your class from changes coming from different directions.
This question is very generic but I don't think it is opinion based. It is about software design and the example prototype is in python:
I am writing a program which goal it is to simulate some behaviour (doesn't matter). The data on which the simulation works is fixed, but the simulated behaviour I want to change at every startup time. The simulation behaviour can't be changed at runtime.
Example:
Simulation behaviour is defined like:
usedMethod = static
The program than looks something like this:
while(true)
result = static(object) # static is the method specified in the behaviour
# do something with result
The question is, how is the best way to deal with exchangeable defined functions? So another run of the simulation could look like this
while(true)
result = dynamic(object)
if dynamic is specified as usedMethod. The first thing that came in my mind was an if-else block, where I ask, which is the used method and then execute this on. This solution would not be very good, because every time I add new behaviour I have to change the if-else block and the if-else block itself would maybe cost performance, which is important, too. The simulations should be fast.
So a solution I could think of was using a function pointer (output and input of all usedMethods should be well defined and so it should not be a problem). Then I initalize the function pointer at startup, where the used method is defined.
The problem I currently have, that the used method is not a function per-se, but is a method of a class, which depends heavily on the intern members of this class, so the code is more looking like this:
balance = BalancerClass()
while(true)
result = balance.static(object)
...
balance.doSomething(input)
So my question is, what is a good solution to deal with this problem?
I thought about inheriting from the balancerClass (this would then be an abstract class, I don't know if this conecpt exists in python) and add a derived class for every used method. Then I create the correct derived object which is specified in the simulation behaviour an run-time.
In my eyes, this is a good solution, because it encapsulates the methods from the base class itself. And every used method is managed by its own class, so it can add new internal behaviour if needed.
Furthermore the doSomething method shouldn't change, so therefore it is implemented the base class, but depends on the intern changed members of the derived class.
I don't know in general if this software design is good to solve my problem or if I am missing a very basic and easy concept.
If you have a another/better solution please tell me and it would be good, if you provide the advantages/disadvantages. Also could you tell me advantages/disadvantages of my solution, which I didn't think of?
Hey I can be wrong but what you are looking for boils down to either dependency injection or strategy design pattern both of which solve the problem of executing dynamic code at runtime via a common interface without worrying about the actual implementations. There are also much simpler ways just like u desrcibed creating an abstract class(Interface) and having all the classes implement this interface.
I am giving brief examples fo which here for your reference:
Dependecy Injection(From wikipedia):
In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A "dependency" is an object that can be used, for example as a service. Instead of a client specifying which service it will use, something tells the client what service to use. The "injection" refers to the passing of a dependency (a service) into the object (a client) that would use it. The service is made part of the client's state.
Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.
Python does not have such a conecpt inbuilt in the language itself but there are packages out there that implements this pattern.
Here is a nice article about this in python(All credits to the original author):
Dependency Injection in Python
Strategy Pattern: This is an anti-pattern to inheritance and is an example of composition which basically means instead of inheriting from a base class we pass the required class's object to the constructor of classes we want to have the functionality in. For example:
Suppose you want to have a common add() operation but it can be implemented in different ways(add two numbers or add two strings)
Class XYZ():
def __constructor__(adder):
self.adder = adder
The only condition being all adders passed to the XYZ class should have a common Interface.
Here is a more detailed example:
Strategy Pattern in Python
Interfaces:
Interfaces are the simplest, they define a set of common attributes and methods(with or without a default implementation). Any class then can implement an interface with its own functionality or some shared common functionality. In python Interfaces are implemented via abc package.
I have a lot of different child classes that inherit from one base class. However all the different child classes implement very similar methods. So if I want to change code in the child classes, I have to change it multiple times.
For me this sounds like bad practice and I would like to implement it correcty. But after a lot of googling I still didn't find a coherent way of how this should be done.
Here is an example of what I mean:
from ABC import ABC, abstractmethod
import logging.config
class BaseModel(ABC):
def __init__(self):
# initialize logging
logging.config.fileConfig(os.path.join(os.getcwd(),
'../myconfig.ini'))
self.logger = logging.getLogger(__name__)
#abstractmethod
def prepare_data(self):
"""
Prepares the needed data.
"""
self.logger.info('Data preparation started.\n')
pass
So this is my BaseClass. Now from this class multiple other classes inherit the init and prepare_data method. The prepare_data method is very similar for every class.
class Class_One(BaseModel):
def __init__(self):
super.__init()__
def prepare_data(self):
super().prepare_data()
# Some code that this method does
class Class_Two(BaseModel):
def __init__(self):
super.__init()__
def prepare_data(self):
super().prepare_data()
# Some code that this method does
# Code is almost the same as for Class_One
class Class_Three(BaseModel):
def __init__(self):
super.__init()__
def prepare_data(self):
super().prepare_data()
# Some code that this method does
# Code is almost the same as for Class_One and Class_Two
# etc.
I suppose you could refactor the methods into another file and then call them in each class. I would love to know how to do this correctly. Thanks a lot in advance!
I'm afraid there's no generic one-size-fits-all magic answer - it all really depend on the "almost" part AND on the forces that will drive change in those parts of the code. IOW, one can only really answer on a concrete example...
This being said, there are a couple lessons learned from experience, which are mostly summmarized in the famous (but unfortunately often misunderstood) GOF "Design Patterns" book. If you take time to first read the first part of the book, you understand that most of (if not all) the patterns in the catalog are based on the same principle: separate the variant from the invariant. Once you can tell one from the other in your code (warning: there's a trap here and beginner almost always fall into it), which pattern to apply is usually obvious (sometimes to the point you only realize you used this and that patterns after you refactored your code).
Now as I said, there IS a trap: accidental duplication. Just because two pieces of code look similar doesn't mean they are duplicates - quite often, they are only "accidentally" similar now but the forces that will make one or the other change are mostly unrelated. If you try to immediatly refactor this code, you'll soon find yourself making the "generic" case more and more complicated to support changes that are actually unrelated, and end up with an overcomplicated, undecipherable mess that only make your code unmaintainable. So the trick here is to carefully examine the whole context, ask yourself what would drive change in one or the other "similar" parts, and if in doubt, wait until you know more. If it happens than each time you change A you have to make the exact same change in B for the exact same reasons then you DO have real duplicate.
For a more practical, short-term advise based on what we can guess from your way too abstract example (and from experience), there are at least two patterns that are most often involved in factoring out duplication in a class hierarchy: the template method and the strategy.
NB : I said "unfortunately often misunderstood" because most people seem to jump to the patterns catalog and try to forcefit all of them in their code (whether it makes sense for the problem at hand or not), and usually by copy-pasting the canonical textbook _implementation_ (usually Java or C++ based) instead of understanding the _concept_ and implementing it in a way that's both idiomatic and adapted to the concrete use case (example: when functions are first class object, you don't necessarily need a Strategie class with abstract base and concrete subclasses - most often plain old callback functions JustWork(tm)).
EDIT totally unrelated but this:
def __init__(self):
# initialize logging
logging.config.fileConfig(os.path.join(os.getcwd(),
'../myconfig.ini'))
self.logger = logging.getLogger(__name__)
is NOT how to use logging. Library code can use loggers, but must not configure anything - this is the application's (your main script / function / whatever) responsability, the rational being that the proper logging config depends on the context - which type of application is using the lib (a CLI app, a local GUI app and a backend web app don't have the same needs at all) and in which kind of environment (a local dev env will want much more logs than a production one for example).
Also, with the logger created with __name__ in your base class module, all child classes will send their log to the same logger, which is certainly not what you want (you want them to have their own package / module specific loggers so you can fine tune the config per package / module).
And finally, this:
os.path.join(os.getcwd(), '../myconfig.ini')
certainly doesn't work as you expect - your cwd can be just anything at this point and you have no way of knowing in advance. If you want to reference a path relative to the current file's directory, you want os.path.dirname(os.path.realpath(__file__)). And of course adding system specific path stuff (ie "../") in a os.path.join() call totally defeats the whole point of using os.path.
General Python Question
I'm importing a Python library (call it animals.py) with the following class structure:
class Animal(object): pass
class Rat(Animal): pass
class Bat(Animal): pass
class Cat(Animal): pass
...
I want to add a parent class (Pet) to each of the species classes (Rat, Bat, Cat, ...); however, I cannot change the actual source of the library I'm importing, so it has to be a run time change.
The following seems to work:
import animals
class Pet(object): pass
for klass in (animals.Rat, animals.Bat, animals.Cat, ...):
klass.__bases__ = (Pet,) + klass.__bases__
Is this the best way to inject a parent class into an inheritance tree in Python without making modification to the source definition of the class to be modified?
Motivating Circumstances
I'm trying to graft persistence onto the a large library that controls lab equipment. Messing with it is out of the question. I want to give ZODB's Persistent a try. I don't want to write the mixin/facade wrapper library because I'm dealing with 100+ classes and lots of imports in my application code that would need to be updated. I'm testing options by hacking on my entry point only: setting up the DB, patching as shown above (but pulling the species classes w/ introspection on the animals module instead of explicit listing) then closing out the DB as I exit.
Mea Culpa / Request
This is an intentionally general question. I'm interested in different approaches to injecting a parent and comments on the pros and cons of those approaches. I agree that this sort of runtime chicanery would make for really confusing code. If I settle on ZODB I'll do something explicit. For now, as a regular user of python, I'm curious about the general case.
Your method is pretty much how to do it dynamically. The real question is: What does this new parent class add? If you are trying to insert your own methods in a method chain that exists in the classes already there, and they were not written properly, you won't be able to; if you are adding original methods (e.g. an interface layer), then you could possibly just use functions instead.
I am one who embraces Python's dynamic nature, and would have no problem using the code you have presented. Make sure you have good unit tests in place (dynamic or not ;), and that modifying the inheritance tree actually lets you do what you need, and enjoy Python!
You should try really hard not to do this. It is strange, and will likely end in tears.
As #agf mentions, you can use Pet as a mixin. If you tell us more about why you want to insert a parent class, we can help you find a nicer solution.
I have some algorithms to do that are very similar in very aspects but are all different.
I'll try to give an example of what I mean.
Let's assume I have a Robot class. This class should be the "base" of all classes. It provides basic mechanisms to make the robot work in its environment. It might or not have to work by itself (with this I mean it can either be an abstract class, that is useless by itself, or if possible, to have basics mechanisms to be ready to work).
All robots have hands. But some robots will have human-like hands, other will have blades, other will have razors. I could do a base class called RobotBase and then create RobotHumandHand, RobotBladeHand and RobotRazorHand. But they also can have different heads, different eyes, different legs, different arms, etc. Is there any easy way I can address this? I'd like to put this in a way that is a bit like LEGO, so I could just define a robot and "add" the pieces I want. Maybe through interfaces? I am not even aware if those exist in python(that's the language I'll be using).
Any comments / suggestions are really appreciated! Thanks!
The design patterns I'd probably go with for such a problem are: Dependency Injection and a framework to go with it, the Composite pattern, and the Builder pattern. They should basically let you separate the creation of your Robots from their use.
I think your robot should have a list of ports i.e. a number of injected components each robot may have. Your Robot class will be a container of RobotParts. You can have specific parts to have specific interfaces. RobotHand extends RobotPart and Robot class has a field that holds a list of RobotHand implementations (you can limit it to 2 hands, but in general case there could be more). You can do the same with RobotHead that will inherit from RobotPart and also there will be a field in Robot class holding implementation of RobotHead. In its turn RobotHead may hold a list of RobotEye implementations and so on. Then your specific Robot implementations may inherit their behavior from base class or take advantage of configuration e.g. by using RobotBladeHands if available.
I'm not a Python guy, but a quick look indicates they support multiple inheritance which can be used like Java Interfaces (Python does not seem to support interfaces). So you can have essentially superclasses for RobotHand then RobotHumanHand, RobotBladeHand, etc, Same with eyes, feet what have you. This is a reasonable way to do what you want to do.
If you are seeking for a design pattern, then I suggest you strategy pattern.Because Implementing this pattern you can dynamically interchange the components of robot.