192 points · by thedigicat · 7y ago · 62 comments
I just published on Leanpub a free book, "Clean Architectures in Python". It's a humble attempt to organise and expand some posts I published on my blog in the last years.
You can find it here: https://leanpub.com/clean-architectures-in-python
The main content is divided in two parts, this is a brief overview of the table of contents
* Part 1 - Tools - Chapter 1 - Introduction to TDD - Chapter 2 - On unit testing - Chapter 3 - Mocks
* Part 2 - The clean architecture - Chapter 1 - Components of a clean architecture - Chapter 2 - A basic example - Chapter 3 - Error management - Chapter 4 - Database repositories
Some highlights:
- The book is written with beginners in mind
- It contains 3 full projects, two small ones to introduce TDD and mocks, a bigger one to describe the clean architecture approach
- Each project is explained step-by-step, and each step is linked to a tag in a companion repository on GitHub
The book is free, but if you want to contribute I will definitely appreciate the help. My target is to encourage the discussion about software architectures, both in the Python community and outside it.
I hope you will enjoy the book! Please spread the news on your favourite social network
I would add a very important second part here "you think is correct".
An introduction to TDD that starts by implementing a function called `add` with `pass` or `return 9` is somehow deeply irritating to me.
The example would be so much closer to real world usage if you started with `a + b` and then realized the tests also require you to support 3 arguments.
Also: you introduced the test for three arguments after you wrote the first code for `add`.
In Philosophy of Software Design, J. Ousterhout says that this TDD practice encourages "tactical programming", i.e. trying to solve the current open ticket with minimum amount of work, instead of solving the problem correctly. Personally I'd go further. To me, this approach encourages replacing your brain with a dumb gradient descent process. Instead of thinking about the problem and solution, you just keep writing an ever larger monster whose sole purpose is to interpolate between test cases.
Tests themselves are useful. Following a process that makes meaning implicit instead of explicit? Not so much.
If your test is "add(4, 5)" and you implement add with "a + b", there is no failing test you can add. However, there are many classes of potential failures. For example, what if "a" or "b" is zero? What if one of them is negative? Even potentially, what about real numbers, etc. If you write your first failing test and then implement it with the entire solution, then you often stop with a single test that doesn't cover the edge cases you care about.
However, the real problem is explaining that style of TDD with such a simple function. I would never use a test first style for "add" unless there were some reason to do so (for example, there was some reason to assume that 0 wouldn't work). The "return the answer" trick is really useful when you have a function that has a very complex set of return values. You pick some arbitrary value to test against so that when you are working on the solution, you can see if you've broken then "happy path" test.
The "return the answer" bit is not even necessary, but it's handy to ensure that your test harness is working properly. I've often seen people do a "green-green-refactor" style of testing and write hundreds of lines of code only to realise that their tests weren't even running and the code doesn't work at all. It's 30 seconds of, "Can I write a test that makes the tests go red?", "Can I make the tests go green?" OK, let's begin.
> `add` with `pass` or `return 9` is somehow deeply irritating
Similar to others, I understand this feeling. And I would urge you to get over it.
First, technically returning 9 for a test of add(4,5) is correct. Your tests define what the function does, not the name. If you are thinking "a correct add adds all numbers", then that isn't wrong, but it is bringing your tacit world knowledge into the code without that knowledge being expressed in the code. And that's Not a Good Thing™.
It also seems to me that what you meant here was not "correct" (because it is correct), but "general". And that's one of the points of XP/TDD: as programmers we have a terrible tendency to over-generalise. Really horrible. "Write only the code to make the test pass" works against that tendency (and also has the nice gamification effect mentioned elsewhere).
The other point is when to generalise. The first answer is "not", the second is "not yet". Generalise only when you have several instances, otherwise your generalisation will, what's the technical term, suck.
Last not least is how to generalise. TDD/XP essentially say that you generalise only as a refactoring, that is a behavior-preserving transformation.
So when you add the add(10,2) test case, the really pedantic way of doing it would be to handle the extra case with an if-check, then once the additional test passes refactor the add method to handle all those cases with less code, by removing the case-handling and doing arithmetic.
What that means is that you separate the coding that gets the tests to pass from the more challenging bits of coding where you need to generalise, with the latter always under full test coverage.
It's a really nice way to make progress.
And of course: use your own judgement. If things get to tedious, it's OK to leave out steps. At some point you will probably find that you are running into problems, at that point you want to slow down and re-introduce more of the intermediate steps.
How do you feel about just starting with tests that are actually more of a specification? For example, I'm starting to feel that unit tests aren't something we should be writing, but are something we should be generating. We should be writing things like QuickCheck specifications. So the first test I'd probably write is:
given x. y. add(x, y) == x + y
This is a specification that is essentially tested against a "model" (native addition, in this case).
Tempted and conflicted. Yes, it's tempting, because "yay, more general and comprehensive", the mathematician inside me says.
On the other hand, the beauty of these sorts of tests is often precisely their concreteness/specificity. Tests should be so simple that their correctness is obvious by inspection. (One of my problems with specifications was always that to me it was no clearer that the specification captured what I wanted than that the code did).
The other side of the equation is that although theoretically such concrete tests are seriously flawed, because they only test one set of values, in practice that is actually usually quite sufficient.
> we should be generating
Again, sounds very reasonable, but now you have to trust (a) your generator and (b) your specification of those tests. I'd rather have a concrete test.
Now I do think there is some use for this sort of thing, for example in ferreting out edge cases that you might otherwise miss. I wouldn't want to rely on it.
Linus Torvalds didn't write the linux kernel or Git in this manner and ended up pretty well.
I get the idea behind TDD, and have used it successfully in areas where indeed the business case was very unclear.
But to drink the Uncle Bob Koolaid and pretend this is now the only way to do things is lacking in creativity, and wisdom imo.
I am not Linus. Maybe you are.
The reason I am such a fan of this approach is that I wrote software without it for a long time (Objective-C pre-processor/runtime, Postscript interpreter + various RIPs + other pre-press stuff, content mgt. system when that was still a thing...), and the difference is...hmm..let's say "significant".
Without this sort of approach, you get that rush of making super progress quickly, of holding the entire state in your head and being just the coolest cat on earth. It just doesn't last. Things start deteriorating, you fix a bug only to have another one pop up, after a while of this you get a sense of deja-vu and notice you've been going around in circles. Pretty soon you are stuck.
When I was put in charge of the CMS, management wanted to know when we would ship the next version. I couldn't honestly tell.
With a TDD approach, you get less of that rush, less of the "I am the greatest". What you do get is steady progress without backtracking.
> drink the Uncle Bob Koolaid
You shouldn't drink anyone's Koolaid, not mine and certainly not Uncle Bob's.
For your reference, I was doing this long before Uncle Bob. At least I remember sparring with him on comp.object, when he was still claiming that "OO is just function tables" and not a peep about TDD from him.
Oh, and can write a 9 that doesn't fail? That goes against TD; shouldn't I first break the lexical analyzer of my language so that the 9 constant goes red? Then repair things, so the 9 test goes green?
How can you call it TDD if you're relying on non-TDD pieces that work without being covered by tests that previously failed?
You are technically correct that testing "add(4,5) == 9" is valid. However, everyone already knows that an "add(a,b)" function which always returns 9 is broken.
> So when you add the add(10,2) test case, the really pedantic way of doing it would be to handle the extra case with an if-check
Saying an if-check is the correct way to refactor does a disservice to TDD practitioners everywhere.
Implementing a trivial add function via TDD is just bad. It would have been far better to choose something slightly more complicated such as sorting or fizzbuzz.
TDD is in a way a gamification of programming. You go back and forth between being rewarded with a green test suite, to challenging your implementation with another test, to "pinhole-surgery" for improving the implementation. Finally you get the relieve of being able to refactor your implementation without breaking the functionality.
So starting with stupid implementations delivers that first reward from the start and helps you find the rhythm of red-green-refactor.
Now of course TDD is also about making a correct implementation eventually, and usually you will get there after a handful of test cases.
You don't get into a flow state because of the reward / regular feedback alone. The challenge must match, or slightly exceed, your skill. Otherwise, you get bored. Boredom kills productivity and, ultimately, the point.
A competent programmer may as well just write out the addition implementation. I'd argue even that's too low a bar. In fact, I don't think it deserves a test (adding two numbers specifically).
That leads me to the second gripe. A majority of TDD examples are trivial problems. A great many are that trivial they wouldn't even warrant the time and expense to test in the real world, which is a genuine factor. If you're spending half your time testing trivial shit that can be verified by sight, you're not spending half your time testing what is crucial that may be difficult to verify without trying out the code.
Dogmatic TDD is the best way to practice and learn TDD. If you don't do this then you _will_ inevitably learn bad habits. Once you learn how to TDD like this you will begin to understand when you don't need to be dogmatic, but that only comes with experience.
I guess what I'm looking for is something like: "here's a list of array operations. Now do Towers of Hanoi". Any recommendations?
I found this the best way to start with python. YMMV.
[0] https://docs.python.org/3/tutorial/index.html [1] https://docs.python.org/3/library/index.html
Each chapter shows the minimal syntax needed for the chapter content, and then it has some exercises to get you going. I use it to teach Python to my Distributed Computing course students (2nd year students, which come mostly from a Java and C background).
The first chapters are mostly for beginners, so I guess you can skip them if you want. I also talk about more advanced concepts on the later chapters (such as iterators, generators, coroutines and asyncio). You can get the epubs/pdfs from [2]..
[1] https://github.com/joaoventura/full-speed-python/
[2] https://github.com/joaoventura/full-speed-python/releases/
As a language reference you could use something like that https://gto76.github.io/python-cheatsheet/ or another good book https://doughellmann.com/blog/the-python-3-standard-library-...
Definitely would recommend to anyone experienced wanting to learn Python.
Oh, and if you find a book series like that please let me know - I would love to move in to another language like C++ or similar, but I cannot be bothered reading about while-loops again.
I love this service as a publishing solution. You can write markdown and get your book updated to dropbox (while you write it/push it to VCS) and then publish directly through them to epub/PDF. But the other nice thing is they can export Amazon-compatible files so you can publish to Kindle.
They also offer a very fair and transparent royalty structure. I found Amazon could be a bit greedy. The reason why is when a book goes above 9.99, they increase the royalty significantly.
The only other tidbit I have to say is:
I also considered using sphinx-doc as a route to build the book. I haven't found a way to offer an appealing LaTeX (theme? template?) that'd work with it. If you do know LaTeX well, and have time on your side, maybe sphinx-doc could be down your alley. It can build to HTML, PDF, and epub.
As far as distribution goes: My experience with Apple's book store was very cumbersome. Difficult to get support, and in one case there was a glitch that unpublished the book.
thanks for writing the book.
What software did you use to writing?