I'm running @pythonetc, a Telegram channel about Python and programming in general. Here are the best posts of August 2018.Factory methodIf you create new objects inside your __init__, it may be better to pass them as arguments and have a factory method instead. It separates business logic from technical details on how objects are created.In this example __init__ accepts host and port to construct a database connection:class Query: def __init__(self, host, port): self._connection = Connection(host, port)The possible refactoring is:class Query: def __init__(self, connection): self._connection = connection @classmethod def create(cls, host, port): return cls(Connection(host, port))This approach has at least these advantages:It makes dependency injection easy. You can do Query(FakeConnection()) in your tests.The class can have as many factory methods as needed; the connection may be constructed not only by host and port but also by cloning another connection, reading a config file or object, using the default, etc.
I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.
Stay tuned to my blog, twitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.
metaprogramming,oop,software-architecture,software-development,python
Stay tuned to my blog, twitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.
This article is related to
metaprogramming,oop,software-architecture,software-development,python
No comments:
Post a Comment