constructor classmethods

teppo.pera at gmail.com teppo.pera at gmail.com
Mon Nov 7 04:14:01 EST 2016


torstai 3. marraskuuta 2016 14.47.18 UTC Chris Angelico kirjoitti:
> On Thu, Nov 3, 2016 at 7:50 PM,  <teppo... at gmail.com> wrote:
> > Little bit background related to this topic. It all starts from this article:
> > http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf
> >
> > The guide is written in c++ in mind, yet the concepts stands for any programming language really. Read it through and think about it. If you come back to this topic and say: "yeah, but it's c++", then you haven't understood it.
> 
> I don't have a problem with something written for C++ (though I do
> have a problem with a thirty-eight page document on how to make your
> code testable - TLDR), but do bear in mind that a *lot* of C++ code
> can be simplified when it's brought to Python. 
I know differences of c++ and python, as I have done programming in both languages for years. By the way, generally all design patterns, not just this one, are aimed to improve maintenance work, testability or flexibility and there are tons of books around these topics. This is good place to look at too:  https://sourcemaking.com/


> One Python feature that
> C++ doesn't have, mentioned already in this thread, is the way you can
> have a ton of parameters with defaults, and you then specify only
> those you want, as keyword args:
> 
> def __init__(self, important_arg1, important_arg2,
>         queue=None, cache_size=50, whatever=...):
>     pass
> 
> MyClass("foo", 123, cache_size=75)
> 
> I can ignore all the arguments that don't matter, and provide only the
> one or two that I actually need to change. Cognitive load is
> drastically reduced, compared to the "alternative constructor"
> pattern, where I have to remember not to construct anything in the
> normal way.
If writing two constructors start to feel cumbersome, it's always possible to make metaclass or decorator do at least basic one for you. For example, decorator can do __init__ to you and with that same information many other useful magic functions.

I see this more like of a trade-of of writing one factory method to help me write more stable and comprehensive tests vs having to write more brittle tests whose maintenance gets burden to developers (which can come real pain if things are done poorly in the beginning and the project goes forward). Python makes things much easier, but still care needs to be taken.

Finally, some wise words to think about (these are all tied up together):
"As an engineer, you should constantly work to make your feedback loops shorter in time and/or wider in scope." — @KentBeck

Br,
Teppo



More information about the Python-list mailing list