<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-6040130426871585154</atom:id><lastBuildDate>Mon, 09 Sep 2024 03:19:19 +0000</lastBuildDate><title>Feelings Erased</title><description>Object oriented, test-driven reality.</description><link>http://feelings-erased.blogspot.com/</link><managingEditor>noreply@blogger.com (Grzegorz Gałęzowski)</managingEditor><generator>Blogger</generator><openSearch:totalResults>72</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-4521758236411385623</guid><pubDate>Sat, 15 Oct 2022 20:35:00 +0000</pubDate><atom:updated>2022-10-15T22:35:15.127+02:00</atom:updated><title>An outside-in TDD youtube video series by me :-)</title><description>&lt;p&gt;&amp;nbsp;Hi!&lt;/p&gt;&lt;p&gt;I created and published a set of videos showing me &lt;a href=&quot;https://www.youtube.com/watch?v=_6QLOVJPkNQ&amp;amp;list=PL9P6lbfCUMCHcqXsHdVOcT4N3yif58jUA&quot; target=&quot;_blank&quot;&gt;doing outside-in TDD with hexagonal architecture in C#&lt;/a&gt;. The videos are very low-budget, which means:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;There is no voice commentary (I added subtitles though),&lt;/li&gt;&lt;li&gt;This was mostly done on first take and unedited (so there are some mistakes and screwups, I try to explain them in the subtitles)&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;Other than that, if you feel like you have ~6 hours to kill by watching me doing TDD of an an asp.net core app with hexagonal architecture and four different levels of tests, have fun!&lt;/div&gt;&lt;p&gt;&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2022/10/an-outside-in-tdd-youtube-video-series.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-5488036711082654161</guid><pubDate>Thu, 05 Mar 2020 00:20:00 +0000</pubDate><atom:updated>2020-03-05T13:25:28.251+01:00</atom:updated><title>Robert Pająk&#39;s &quot;Lessons Learned&quot; post - a gentle polemic</title><description>One of the people I respect and had very productive discussions with, Robert Pająk, published a blog post about &lt;a href=&quot;https://pajak.home.blog/2020/02/28/lessons-learned-after-1-year-of-programming-in-go-as-a-c-developer/&quot; target=&quot;_blank&quot;&gt;lessons learned from working with Go language&lt;/a&gt;. He points out 12 points and I thought it would be fun to comment on them from my own experience in OO design.&lt;br /&gt;
&lt;br /&gt;
Apologies for absolute tone in many places, I tried to keep this post short so I had to resort to some mental shortcuts. Also, it may seem a bit chaotic and general, which is because unpacking all of those thoughts would probably take me a book or two.&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Robert suggests to start project from a single assembly and then split into multiple apps or vertical segments. While I agree with the spirit of this point, I find this topic much more nuanced. First of all, my typical initial layout for apps is two assemblies - one for bootstrap/adapters (in the hexagonal architecture sense) and one for application logic. This way I can get the compiler to protect me from dependencies pointing in the wrong direction while keeping everything simple. When the application grows, I find partitioning vertically helps, although to achieve real vertical partitioning, I find that the features must differ significantly from each other. In other case, there&#39;s typically some kind of core model containing the code that many features need. Also, I have often some &quot;lib&quot; code growing aside, which fits in no specific place and could later be extracted as separate libraries.&lt;/li&gt;
&lt;li&gt;Robert suggests e.g. that &quot;a little copying is better than a little dependency&quot;. I strongly disagree. Not that I consider myself a reuse zealot but that I don&#39;t think there&#39;s a single rule defining all the possible cases. Also, I don&#39;t think &quot;little&quot; or &quot;much&quot; has much to do with this. My take on dependencies is:&amp;nbsp;&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;I try to avoid depending on frameworks. If I do, I keep them away from my application logic,&amp;nbsp;&lt;/li&gt;
&lt;li&gt;I always consider whether two pieces of code evolve together and if they do - what is the cost of them falling out of sync. Based on that I decide about dependency vs. copying,&amp;nbsp;&lt;/li&gt;
&lt;li&gt;I don&#39;t hesitate from pulling dependencies containing code that I could easily write by hand but am too lazy to do so (e.g. a Maybe library) - the reason is, when such dependencies cause issues, I can replace them with hand-written code without lots of effort.&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;Robert suggests that clear code is better than clever code. I agree 100% but would like to rephrase it into: &quot;if you can achieve the same with clear code or clever code, choose clear code&quot;. Sometimes I find writing clever code necessary (e.g. see how Functional.Maybe library checks whether a Maybe is &quot;something&quot; or &quot;nothing&quot;).&lt;/li&gt;
&lt;li&gt;Robert suggests to avoid interfaces that have one implementation, pointing to Mark Seemaan&#39;s blog. I&#39;d like to point several things.&amp;nbsp;&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;First, Mark says that single-implementation interfaces are a smell. I often see this rephrased into &quot;single implementation interfaces don&#39;t make sense&quot; which I strongly disagree with. Single implementation interfaces make sense when they are used to achieve ISP (e.g. separating &quot;mutate interface&quot; from &quot;read interface&quot;, see e.g. IReadOnlyList interface) or where they are needed to manage dependencies more cleanly.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Interfaces are also used extensively in the GOOS design/TDD approach which I often use. Still, I am against single implementation interfaces when added as an afterthought only to enable mocking. I find they often typically bad abstractions.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;The last comment, in regard to Mark&#39;s article is that I myself stopped using the phrase &quot;x is a smell&quot; and I find it unnecessarily offensive and somewhat arrogant.&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;Robert writes &quot;Do not use patterns, nor do not apply SOLID, DDD, CQRS unless it really helps&quot;. Depending on what it means to &quot;really help&quot; I either agree or disagree on this one. About patterns - I don&#39;t see using a pattern where it doesn&#39;t help as using a pattern at all. About principles - I consider it the whole point of a principle that I adhere to it before I see the &quot;real benefit&quot;. The point, I think, it that by following a principle I should not get into a situation where I would see how it really helps. I find that similar to sth. like &quot;be honest&quot; - the whole point is not to feel on my own skin that being dihonest doesn&#39;t pay.&lt;/li&gt;
&lt;li&gt;This point is about generics. I agree. Generics, at least in C#, cost not only in cognitive load. E.g. applying nullable reference analysis to generic code tends to get somewhat complicated.&lt;/li&gt;
&lt;li&gt;Robert suggests to avoid reflection and IoC containers. I agree fully.&lt;/li&gt;
&lt;li&gt;is about the cost of fluent API. I agree as well. My rule of thumb is: I treat fluent APIs as UX tool for developers. It pays back when the API has many users and needs to be very flexible while maintaining readability. I also consider fluent API &quot;a language in a language&quot; and effort must be taken to learn that language.&lt;/li&gt;
&lt;li&gt;is about SQL and ORMs. I don&#39;t know much about this topic, in my cases facades working on DTOs were typically good enough.&lt;/li&gt;
&lt;li&gt;is about testing. There are some sentences that I disagree with.&amp;nbsp;&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;&quot;Tests should show what the system does, instead of how it does it&quot; - if this means &quot;test on the highest level&quot;, then I disagree. A system is almost always composed of subsystems. The apps I write are typically only part of much bigger systems that even transcend software. Also, tests on different level have different purposes and properties.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&quot;Avoid mocking whenever possibile&quot; - I think mi agrement or not depends on what &quot;when possible&quot; means. When I use GOOS-style design approach, I use lots of mocks but I would still say I &quot;avoid mocking where possible&quot; because e.g. I don&#39;t have to mock value objects and so I don&#39;t.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&quot;There is nothing wrong in using real database or file system in your automated tests unless the tests are not taking too much time&quot; - time is not the only factor in play - there are others. One example is isolation.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&quot;Integration tests give more trust, because they work the same way as code in production&quot; - I disagree. Integration tests give more trust about two pieces of whatever being able to work together and functional tests give more trust about the functionality thus I see no superiority of integration tests in that regard.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&quot;Mocking often leads to testing implementation details instead of behavior&quot; - in principle, I disagree. In my opinion, there is nothing inherent of mocks that makes them any special in that regard. Most often when I hear people saying this, it means their testing approach does not match their design approach, thus they end up testing what their design approach considers an implementation detail while their&amp;nbsp;testing approach does not.&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;Again, about testing and test removal.&amp;nbsp;&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;&quot;If you have an integration test that already covers 10 of your unit tests, then just remove them&quot; - I disagree with that. First of all, most of my unit tests are functional tests. Functional tests and integration tests have very different goals, so I cannot see how one can be a replacement for another. Also, &quot;integration test&quot; is not an alternative to &quot;unit test&quot; - in fact, there are integration tests that can be written on the unit level (e.g. &quot;my DTO class should work with 3rd party serializer&quot;). Maybe &quot;integration&quot; here means &quot;higher level&quot; - in such a case, I disagree as well. I found that in my approach, different levels of tests have different properties and thus are useful for different things, e.g. I find faster tests very useful during refactoring when ran with a CT tool such as NCrunch.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&quot;Avoid writing tests for a single type&quot; - again, I think that depends on the design approach. I have several open source projects where I use different design approaches and hence my testing strategies are different. One of them is driven solely by end-to-end tests, while another has three-level testing pyramid with single-type tests at the bottom and end-to-end tests at the top.&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;&quot;There is nothing bad in multiple asserts in a single test as long as it verifies one scenario&quot; - not sure if I see something bad or not about it, but I do multiple &quot;physical&quot; asserts per test as well and find that I never had to regret the decision.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
</description><link>http://feelings-erased.blogspot.com/2020/03/robert-pajaks-lessons-learned-post.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-6318868827202648623</guid><pubDate>Tue, 23 Oct 2018 13:25:00 +0000</pubDate><atom:updated>2018-10-23T15:25:54.111+02:00</atom:updated><title>Sandro Mancuso &amp; Uncle Bob comparative design episode 6 notes</title><description>&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancusso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 1&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 2&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative_26.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 3/4/5&lt;/a&gt; &lt;br /&gt;
&lt;br /&gt;
The episode 6 was the first episode where Uncle Bob&#39;s approach is presented. This approach is much less familiar to me than Sandro&#39;s so I had a lot of observations about both uncle Bob&#39;s testing and his design approach. Not everything is clear to me but more, I hope, will unveil in the next episodes.&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;As described in the episode summary, he starts with UML diagram to identify a domain model consisting of abstractions and relationship between them. Also, Bob identifies a set of use cases on a whiteboard first.&lt;/li&gt;
&lt;li&gt;Bob starts his first test with a test file for a use case (e.g. for &quot;create user&quot; use case, he creates a file called CreateUserTest) and creates a first test called &quot;nothing&quot;.&lt;/li&gt;
&lt;li&gt;The &quot;nothing&quot; test quickly transforms into creation test (testing that a use case object can be created)&amp;nbsp;&lt;/li&gt;
&lt;li&gt;The second test is for the use case logic and is called &quot;canCreateUser&quot;. The use case class is called CreateUser - a verb, not a noun, which I am fine with. I don&#39;t think all classes names should be nouns and I consider this one a good example.&lt;/li&gt;
&lt;li&gt;When writing this test, Uncle Bob introduces a DTO and calls it CreateUserRequest. Also, he puts all the data as public fields, to stress that this is a data structure and not a class with behaviors.&lt;/li&gt;
&lt;li&gt;As a refactoring step, Uncle Bob moves all but assertions to the setUp() method, creating essentially what is called &quot;&lt;a href=&quot;http://xunitpatterns.com/Testcase%20Class%20per%20Fixture.html&quot; target=&quot;_blank&quot;&gt;testcase class per fixture&lt;/a&gt;&quot; test organization scheme.&lt;/li&gt;
&lt;li&gt;A surprising step - Uncle Bob does not inject repository to the use case. Rather, he makes a class called Context and places the repository in a mutable public static field of this class. In each test, he assigns his own in-memory repository to this field. Then the production class accesses this global variable to get the repository. This is, AFAIK, the &lt;a href=&quot;https://codopia.wordpress.com/tag/ambient-context/&quot; target=&quot;_blank&quot;&gt;Ambient Context&lt;/a&gt; pattern. The rationale for using it is that Uncle Bob doesn&#39;t like passing the reference to repository around. My comments on that choice:&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;Personally, I don&#39;t think the reference would be &quot;passed around&quot; - had Uncle Bob used a factory for the use cases, he could inject the repository from composition root into the factory and from there into the use case and that&#39;s it. Not sure I would call it &quot;passing around&quot;.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Another point would be that probably not every unit testing framework would let him get away with this. For example in xUnit.net, where tests are ran in parallel with each other, I assume he would see some nasty non-deterministic behavior.&lt;/li&gt;
&lt;li&gt;By creating the global mutable state, Uncle Bob creates a persistent fixture, which requires a manual teardown (either at the beginning or at the end of a test). I believe him he has enough discipline to keep it torn down at all times, but in team setup, I can see two programmers, each adding new tests and new fields to the Context, each anaware of what the other does and then they merge and it turns out that the changes made by programmer &quot;A&quot; do not include tearing down the things that programmer &quot;B&quot; added and vice versa. In other words, I believe it requires an immense amount of discipline and communication to keep this stuff clean at all times.&lt;/li&gt;
&lt;li&gt;This approach, as Sandro suggested, makes dependencies implicit. Uncle Bob argues that although it does make the dependency implicit, it does not hide it. Having looked at several definitions of what &quot;implicit&quot; means (I&#39;m not a native speaker), from my perspective I would call it &quot;hiding&quot; anyway.&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;When testing whether he can get the user that was put inside the repository by the use case, Uncle Bob makes a test fail by changing the in-memory repository to return a clone of the user instead of the original reference that was put inside the repository. Here I don&#39;t know what to think of it. This is because I am not sure how Uncle bob treats the InMemoryRepository class. If it&#39;s treated as a fake, a part of the test, then this is a legit TDD step, because by modifying the repository, Bob modifies the test fixture, i.e. he modifies the test. On the other hand, if the in-memory repository is a test fixture, then how did it end up in the org.openchat.repositories production package? This is the part that confuses me.&lt;/li&gt;
&lt;li&gt;An interesting part is that Bob tries to write the controller logic without a passing test and only goes to write one when he doesn&#39;t know what to write next in the controller logic. Bob doesn&#39;t want to mock the framework types (I wouldn&#39;t want to as well) and searches for another way, but this will be resolved in episode 7.&lt;/li&gt;
&lt;/ol&gt;
</description><link>http://feelings-erased.blogspot.com/2018/10/sandro-mancuso-uncle-bob-comparative.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-3665131748415173254</guid><pubDate>Wed, 26 Sep 2018 14:56:00 +0000</pubDate><atom:updated>2018-10-23T15:27:01.652+02:00</atom:updated><title>Sandro Mancuso &amp; Uncle Bob comparative design episode 3/4/5 notes</title><description>&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancusso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 1&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 2&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/10/sandro-mancuso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 6&lt;/a&gt; &lt;br /&gt;
&lt;br /&gt;
Here are my notes from &lt;a href=&quot;https://cleancoders.com/videos/comparativeDesign&quot; target=&quot;_blank&quot;&gt;Comparative Design&lt;/a&gt; episode 3,4 and 5 by Sandro Mancuso and Uncle Bob. There were less new things for me in these episodes, more of applying the approach from previous episodes on other use cases (so the notes are going to be short on this one) . Still, I enjoyed it and consider the watching time well-spent. As with previous posts, I will only list stuff that was new or controversial to me as that&#39;s what I use the notes for. There&#39;s lots of great stuff in these videos that I don&#39;t write about because I know them from womewhere else. Also, as these are notes, they are a bit unsolicited and messy - get over it.&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;I learned IntelliJ IDEA&#39;s shortcut ALT+SHIFT+F10 for launching tests from current class. I didn&#39;t know that - thanks Sandro &amp;amp; Uncle Bob!&lt;/li&gt;
&lt;li&gt;A nice comment from Sandro: In outside-in approach, each test represents a design decision&lt;/li&gt;
&lt;li&gt;When doing validation whether a post contains inappropriate words, Sandro delegates the validation (at least the condition) to a separate collaborator and calls it language service instead of &quot;validator&quot; - nice, I never really liked the name &quot;validator&quot;. After that, he extracts the condition together with decision to throw exception to a separate method called validate(). Typically, I call methods that throw when a condition is not met &lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;assert...()&lt;/span&gt; by analogy to how they are called in xUnit frameworks.&lt;/li&gt;
&lt;li&gt;When implementing the &quot;adding posts&quot; requirement, Sandro leaves the repository empty since there is no requirement for reading from the repository yet. I like that - there was no point inventing a speculative reading feature for the class only to see it turn out different in the future when driven by a real use case. On the other hand, however, this might be a singnal that the acceptance tests do not revolve around use cases. Is &quot;add a post and receive OK&quot; really a valid customer use case? What use is adding a post if the post cannot be read? Thus, I would probably have a test where I would add a post and then read it, because from the user point of view, only then is the API useful at all. Well, there may be a case where someone writes their own GUI client and wants to integrate with each method as fast as possible (thus having POST only would be beneficial to them as it would allow them check their client compatibility), but I didn&#39;t find anything to confirm this is the assumed scenario here. Also, if I only could do one of read/write in an iteration, I would pick reading first as it would already allow showing the customer how posts look like on the GUI.&lt;/li&gt;
&lt;li&gt;When testing the language service (a piece of code that rejects inappropriate words), Sandro picks &quot;elephant&quot; for a bad value (because &quot;elephant&quot; is one of the inappropriate words), but uses &quot;OK text&quot; for a good value. I would probably pick some text that&#39;s closer to the boundary, e.g. &quot;elephan&quot; to show that the whole word has to match to reject it. Several seconds later, Sandro picks some more examples of bad values, some of which I wouldn&#39;t think of (e.g. all uppercase ELEPHANT). Sandro&#39;s comment on this: &quot;I don&#39;t like baby steps&quot;. I can understand that - baby steps are typically for exploratory stuff and this is a CRUD app so no surprises are expected here.&lt;/li&gt;
&lt;li&gt;When testing with APIs that accept collections, Sandro uses a single-element collection. I typically &lt;a href=&quot;https://blogs.msdn.microsoft.com/ploeh/2008/12/08/3-is-many/&quot; target=&quot;_blank&quot;&gt;prefer 3 elements&lt;/a&gt;&amp;nbsp;although I must say that this time Sandro&#39;s preference is closer to boundary value testing - interesting :-).&lt;/li&gt;
&lt;li&gt;Another interesting observation is that Sandro does sorting of posts (to have the latest post first) in the repository but filtering of logged-in user (when showing all users) in the GUI. I have to admit (and Sandro does as well) these are hard decisions to make and typically an assumption made on these things gets validates as more code appears.&lt;/li&gt;
&lt;li&gt;The rest of the episodes 4 and 5 are more or less about the same stuff, so I see no point taking too much notes from them. The only interesting fact is that when Sandro registers a following (a relationship saying that one user follows the other) - and, while there is some validation whether the following already exists, there is no validation whether the users exist at all. I wonder why - does Sandro trust that only the UI will use the API and hence no one will send IDs that don&#39;t exist?&lt;/li&gt;
&lt;/ol&gt;
&lt;ol&gt;
&lt;/ol&gt;
&lt;div&gt;
And that&#39;s it. This concludes my notes on Sandro&#39;s part (of course, after Bob&#39;s part there will be some dicsussion between both of them). As a final note on this part of episodes, I&#39;d like to comment on the example problem that is used in comparative design case study. It&#39;s about writing a backend API for a twitter-like app. The best part about the chosen problem is that it is a realistic one and allows showing TDD with randomness, I/O and some other stuff that usually gets left behind in simple examples, end to end from controller to cache (without a real database though). The worst part of it is that it lacks a significant amount of logic around the use cases. Basically, it&#39;s almost a plain CRUD app and if we dropped the layering from the design, each use case would take around 10-15 lines of code to implement. And now we come to my greatest source of confusion. Sandro deciding to introduce the layering means he clearly wanted to show how to design something maintainable. On the other hand, some of the choices he made looked to me like cutting corners because this is a very simple app. No thread safety, no authorization, no authentication. Also, unfortunately, no elaborate requirements like &quot;when you create a post and this is a 10th post created during the last second, we will consider you are a bot and disallow you from posting for 10 minuts&quot;. The resulting domain model turned out very anemic and consisting mainly of DTOs. I&#39;d rather see less use cases but more elaborate because interactions between entities and domain concepts is where GOOS authors wrote this style really shines. Still, I enjoyed the episodes and I think this part is something that every senior coder should watch as even without an elaborate domain, it contains lots of great insight, tips, tricks and discussion. I look forward to Uncle Bob&#39;s episodes and the concluding discussion!&lt;/div&gt;
</description><link>http://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative_26.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-7090704735406832773</guid><pubDate>Tue, 11 Sep 2018 09:50:00 +0000</pubDate><atom:updated>2018-10-23T15:26:51.247+02:00</atom:updated><title>Sandro Mancuso &amp; Uncle Bob comparative design episode 2 notes</title><description>&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancusso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 1&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative_26.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 3/4/5&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/10/sandro-mancuso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 6&lt;/a&gt; &lt;br /&gt;
&lt;br /&gt;
After &lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancusso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;notes from episode 1&lt;/a&gt;, I promised some notes after &lt;a href=&quot;https://cleancoders.com/episode/comparativeDesign-episode-2/show&quot; target=&quot;_blank&quot;&gt;episode 2&lt;/a&gt; and here they are.&lt;br /&gt;
&lt;br /&gt;
As with the previous post (please read the disclaimer that&#39;s there if you didn&#39;t), I am focusing on the stuff I disagree with, would do in another way or consider controversial. This is because that&#39;s what I learn from the most, not because I want to prove to anyone that I am smarter or something. There was also lots of great stuff that I just happen to agree with, so I won&#39;t write a lot about that. Also, remember that the episodes show code in evolution, so it may be that some choices Sandro makes are temporary or made with knowledge that no further development will be done in specific code areas.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;
General Remarks&lt;/h2&gt;
&lt;div&gt;
Stuff I forgot to write down from the first episode and is also in the second.&lt;/div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;I noticed that Sandro mixes Mockito with BddMockito, which seems kind of strange to me. Typically what I see is that people prefer one namespace or the other, but Sandro takes stubbing syntax from BddMockito (given(...).willReturn(...)) and verification syntax from plain Mockito (verify(...)). I wonder what he does when he works with his team - whether they all use this convention or someone gives up and agrees to use something different.&lt;/li&gt;
&lt;li&gt;Sandro doesn&#39;t use a TODO list anywhere in the example. I think one of the reasons is that his UnsupportedException occurences work as TODO marks. The other may be that this is a prepared exercise so there&#39;s little exploration and question marks to be investigated. When doing prepared presentations, I also very rarely use a TODO list, so I don&#39;t see any issue with that.&lt;/li&gt;
&lt;li&gt;He uses TDD together with &lt;a href=&quot;http://www.netobjectives.com/files/books/esad/essential-skills-programming-by-intention.pdf&quot; target=&quot;_blank&quot;&gt;programming by intention&lt;/a&gt;. This is something I&#39;ve never done before, I will try to practice it a bit in the coming weeks.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
Now for the main notes.&lt;/div&gt;
&lt;/div&gt;
&lt;h2&gt;
&amp;nbsp;Users API&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;The beginning of the episode is about finishing the user API, where a UserService instance should create a user. Sandro moves the randomness of generating user ids (UUIDs) to a separate class, called IdGenerator and says he will not test it as it is not deterministic. While I agree that it isn&#39;t deterministic, I think some of the properties of the ID generator may be. Personally, I think it still is a material for a property-based test. Though there&#39;s (almost non-existent) chance of generating a UUID that was once used, I think it is reasonable to expect from the algorithm that no two UUIDs generated in a sequence are the same. Sure, that would lead to a discussion on &quot;why two, not three&quot; etc., but I would still write a small test around that property, especially that the return value of the generator is String, not UUID, so there&#39;s nothing in the signature that forces one to use UUIDs in the implementation.&lt;/li&gt;
&lt;li&gt;The next test for the UserService is about throwing an exception when a user that we&#39;re trying to create is already in the repository. Sandro uses JUnit&#39;s expected exception annotation: @Test(expected = UserNameAlreadyInUseException.class). Not sure why he prefers it to AssertJ&#39;s built-in &lt;a href=&quot;http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion&quot; target=&quot;_blank&quot;&gt;assertThatThrownBy()&lt;/a&gt;. While this is a recent feature, I think it was already around when the video was recorded. Typically when I read people writing on asserting exceptions, the annotation-oriented solutions are considered the inferior ones to specialized assertions.&lt;/li&gt;
&lt;li&gt;In the same test, Sandro wonders whether to return an optional or to create a query method named &quot;isUsernameTaken()&quot;. Only if that method returns true does he go on and create the user. I think I can see why he doesn&#39;t use an optional - because that would not scale - he would need to establish an implicit assumption that every Optional.empty() returned from repository means that user name is already taken, which could be a bit of stretch. Alternatively, he could throw the exception straight from the repository, but that might mean pushing some of the application logic into what can essentially end as adapter (but currently Sandro puts his repository together with domain logic). On the other hand, I&#39;m wondering whether his solution would hold in a more real-life environment of race conditions and multiple threads accessing the repository. Sandro seems to assume no such requirement for this system since if there was one, the access to the repository would need to be synchronized. Then, he would probably need to solve the dilemma of where to place the synchronization construct. I wonder what would be his answer.&lt;/li&gt;
&lt;li&gt;Another thing I am wondering about is whether Sandro considers the repository he created a domain construct or an adapter in the hexagonal architecture sense. He puts it into domain logic for now, but actually how he thinks of it can influence what kind of logic he may be inclined to push inside and what kind of logic he would like to keep away from it. Especially that Sandro says this is going to be replaced by a database at some point.&lt;/li&gt;
&lt;li&gt;An interesting fact is that he defers the technology choice for the persistence mechanism. Not sure if he will implement it or not. This is the place where in normal project I would like to see something like a story map to be sure where I am, since the external API description in Swagger does not say anything about persistence, so as a behavioral specification, it is incomplete. If this is the only specification we have, then what should we derive our need for persistence from?&lt;/li&gt;
&lt;li&gt;When testing the isUserTaken() behavior in the repository, Sandro writes two tests in a single method - one for true (name is taken), one for false (name is not taken). For me these are two behaviors and I would like to write them separately. When I look at it, the behavior looks to me like a good candidate for a parameterized test, although I must say that JUnit 4 does not make writing parameterized test methods easy. At the very least, if I really felt this is closer to a single behavior (just that each assertion shows one side of the coin), I would employ the &lt;a href=&quot;http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#soft-assertions&quot; target=&quot;_blank&quot;&gt;soft assertions&lt;/a&gt; feature of AssertJ to not stop on the first assertion failure.&lt;/li&gt;
&lt;li&gt;There is a nice discussion between Sandro and Bob on why there isn&#39;t a getUser() method in the repository that would allow checking whether the user is in the repository or not. I agree with Sandro that adding such method would be premature as no existing use case needs it yet and I think something like this would constrain my internal implementation.&amp;nbsp;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
Login API&lt;/h2&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;I noticed that Sandro doesn&#39;t use named constants in tests. Even though the production code uses the library-defined OK_200 constant (as funny as this name might be), the test uses plain 200. Not sure what the rationale is as it is never given, so I am going to try and guess that Sandro does not trust the constants and wants the tests independent of them because if tests used the named constants as the production code does, the values of the constants would essentially fall out of scope of a test, so if the value of OK_200 changed at one point, there would be no test to detect that. Personally, I prefer a different way of including constants in the test scope. I use the named constants everywhere in the tests and write an additional small test that says assertThat(OK_200).isEqualTo(200) writing such test takes me literally half a minute and the dilemma is solved for me. Now if the value of the constant changes, I have a single test to maintain.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Just as Sandro created UserApi class, he creates LoginApi. I think not putting both registration and login methods in the same class is a clever move because by doing that, Sandro establishes vetrtical architecture slicing and has a green field for his new feature in a fresh vertical slice.&lt;/li&gt;
&lt;li&gt;Interestingly, Sandro goes straight to the repository from the LoginAPI, not introducing any kind of LoginService as he did in case of the UserAPI -&amp;gt; UserService-&amp;gt;UserRepository. The rationale is that the login API is so simple that in this case Sandro is willing to do an exception and move away from what he considers a redundant abstraction layer. I think that doing that is a nice demonstration of benefits of vertical slicing, since he can make this decision for login API without affecting the user API. This is one of the reasons why I like vertical slicing so much. If he did put both registration and login methods in the same API class, it would look confusing that for one feature, the API goes to the service which goes to the repository and for another the same API class goes straight to the repository. That being said, I don&#39;t understand in what way is the login API simpler than the user API - both are plain &quot;DTO for DTO&quot; cases with &quot;else return error&quot; conditions so I see no significant factor that would lead me to taking a different approach in each case.&lt;/li&gt;
&lt;li&gt;I have some (temporary?) concerns with the UserCredentials class - it seems to be a a DTO and a value object in one. While I don&#39;t have much against DTOs implementing comparison operations for convenience, the class later seems to get more responsibilities that make it even more similar to a value object (i.e. a method &lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;boolean matches(User user)&lt;/span&gt;). Maybe this is a beginning of evolution that I will observe further in the next episodes?&lt;/li&gt;
&lt;li&gt;In my notes form the last episode, I noticed that Sandro established a relationship between test values where such relationship is not required. He did the exact contrary in the login API test. Here, he created input UserCredentials and did not make data relationship between it and the User object set to be returned by a mock. He only established such relationship between User and its JSON representation, using the User instance as a reference. This is exactly how I like to handle such cases. This way it is clearly shown that it&#39;s not the login API&#39;s business to say what kind of values will the User object hold - this responsibility is pushed onto the UserRepository class.&lt;/li&gt;
&lt;li&gt;Sandro has two identical methods called jsonContaining() but chooses not to remove the duplication. He gives a nice explanation that he is still not sure whether the two occurences of this method will change for the same or different reasons. Also, I can only guess that he is more careful with refactorings that come across vertical slices, but this is only my assumption. I would maybe leave a TODO here if I believed this conflict can be resolved in a foreseeable future. If I believed otherwise, I would probably eliminate this duplication because it would probably be easier for me to later copy-paste than find all the ocurrences of a piece of code.&lt;/li&gt;
&lt;li&gt;In the controller test, Sandro has the following login() method:&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;String login(Request request, Response response) {&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; UserCredentials credentials = credentialsFrom(request);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; Optional&amp;lt;User&amp;gt; user = userRepository.userFor(credentials);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; if(user.isPresent()) {&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; response.status(OK_200);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; response.type(&quot;application/json&quot;);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; return jsonFor(user.get());&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; }&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; response.status(NOT_FOUND_404);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; return &quot;Invalid credentials&quot;;&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;One thing that bothers be is that in the test for the case where a user is NOT present, there is no assertion on the content type of the response, which means that if I move the line response.type(&quot;application/json&quot;) above the if statement, all the tests are going to compile and pass but the response is going to be different. I assume that from Sandro&#39;s perspective, this doesn&#39;t matter as he has only one client application and that application doesn&#39;t care (or maybe acceptance tests check that?). Typically in what I do for a living, I am told to be strict about what I offer through my API and generous about what I accept. This is because where I work, the API is the product and I don&#39;t know all the client applications up-front.&lt;/li&gt;
&lt;li&gt;In the same method, a choice between response.status(OK_200) and response.status(NOT_FOUND_400) is what I call a situation of exclusive choice. In other words, this is not like an &quot;add&quot; method that can be called multiple times, but only one call to the status() method makes sense and it must be exclusively chosen. In such situation, I typically use Mockito&#39;s VerifyNoMoreInteractions() to make sure only one choice is made. In this case, however, there are several calls to the response object so VerifyNoMoreInteractions() would be too coarse-grained because it works for the whole mock, not for a single method. The code can be refactored (I will show how in a second) to make the use of VerifyNoMoreInteractions easier or something like this could work:&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;verify(response).status(OK_200);&lt;br /&gt;verify(response, never()).status(intThat(status -&amp;gt; !status.equals(OK_200)));&lt;/span&gt;&lt;br /&gt;This could be also refactored to something like:&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;verifyStatusSetExclusivelyTo(OK_200, response);&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;The whole rationale for me doing it is that presence of two different calls to response.status() in one method move a potential error of calling them both at some point to the &lt;a href=&quot;http://www.sustainabletdd.com/2015/12/specifying-negative-in-tdd_11.html&quot; target=&quot;_blank&quot;&gt;Inherently possible (can be made impossible)&lt;/a&gt; group from the inherently impossible (can be made possible) group.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Sandro refactors the login() method to use two more methods and ternary operator (condition ? a : b) to transform the code into something like this:&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;String login(Request request, Response response) {&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; UserCredentials credentials = credentialsFrom(request);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; Optional&amp;lt;User&amp;gt; user = userRepository.userFor(credentials);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; return user.isPresent() &lt;br /&gt;&amp;nbsp; ? prepareOkResponse(response, user)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;: prepareErrorResponse(response);&lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Bob and Sandro briefly discuss this choice, Sandro commenting that he likes ternary operator and that the real problem with ternary operators is when you chain them. Personally, though I have nothing against ternary operator as such I see one more issue with the use of ternary operator in this case and the refactoring that was done here. To demonstrate it on a simpler example, I find the following use of ternary operator confusing as well:&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;int a = getA();&lt;br /&gt;int b = getB();&lt;br /&gt;int c = getC();&lt;br /&gt;int y = (a = b) == 3 ? c = 1 : 4;&lt;/span&gt;The part that confuses me in the code above (besides the cryptic variable names :-)) is that there are side-effects in ternary operator - two assignment operators which, in C-like languages, happen to return value as well. A ternary operator turns &quot;if&quot; from statement to an expression and typically when I see someone make expression out of a statement like this, it is to stress that the whole code in scope of the operator is just a composition of pure expressions or pure functions. This is where I think ternary operator is even clearer in conveying intention than the if statement. But this is not what happens in the login() method as both prepareOkResponse() and prepareErrorResponse() are impure functions with side effects, similarly to the assignment operator I presented above. For example, the prepareErrorResponse() is defined as:&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;private String prepareErrorResponse(Response response) {&lt;br /&gt;&amp;nbsp; response.status(NOT_FOUND_404); //side effect&lt;br /&gt;&amp;nbsp; return &quot;Invalid Credentials&quot;;&lt;br /&gt;}&lt;/span&gt;&lt;br /&gt;When looking at the login() method and the ternary operator, I wouldn&#39;t expect to find side effect in a function like this, so this is not my favorite solution. What would I do instead? Probably either I would not do the refactoring or (in more complex use case) I would refactor further to something like custom result observer or collecting parameter, which would on the other hand cost me at least one or two new classes (and would probably require moving the login() method logic to a service class from the controller). The code could then look like this (note that the Response type is changed to my own custom class):&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;void login(Request request, MyOwnResponse response) {&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; UserCredentials credentials = credentialsFrom(request);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; Optional&amp;lt;User&amp;gt; user = userRepository.userFor(credentials);&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; if(user.isPresent()) {&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; response.foundCredentialsMatching(user.get());&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; } else {&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; response.InvalidCredentials();&lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&amp;nbsp; &amp;nbsp; }&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;This would have the added benefit that I could now use VerifyNoMoreInteractions on the response object as now there is only one exclusive call to this object in each case and the situation of exclusive choice becomes clearer.&lt;br /&gt;&lt;br /&gt;Note that in my example, the login() method is void. This would be a result of pushing the responsibility of holding the return value to the MyOwnResponse class. Someone that calls the login() method (in my case - a controller) could then do something like this:&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;loginService.login(request, response);&lt;br /&gt;return response.text();&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Sandro claims his acceptance tests only test the sunny day scenarios because of test pyramid, so he pushes all the error conditions into the unit tests. Personally, I typically don&#39;t have as dramatic dilemma as I write bigger systems where there are three or four levels of tests. And while I would not test error conditions in the end-to-end tests, I would not leave them for unit tests alone. I would have maybe one test at the lowest test level where I still have real network and HTTP, one test for each error category in tests that test the whole component logic in isolation from external resources and leave the rest to unit tests. My experience is that errors and validation is something that sometimes can be more tricky than the sunny day logic. Moreover, I remember writing some code where error detection and reporting is the only logic there is (e.g. assertion libraries) so (even though the openchat app is not like that) I personally believe that validation and error reporting is often underrated part of the system, especially when it is a big system.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;An interesting observation is that, while Sandro tends to prefer vertical architecture slicing, his package structure does not seem reflect it (yet?). For example, he has &lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;domain.posts&lt;/span&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt; package where I would expect &lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;posts.domain&lt;/span&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt; with posts, the vertical feature, as the main package differentiator. That may be a temporary choice so I think I would need to watch more and see for myself.&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
And there it is. I suspect I will not be doing as lengthy notes onward as there will be less things I will see for the first time, but I can be wrong :-).&lt;/div&gt;
&lt;/div&gt;
</description><link>http://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-7422620337703635683</guid><pubDate>Thu, 06 Sep 2018 10:33:00 +0000</pubDate><atom:updated>2018-10-23T15:26:40.714+02:00</atom:updated><title>Sandro Mancuso &amp; Uncle Bob comparative design episode 1 notes</title><description>&lt;b&gt;Update&lt;/b&gt;: &lt;a href=&quot;https://twitter.com/GGalezowski/status/1037653093750644736&quot; target=&quot;_blank&quot;&gt;Sandro commented on my notes in a twitter thread&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 2&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;https://feelings-erased.blogspot.com/2018/09/sandro-mancuso-uncle-bob-comparative_26.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 3/4/5&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://feelings-erased.blogspot.com/2018/10/sandro-mancuso-uncle-bob-comparative.html&quot; target=&quot;_blank&quot;&gt;Notes from episode 6&lt;/a&gt; &lt;br /&gt;
&lt;br /&gt;
I just finished watching episode 1 of Uncle Bob and Sandro Mancuso&#39;s&amp;nbsp;&lt;a href=&quot;https://cleancoders.com/videos/comparativeDesign&quot;&gt;London vs Chicago Comparative Design Case Study&lt;/a&gt;&amp;nbsp;and enjoyed it. I really recommend this case study to anyone who wants to learn more about TDD.&lt;br /&gt;
&lt;br /&gt;
This episode 1 was about Sandro beginning writing a twitter-like application and the first tests. Sandro claims to use the London Style TDD school, which is heavily based on mocking and outside-in approach. The school originated (AFAIK) from the Growing Object Oriented Software Guided By Tests book. Because of that and because I prefer this approach to design as well, I thought it could be interesting to write down, even if only for the &quot;future me&quot;, the notes on the differences I think I can see between what Sandro did and what GOOS would do and what I would do. Of course, this is only based on episode 1, so some things may change during the next episodes.&lt;br /&gt;
&lt;h3&gt;
Disclaimer&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;This is a set of notes, not a full blown article, so its structure might be a bit too dense and unsolicited. I welcome discussion and requests to clarify stuff. If you didn&#39;t see the episode, there is a high chance some of what I write will not make sense to you.&lt;/li&gt;
&lt;li&gt;This post is not a critique of Sandro&#39;s style. I am not claiming that I am better in TDD than Sandro or better in this particular style of TDD. While I may sometimes sound as if I find some ideas silly, it&#39;s just for showing this stuff from the perspective of my biases and default choices (this is why sometimes I will describe my feelings, not only rational judgement). I am by no means suggesting that my choices are/would be better. I am sharing this because I think that sharing thoughts (and feelings) leads to interesting discussions. If you find me being disrespectful, please point it out so that I can correct it.&lt;/li&gt;
&lt;li&gt;While I point some of the differences I think I see between GOOS and Sandro&#39;s TDD, it&#39;s not that I do EVERYthing like in GOOS. I am not including the differences between my TDD and GOOS TDD because I figured nobody would be interested in that :-).&lt;/li&gt;
&lt;li&gt;I am not an authority on what is and is not compliant with GOOS style. I just write my subjective opinion based on my observations that may be wrong. If you see me missing the point, please point it out so that I can correct it and learn from the exercise.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
Differences between Sandro&#39;s TDD and GOOS:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;GOOS worked example started with a single acceptance test, then some code was written (without unit tests) just to make this acceptance test pass, resulting with a walking skeleton. The next step would be to refactor the existing code based only on the acceptance test and then introduce some first abstractions and place to insert mocks for future behaviors. Sandro does two things differently:&amp;nbsp;&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;He has all the acceptance tests written up-front (Update: this was explained by Sandro as being an input condition for the whole exercise)&lt;/li&gt;
&lt;li&gt;He drives even the very first feature with unit tests already.&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;GOOS advises writing the acceptance tests in a domain language. For that, it recommends building a testing DSL that isolate a test from the implementation details like delivery mechanism. Sandro uses plain RestAssured library calls without (almost) any abstractions on top of it. This may be because Sandro&#39;s tests are not really end-to-end, but they are tests for HTTP contracts between the front-end and the back-end (Update: this was explained by Sandro as being an input condition for the whole exercise). Also, Sandro calls his tests &quot;integration tests&quot;, which is a term that is used for a different kind of tests in GOOS, but that might not be an issue since, as I believe, the &quot;integration&quot; is more about the goal of a test, not about a level or kind.&lt;/li&gt;
&lt;li&gt;GOOS advises usage of strict mocking framework (JMock), while Sandro uses a more-loose-by-default mocking framework (Mockito). Usage of strict mocking framework by GOOS was not merely a choice dictated by the availability of tools at the time the book was written. On the GOOS mailing list, there is a comment by Steve Freeman that he considers strictness-by-default part of his style (cannot find it now though).&lt;/li&gt;
&lt;li&gt;GOOS advises mocking interfaces, while Sandro up to now has only mocked classes. As above, the choice to introduce and mock interfaces in GOOS was not dictated by the limitation of tools at that time. It was a deliberate choice to think of interfaces as roles that objects play and GOOS authors claim they are aggressive in refactoring interfaces to make them smaller and more abstract.&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
&lt;h3&gt;
Now time for the differences between Sandro&#39;s TDD and my TDD:&lt;/h3&gt;
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Sandro starts all his tests from a name and then an assertion. As this is one of my ways to start a failing tests, it&#39;s not the only one that I use. &lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-how-to-start&quot; target=&quot;_blank&quot;&gt;In my book, I describe 4 different approaches to starting with a failing test&lt;/a&gt;, starting from assertion being one of them.&lt;/li&gt;
&lt;li&gt;Sandro uses underscores in test names and lower camel case in production code method names. It&#39;s just a matter of preference, but I find that confusing - I find it better to stick to a single convention, which has the added value of simplifying the configuration of static analysis tools that enforce naming convention and takes one dilemma away. Still, this is not a big deal, just a matter of style.&lt;/li&gt;
&lt;li&gt;Sandro tends to prefer realistic test data even where this is not needed or required. In the first test, where he passes data for user registration, he chooses a realistic name, (semi)realistic password and the ID is generated as UUID and converted to string. This is not needed at all, because the object under test does not handle any validation and, as we find out later, the only class that knows that the user ID is actually a UUID is the IdGenerator - in the rest of the cases, any string would do. Personally I use dummy data wherever validating this data is not the responsibility of the object under test because I find that by doing it, I describe the contract of my class with its collaborators more precisely. Whenever I see a specific/realistic data, I interpret it as if it was required by the tested object. Also, I am confused about one more thing - if I use another ID generator or change the implementation of existing one, should I change the &quot;realistic data&quot; in the tests where it doesn&#39;t matter?&lt;/li&gt;
&lt;li&gt;Also, I wouldn&#39;t establish relationship between test data fragments where it is clearly not required. For example, Sandro creates a registration object with &quot;name&quot;, &quot;password&quot; and &quot;about&quot; fields and sets up a mock of a service object to return a User object with the same three values. Personally, I don&#39;t see why. The responsibility for establishing relationship between input and output values is clearly pushed to another class that is mocked (a service class), so in my mind, this is leaking responsibilities of another class to tests of class that clearly does not care. And as I understand GOOS compositional approach to design and its principle of context independence, a class and its tests should not assume in what context the class is used.&lt;/li&gt;
&lt;li&gt;Sandro moves parts of the code to the setup method and parts of the data to fields of class with tests, arguing that this is cleaner.&amp;nbsp;&lt;a href=&quot;http://feelings-erased.blogspot.com/2012/11/dont-use-setup-and-teardown-or-i-will.html&quot;&gt;I wrote a blog post long ago explaining why I don&#39;t like this idea&lt;/a&gt;&amp;nbsp;and why I find such tests harder to read and maintain with the &quot;&lt;a href=&quot;http://xunitpatterns.com/Testcase%20Class%20per%20Class.html&quot; target=&quot;_blank&quot;&gt;Testcase class per class&lt;/a&gt;&quot; organization approach.. Looking at the video, the setup method is called &quot;initialise&quot;, which I find a meaningless name and usually read it as &quot;bag for everything I don&#39;t want to look at&quot;. Thus I consider it a smell and I also feel it takes away a bit of the pressure from tests to improve the design. When I see some logic that I strongly feel could be moved to a setup method and fields, this leads me to searching for a way to improve the design. I find setup methods hiding these issues for me. I understand that most probably, Sandro has a way of compensating for all the issues I described and maybe even making them irrelevant.&lt;/li&gt;
&lt;li&gt;The method of UserAPI class that Sandro test-drives clearly violates the principle of command-query separation (it is a command that returns a value as well). This is often what frameworks require us to do, unfortunately. Sandro chooses to push this violation further into the application/domain layer (specifically - the UserService class). Personally, I tend to cut away from this kind of violation on controller level using a &lt;a href=&quot;http://wiki.c2.com/?CollectingParameter&quot; target=&quot;_blank&quot;&gt;Collecting Parameter pattern&lt;/a&gt; and then I only deal with commands, which I find makes the rest of my tests easier.&lt;/li&gt;
&lt;li&gt;In the controller test, Sandro includes parsing in the scope. I would probably push the parsing responsibility to a collaborator. I can see that Sandro can succeed with his approach with a simple, non-nested JSON with three fields, but I wonder if his approach would be the same if it was a bigger structure with several nesting levels, optional sections etc.&lt;/li&gt;
&lt;/ol&gt;
</description><link>http://feelings-erased.blogspot.com/2018/09/sandro-mancusso-uncle-bob-comparative.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-1396726370621582034</guid><pubDate>Sun, 02 Jul 2017 20:07:00 +0000</pubDate><atom:updated>2017-07-02T22:07:40.272+02:00</atom:updated><title>What&#39;s happening with my book and future plans</title><description>&lt;p&gt;Hi, I haven&#39;t posted in a while, so a quick update:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I am currently focusing on my book, that&#39;s why the updates on this blog are extremely rare.&lt;/li&gt;
  &lt;li&gt;I have some nice topics to write blog posts about, but I&#39;m putting them on hold for a bit. The steady increase pace of my book&#39;s content (it&#39;s already over 250 pages A4!) should make it up for you.&lt;/li&gt;
  &lt;li&gt;Speaking about book&#39;s content, I recently finished an overhaul of part 1, which took me a long time and lots of effort.&lt;/li&gt;
  &lt;li&gt;I&#39;m currently fixing some bugs submitted on the book&#39;s github page for some portions of part 2&lt;/li&gt;
  &lt;li&gt;When I finish this, I plan on continuing part 2, review the value objects chapters and probably move TDD with mocks to part 3.&lt;/li&gt;
  &lt;li&gt;After that, I want to write something about hexagonal architecture (which will probably be part 4) and TDDing  on a level of a whole component, using mentioned hexagonal approach (maybe part 5?).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There is still a lot of work ahead of me, so thank you all for your support and I hope you like the new book content. I not, well, you can still contact me with your thoughts and opinions!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2017/07/whats-happening-with-my-book-and-future.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-7599814441140573083</guid><pubDate>Mon, 09 May 2016 21:36:00 +0000</pubDate><atom:updated>2016-05-09T23:36:40.541+02:00</atom:updated><title>New release of my book</title><description>&lt;p&gt;&lt;a href=&quot;https://github.com/grzesiek-galezowski/tdd-ebook/blob/0969b2e42021322acd701877aa9c388e6f0afb93/ReleaseNotes.md&quot;&gt;Release notes are on the books&#39; github page&lt;/a&gt;. Enjoy!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2016/05/new-release-of-my-book.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-8331841628179081062</guid><pubDate>Sat, 13 Feb 2016 20:35:00 +0000</pubDate><atom:updated>2016-02-15T09:24:18.195+01:00</atom:updated><title>Is test isolation always a good thing?</title><description>&lt;p&gt;TDD is not only about unit tests. Steve Freeman and Nat Pryce argue &lt;a href=&quot;http://www.growing-object-oriented-software.com/&quot;&gt;in their book&lt;/a&gt; that a TDD cycle is kickstarted using an end-to-end automated test. These tests exercise a system as a black box. This often implies difficulties and issues that well written unit tests don’t have. On of such fields of difficulty is test fixture management, especially fixture teardown.&lt;/p&gt;
&lt;p&gt;Gerard Meszaros in his book titled &lt;a href=&quot;http://xunitpatterns.com/&quot;&gt;XUnit test patterns&lt;/a&gt; provides an extensive discussion of different fixture management strategies and their implications. Using Meszaros’ terminology, what I have seen many end-to-end tests using is a combination of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://xunitpatterns.com/Shared%20Fixture.html#Immutable%20Shared%20Fixture&quot;&gt;Persistent shared immutable fixture&lt;/a&gt; - this is the data that’s shared by many tests - usually some initial environment setup and plumbing, uploading licenses and so on. The “immutable” part of the fixture name means that no test is allowed to modify any data that’s part of this fixture. The reason is that each test relies on this data being intact. If any test modifies the fixture, then other tests’ assumptions are broken and we cannot expect them to work reliably.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://xunitpatterns.com/Fresh%20Fixture.html&quot;&gt;Persistent fresh fixture&lt;/a&gt; - this is the data that’s needed for a single test. This may be, for example, adding a specific employee required by the test scenario to a database. As database is a persistent storage, this data must be cleaned up either at the end of the same test that created it or at the beginning of any new test (there are some ways to achieve that safely, but that’s a topic for another post). The cleanup is needed to avoid test interactions - many tests may add an employee with the same ID number, but with other data being different. Thus we need to prepare a clean bed for each test so that leftover data from previous tests doesn’t get in the way (by the way, there are some &lt;a href=&quot;http://xunitpatterns.com/Persistent%20Fixture%20Management.html&quot;&gt;other ways of dealing with test interactions than cleaning up&lt;/a&gt; - although they’re quite difficult to apply).&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://xunitpatterns.com/Fresh%20Fixture.html&quot;&gt;Transient fresh fixture&lt;/a&gt; - this part of data is created inside a test and removed without our intervention when the test finishes running, usually by garbage collector or other memory management mechanism. The simplest example of such fixture would be an integer variable defined in a test method - we don’t have to worry about it impacting the other tests, because its lifetime is automatically associated with the lifetime of a test.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After reading XUnit test patterns, my conclusion was obvious - life would be beautiful if we could only use transient fresh fixture. When writing unit tests for classes or small clusters of classes, this kind of fixture is the only one we ever need to use. Things change, on the other hand, when e.g. our tests require installation of the application and a database - in such situation, using only transient fixture would probably mean that each test should perform a fresh installation of an operating system. This would take ages, so we use the other fixture types as a compromise. We accept the problems they bring and accept the fact that they can introduce interactions between tests (and thus, instability) and trade these things for shorter test execution time.&lt;/p&gt;
&lt;p&gt;I met with an opinion that this is not actually bad. What’s more, the opinion states, this can be seen as an advantage, because when a single instance of an application is exercised by many different tests, it resembles closer the way the user exercises the system when it’s deployed and, by working longer with an existing instance of a system, it may uncover some defects that would otherwise not become visible.&lt;/p&gt;
&lt;p&gt;I have several issues with this point of view on fixture management. In order to explain why is that, let’s recap the differences between how user exercises a system and how automated end-to-end tests do it.&lt;/p&gt;
&lt;h2&gt;&lt;a id=&quot;What_are_the_differences_between_usage_by_automated_tests_and_by_user_16&quot;&gt;&lt;/a&gt;What are the differences between usage by automated tests and by user?&lt;/h2&gt;
&lt;p&gt;There are three pretty big differences that I can think of:&lt;/p&gt;
&lt;h3&gt;&lt;a id=&quot;An_automated_test_has_a_scope_ie_it_has_a_beginning_20&quot;&gt;&lt;/a&gt;An automated test has a scope, i.e. it has a &lt;em&gt;beginning&lt;/em&gt;&lt;/h3&gt;
&lt;p&gt;When defining a test, we usually define the context in which a test should be executed, a series of steps and an expected outcome. For example, we might say:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-gherkin&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;Given&lt;/span&gt; there are two employees: Ken and Tom //the context
&lt;span class=&quot;hljs-keyword&quot;&gt;When&lt;/span&gt; I choose to remove Ken&#39;s data         //step 1
&lt;span class=&quot;hljs-keyword&quot;&gt;And&lt;/span&gt; list all my employees                  //step 2
&lt;span class=&quot;hljs-keyword&quot;&gt;Then&lt;/span&gt; I should only see Tom&#39;s data          //expected outcome
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, the explicitly stated context is that we have two employees - if there is only one, executing the two steps would most probably create different results. Of course, there is also an implicit context that’s not written here, for example that the application is installed and turned on and probably that I’m logged into the application. The test relies on both kinds of context to be the same for every execution. In other words, in order to bring stable outcomes, a test &lt;em&gt;requires&lt;/em&gt; a context to be defined. Users usually work in the context they are currently given and are able to adapt to it. For example, I want to create an e-mail account with an address &lt;a href=&quot;mailto:%22buziaczek@mymail.com&quot;&gt;&amp;quot;buziaczek@mymail.com&lt;/a&gt;&amp;quot;, but this address already exists. No problem, I’ll just create &lt;a href=&quot;mailto:%22buziaczek-1984@mymail.com&quot;&gt;&amp;quot;buziaczek-1984@mymail.com&lt;/a&gt;&amp;quot; and I’m ready to go. Most of the time, an automated test doesn’t make such decisions (although we can do something to bypass such situations, e.g. generating a portion of the e-mail address randomly, but note that it’s still &lt;em&gt;not&lt;/em&gt; making a decision).&lt;/p&gt;
&lt;p&gt;Thus, although it may happen for a user to follow a strict sequence of steps in a strictly defined context, this is not what their work with the application is &lt;em&gt;about&lt;/em&gt;. If it was, we could probably automate these sequences in the software itself.&lt;/p&gt;
&lt;p&gt;Anyway, a demand for strictly defined context for each automated test means that this context would usually have to be cleaned after or before each test (Meszaros writes about other ways, like generating distinct test data for each test, but I didn’t see them in practice all that often). This is somehow contradictory to wanting to achieve testing “as the user would” by executing tests in partially the same context (i.e. on the same running or installed application instance). The contradiction for me is that we seem to value test isolation, except that we don’t.&lt;/p&gt;
&lt;h3&gt;&lt;a id=&quot;An_automated_test_has_a_scope_ie_it_has_an_end_37&quot;&gt;&lt;/a&gt;An automated test has a scope, i.e. it has an &lt;em&gt;end&lt;/em&gt;&lt;/h3&gt;
&lt;p&gt;A user uses a product in a continuous manner, usually taking many, many steps during each session with an application. On the other hand, when reading on good practices for automated testing, one can spot that such tutorials hardly ever advise writing long, automated scenarios. It is more common to see several test cases for several different behaviors or variants of a single behavior rather than a single test case exercising all of these conditions. So, it looks like we deliberately try to run away from testing the system the way a user would in automated tests. Why is that?&lt;/p&gt;
&lt;p&gt;This is for several reasons. One of them is that most of the time, a failed assertion ends an automated test, so the longer the test, the harder it is to get feedback from the later parts of that test, because there are more things that can fail along the way. Two other reasons that I’d like to talk about are: splitting work into manageable chunks and defect localization.&lt;/p&gt;
&lt;p&gt;Splitting into manageable chunks means that we prefer shorter scenarios to longer ones because it is easier to maintain and modify each scenario independently when it’s smaller. This is because building up context becomes increasingly harder to grasp, understand and manage. Users, on the other hand, don’t need to manage scenarios - they dynamically choose their goals and steps based on the current situation.&lt;/p&gt;
&lt;p&gt;Defect localization means that when a test fails, I need to search for the failure root cause only among what’s in the scope of this test. When a scope of a test is smaller, I have fewer places to search for such root cause. This is also one of the reasons why we set descriptive names for tests, i.e. we’d rather say “the user should be able to delete an employee” than “the user should be able to play with the system” - because in the first case, a failure points us closer to the root cause. The usual thing I do when I see an automated test failing is to try and run it in isolation (i.e. not as part of a suite) and in clean environment. This is because it gives me a better feedback on whether the failure is caused by something that’s in the scope. So, the broader the scope of a test, the lower defect localization.&lt;/p&gt;
&lt;p&gt;In his wonderful book, &lt;a href=&quot;http://www.amazon.com/Lean-Agile-Acceptance-Test-Driven-Development-Collaboration/dp/0321714083&quot;&gt;Lean-Agile Acceptance Test-Driven Development&lt;/a&gt;, Ken Pugh outlines three conditions we strive to achieve for automated tests:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A test should fail for a well-defined reason.&lt;/li&gt;
&lt;li&gt;No other test should fail for the same reason.&lt;/li&gt;
&lt;li&gt;A test should not fail for any other reason.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And, while Ken admits this is often very hard (or impossible) to achieve, this is the ideal we should be targeting. Managing a persistent fixture introduces more complexity and possible root causes of test failures, driving us away from these three conditions.&lt;/p&gt;
&lt;h3&gt;&lt;a id=&quot;An_automated_test_has_a_scope_ie_it_has_a_purpose_55&quot;&gt;&lt;/a&gt;An automated test has a scope, i.e. it has a &lt;em&gt;purpose&lt;/em&gt;&lt;/h3&gt;
&lt;p&gt;As I said above, a test should fail for a well-defined reason. This well-defined reason for failure is a &lt;em&gt;purpose&lt;/em&gt; of the test. In other words, every test failure should relate to its purpose. This purpose is usually conveyed in test name, for example “An added employee should appear on an employee report”. Note that very rarely do we see tests like “previous tests runs should not have led the application into an illegal or crashing state”. This is because the tests aren’t usually written to check whether an application crashes if we do some random things with it. Sharing parts of the fixture between tests doesn’t help them achieving their purpose.&lt;/p&gt;
&lt;p&gt;I also said that it is probably impossible to get rid of all the things that are beyond the purpose of a test but still can impact the outcome of the test. For example, if a test loads anything from a disk, it can fail because of (unlikely but possible) disk drivers failure. These things are outside the scope of a test, but still influence its result.&lt;/p&gt;
&lt;p&gt;The point is, the more things exist &lt;em&gt;outside&lt;/em&gt; the scope of an automated test that can affect its outcome, the more the test becomes incompetent at testing what’s &lt;em&gt;inside&lt;/em&gt; its scope. Do we want the tests to be incompetent in fulfilling their purpose? I hope not. Thus, my preference is to maximize the competency of a test by reducing to a minimum other things that can impact its outcome. This is how I believe I get the most value out of automated tests. This is in line with Meszaros’ write-up on &lt;a href=&quot;http://xunitpatterns.com/Goals%20of%20Test%20Automation.html&quot;&gt;the goals of test automation&lt;/a&gt;, where he stresses the ease of maintainability as one of such goals.&lt;/p&gt;
&lt;p&gt;Automated tests teardown is often very error-prone and adds a lot of instability to the test suite, thus making it less competent in doing the thing it written for. For some time, For test execution time-related reasons, I’m afraid we’ll have to live with sharing some parts of persistent fixtures, however, If I could get rid of the necessity of teardowns in tests without sacrificing their run time, I’d do so in a blink of an eye.&lt;/p&gt;
&lt;h2&gt;&lt;a id=&quot;Summary_65&quot;&gt;&lt;/a&gt;Summary&lt;/h2&gt;
&lt;p&gt;My opinion on test isolation is that the more the better. For me, saying that partial lack of isolation is better (because it would uncover some defects only a user otherwise could) is really taking the biggest disadvantage of automated black-box tests and pretending it’s an advantage. It is relying on undeliberate potential effect of this disadvantage. Creating a test approach targeted towards uncovering such defects (i.e. relying on deliberate effort to uncover them instead of hoping they will come up from other tests) would in my opinion give a better return of investment.&lt;/p&gt;

&lt;/body&gt;&lt;/html&gt;</description><link>http://feelings-erased.blogspot.com/2016/02/is-test-isolation-always-good-thing.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-2845300654688110124</guid><pubDate>Fri, 25 Sep 2015 07:13:00 +0000</pubDate><atom:updated>2015-09-25T09:13:39.552+02:00</atom:updated><title>Two new chapters on value obejcts</title><description>&lt;p&gt;Hi!&lt;p&gt;
&lt;p&gt;
It has been long since I last wrote about the progress of my book. Two chapters were added since, and both on value objects:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-value-objects&quot;&gt;Value objects&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-value-object-anatomy&quot;&gt;Value object anatomy&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Happy reading and, as always, I welcome any feedback!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2015/09/two-new-chapters-on-value-obejcts.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-1745121335744289256</guid><pubDate>Tue, 01 Sep 2015 04:25:00 +0000</pubDate><atom:updated>2015-09-01T06:25:17.661+02:00</atom:updated><title>I recorded a video: FizzBuzz To Chain of Responsibility to DSL using TDD in Java</title><description>&lt;p&gt;Sorry for bad narration - I did very minor preparation to record this video. Also sorry for saying &quot;dividable&quot; instead of divisible.&lt;/p&gt;

&lt;p&gt;This movie demonstrates implementation a variation of FizzBuzz kata without error checking, but with refactoring towards the Chain of Responsibility pattern. The first part is done using TDD and triangulation.&lt;/p&gt;

&lt;iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/9RJyI1Mu4wI&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;</description><link>http://feelings-erased.blogspot.com/2015/09/i-recorded-video-fizzbuzz-to-chain-of.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/9RJyI1Mu4wI/default.jpg" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-1617497849893170219</guid><pubDate>Fri, 12 Jun 2015 10:27:00 +0000</pubDate><atom:updated>2015-06-12T12:27:17.998+02:00</atom:updated><title>New chapter: Viewing object composition as a language</title><description>&lt;p&gt;Hi!&lt;p&gt;
&lt;p&gt;
&lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-object-composition-as-a-language&quot;&gt;New chapter on viewing object composition as a language was added&lt;/a&gt;. This chapter is about how the idea of having a system of composable objects leads to inventing a set of mini domain-specific languages.&lt;/p&gt;

&lt;p&gt;Happy reading and I really welcome any feedback!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2015/06/new-chapter-viewing-object-composition.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-443324520861136302</guid><pubDate>Sun, 30 Nov 2014 22:29:00 +0000</pubDate><atom:updated>2014-11-30T23:29:08.182+01:00</atom:updated><title>New Chapter: Protocols</title><description>&lt;p&gt;Hi!&lt;p&gt;
&lt;p&gt;
&lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-protocols&quot;&gt;New chapter on protocols was added&lt;/a&gt;. This chapter deals with the idea of creating a stable communication patterns between object and its collaborators. Understanding this idea is crucial for working effectively with mock objects.&lt;/p&gt;

&lt;p&gt;Happy reading!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2014/11/new-chapter-protocols.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-7052706362609515637</guid><pubDate>Sat, 29 Nov 2014 22:11:00 +0000</pubDate><atom:updated>2014-11-29T23:11:56.360+01:00</atom:updated><title>Three new chapters!</title><description>&lt;p&gt;Hi!&lt;/p&gt;

&lt;p&gt;Just to let you know - three new chapters were added since the last time I blogged:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-web-messages-and-protocols&quot;&gt;Web, messages and protocols&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-composing-a-web-of-objects&quot;&gt;Composing a web of objects&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-classes-vs-interfaces&quot;&gt;Interfaces&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Happy reading and I hope this makes up for long absence of posts here!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2014/11/three-new-chapters.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-1832609793090553147</guid><pubDate>Sun, 10 Aug 2014 12:45:00 +0000</pubDate><atom:updated>2014-08-10T14:49:50.573+02:00</atom:updated><title>Why do we need composability?</title><description>&lt;p&gt;Hi,&lt;/p&gt;

&lt;p&gt;I moved my book &lt;a href=&quot;https://leanpub.com/tdd-ebook&quot;&gt;to leanpub&lt;/a&gt; (as you may have guessed from the sidebar of this blog). The online version looks very good and is available for all, so I decided there is no point reproducing it on the blog.&lt;/p&gt;

&lt;p&gt;Instead, you can read the new chapter called &lt;a href=&quot;https://leanpub.com/tdd-ebook/read#leanpub-auto-why-do-we-need-composability&quot;&gt;Why do we need composability?&lt;/a&gt; online on leanpub and maybe decide to download the current state of the book (which is an always will be free).&lt;/p&gt;

&lt;p&gt;This chapter is a next step in explaining the object oriented design knowledge necessary to understand mock objects well.&lt;/p&gt;

&lt;p&gt;Have fun!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2014/08/why-do-we-need-composability.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-6806756497356038273</guid><pubDate>Fri, 16 May 2014 19:26:00 +0000</pubDate><atom:updated>2014-05-16T21:26:25.869+02:00</atom:updated><title>Road To Mock Objects, pt. 2: Telling, not asking</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;https://github.com/grzesiek-galezowski/tdd-ebook#readme&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;In this post, we&#39;ll get back to &lt;a href=&quot;http://feelings-erased.blogspot.com/2014/04/road-to-mock-objects-pt-1-on-objects.html&quot;&gt;Johnny and Benjamin&lt;/a&gt; as they introduce another change in the code they are working on. In the process, they discover the impact that return values and getters have on composability of objects.&lt;/p&gt;

&lt;h3&gt;Contractors&lt;/h3&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; G&#39;morning. Ready for another task?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Of course! What&#39;s next?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Remember the code we worked on yesterday? It contains a policy for regular employees of the company. But the company wants to start hiring contractors as well and needs to include a policy for them in the application.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; So this is what we will be doing today?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; That&#39;s right. The policy is going to be different for contractors. While, just as regular employees, they will be receiving raises and bonuses, the rules will be different. I made a small table to allow comparing what we have for regular employees and what we want to add for contractors:&lt;/p&gt;

&lt;table&gt;
 &lt;tr&gt;
  &lt;th&gt;&lt;/th&gt;
  &lt;th&gt;Raise&lt;/th&gt;
  &lt;th&gt;Bonus&lt;/th&gt;
 &lt;/tr&gt;

 &lt;tr&gt;
  &lt;th&gt;Regular Employee&lt;/th&gt;
  &lt;td&gt;+10% of current salary if not reached maximum on a given pay grade&lt;/td&gt;
  &lt;td&gt;+200% of current salary one time after five years&lt;/td&gt;
 &lt;/tr&gt;

 &lt;tr&gt;
  &lt;th&gt;Contractor&lt;/th&gt;
  &lt;td&gt;+5% of average salary calculated for last 3 years of service (or all previous years of service if they have worked for less than 3 years)&lt;/td&gt;
  &lt;td&gt;+10% of current salary when a contractor receives score more than 100 for the previous year&lt;/td&gt;
 &lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;So while the workflow is going to be the same for both a regular employee and a contractor:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Load from repository&lt;/li&gt;
  &lt;li&gt;Evaluate raise&lt;/li&gt;
  &lt;li&gt;Evaluate bonus&lt;/li&gt;
  &lt;li&gt;Save&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;the implementation of some of the steps will be different for each type of employee.&lt;/p&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Correct me if I am wrong, but these &quot;load&quot; and &quot;save&quot; steps do not look like they belong with the remaining two - they describe something technical, while the other steps describe something strictly related to how the company operates...&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Good catch, however, this is something we&#39;ll deal with later. Remember the scout rule - just don&#39;t make it worse. Still, we&#39;re going to fix some of the design flaws today.&lt;/p&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Aww... I&#39;d just fix all of it right away.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Ha ha, patience, Luke. For now, let&#39;s look at the code we have now before we plan further steps.&lt;/p&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Let me just open my IDE... OK, here it is:&lt;/p&gt;

&lt;pre&gt;public class CompanyPolicies 
{
  readonly Repository _repository; 

  public CompanyPolicies(Repository repository)
  {
    _repository = repository;
  }
  
  public void ApplyYearlyIncentivePlan()
  {
    var employees = _repository.CurrentEmployees();

    foreach(var employee in employees)
    {
      var payGrade = employee.GetPayGrade();

      //evaluate raise
      if(employee.GetSalary() &amp;lt; payGrade.Maximum)
      {
        var newSalary 
          = employee.GetSalary() 
          + employee.GetSalary() 
          * 0.1;
        employee.SetSalary(newSalary);
      }
      
      //evaluate one-time bonus
      if(employee.GetYearsOfService() == 5)
      {
        var oneTimeBonus = employee.GetSalary() * 2;
        employee.SetBonusForYear(2014, oneTimeBonus);
      }
      
      employee.Save();
    }
  }
}&lt;/pre&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Look, Johnny, the class in fact contains all the four steps you mentioned, but they are not named explicitly - instead, their internal implementation for regular employees is just inserted in here. How are we supposed to add the variation of the employee type?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Time to consider our options. We have few of them. Well?&lt;/p&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; For now, I can see two. The first one would be to create another class similar to &lt;code&gt;CompanyPolicies&lt;/code&gt;, called something like &lt;code&gt;CompanyPoliciesForContractors&lt;/code&gt; and implement the new logic there. This would let us leave the original class as is, but we would have to change the places that use &lt;code&gt;CompanyPolicies&lt;/code&gt; to use both classes and choose which one to use somehow. Also, we would have to add a separate method to repository for retrieving the contractors.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; In addition, we would miss our chance to communicate through the code that the sequence of steps is intentionally similar in both cases. Others who read this code in the future will see that the implementation for regular employees follows the steps: load, evaluate raise, evaluate bonus, save. When they look at the implementation for contractors, they will see the same order of steps, but they will be unable to tell whether the similarity is intentional, or is it there by pure accident.&lt;/p&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; So our second option is to put an &lt;code&gt;if&lt;/code&gt; statement into the differing steps inside the &lt;code&gt;CompanyPolicies&lt;/code&gt; class, to distinguish between regular employees and contractors. The &lt;code&gt;Employee&lt;/code&gt; class would have an &lt;code&gt;isContractor()&lt;/code&gt; method and depending on what it would return, we would either execute the logic for regular employees or for contractors. Assuming that the current structure of the code looks like this:&lt;/p&gt;

&lt;pre&gt;
foreach(var employee in employees)
{
  //evaluate raise
  ...
      
  //evaluate one-time bonus
  ...
  
  //save employee
}
&lt;/pre&gt;

&lt;p&gt;the new structure would look like this:&lt;/p&gt;

&lt;pre&gt;foreach(var employee in employees)
{
  if(employee.IsContractor())
  {
    //evaluate raise for contractor
    ...
  }
  else
  {
    //evaluate raise for regular
    ...
  }

  if(employee.IsContractor())
  {
    //evaluate one-time bonus for contractor
    ...
  }
  else
  {
    //evaluate one-time bonus for regular
    ...
  }
  
  //save employee
  ...
}
&lt;/pre&gt;

&lt;p&gt;this way we would show that the steps are the same, but the implementation is different. Also, this would mostly require us to add code and not move the existing code around.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; The downside is that we would make the class even uglier than it was when we started. So despite initial easiness, we&#39;ll be doing a huge disservice to future maintainers. We have at least one another option. What would that be?&lt;/p&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Let&#39;s see... we could move all the details concerning the implementation of the steps from &lt;code&gt;CompanyPolicies&lt;/code&gt; class into the &lt;code&gt;Employee&lt;/code&gt; class itself, leaving only the names and the order of steps in &lt;code&gt;CompanyPolicies&lt;/code&gt;:

&lt;pre&gt;foreach(var employee in employees)
{
  employee.EvaluateRaise();
  employee.EvaluateOneTimeBonus();
  employee.Save();
}
&lt;/pre&gt;

&lt;p&gt;Then, we could change the &lt;code&gt;Employee&lt;/code&gt; into an interface, so that it could be either a &lt;code&gt;RegularEmployee&lt;/code&gt; or &lt;code&gt;ContractorEmployee&lt;/code&gt; - both classes would have different implementations of the steps, but the &lt;code&gt;CompanyPolicies&lt;/code&gt; would not notice, since it would not be coupled to the implementation of the steps anymore - just the names and the order.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; This solution would have one downside - we would need to significantly change the current code, but you know what? I&#39;m willing to do it, especially that I was told today that the logic is covered by some tests which we can run to see if a regression was introduced.&lt;/p&gt;

 &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Cool, what do we start with?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; The first thing that is between us and our goal are these getters on the &lt;code&gt;Employee&lt;/code&gt; class:&lt;/p&gt;

&lt;pre&gt;GetSalary();
GetGrade();
GetYearsOfService();
&lt;/pre&gt;

&lt;p&gt;They just expose too much information specific to the regular employees. It would be impossible to use different implementations when these are around. These setters don&#39;t help much:&lt;/p&gt;
&lt;pre&gt;
SetSalary(newSalary)
SetBonusForYear(year, amount);
&lt;/pre&gt;

&lt;p&gt;While these are not as bad, we&#39;d better give ourselves more flexibility. Thus, let&#39;s hide all of this behind more abstract methods that hide what actually happens, but reveal our intention.&lt;/p&gt;

&lt;p&gt;First, take a look at this code:&lt;/p&gt;

&lt;pre&gt;//evaluate raise
if(employee.GetSalary() &amp;lt; payGrade.Maximum)
{
  var newSalary 
    = employee.GetSalary() 
    + employee.GetSalary() 
    * 0.1;
  employee.SetSalary(newSalary);
}
&lt;/pre&gt;

&lt;p&gt;Each time you see a block of code separated from the rest with blank lines and starting with a comment, you see something screaming &quot;I want to be a separate method that contains this code and has a name after the comment!&quot;. Let&#39;s grant this wish and make it a separate method on the &lt;code&gt;Employee&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Ok, wait a minute... here:&lt;/p&gt;

&lt;pre&gt;employee.EvaluateRaise();&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Great! Now, we&#39;ve got another example of this species here:&lt;/p&gt;

&lt;pre&gt;//evaluate one-time bonus
if(employee.GetYearsOfService() == 5)
{
  var oneTimeBonus = employee.GetSalary() * 2;
  employee.SetBonusForYear(2014, oneTimeBonus);
}&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; This one should be even easier... Ok, take a look:&lt;/p&gt;

&lt;pre&gt;employee.EvaluateOneTimeBonus();&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Almost good. I&#39;d only leave out the information that the bonus is one-time from the name.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Why? Don&#39;t we want to include what happens in the method name?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Actually, no. What we want to include is our intention. The bonus being one-time is something specific to the regular employees and we want to abstract away the details about this or that kind of employee, so that we can plug in different implementations without making the method name lie. The names should reflect that we want to evaluate a bonus, whatever that means for a particular type of employee. Thus, let&#39;s make it:&lt;/p&gt;

&lt;pre&gt;employee.EvaluateBonus();&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Ok, I get it. No problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Now let&#39;s take a look at the full code of the &lt;code&gt;EvaluateIncentivePlan&lt;/code&gt; method to see whether it is still coupled to details specific to regular employees. Here&#39;s the code:&lt;/p&gt;

&lt;pre&gt;public void ApplyYearlyIncentivePlan()
{
  var employees = _repository.CurrentEmployees();

  foreach(var employee in employees)
  {
    employee.EvaluateRaise();
    employee.EvaluateBonus();
    employee.Save();
  }
}
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; It seems that there is no coupling to the details about regular employees anymore. Thus, we can safely make the repository return a combination of regulars and contractors without this code noticing anything. Now I think I understand what you were trying to achieve. If we make interactions between objects happen on a more abstract level, then we can put in different implementations with less effort.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; True. Can you see another thing related to the lack of return values on all of employee&#39;s methods in the current implementation?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Actually, no. Does it matter?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Well, if &lt;code&gt;Employee&lt;/code&gt; methods had return values and this code depended on them, all subclasses of &lt;code&gt;Employee&lt;/code&gt; would be forced to supply return values as well and these return values would need to match the expectations of the code that calls these methods, whatever these expectations were. This would make introducing other kinds of employees harder. But now that there are no return values, we can, for example:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;introduce a &lt;code&gt;TemporaryEmployee&lt;/code&gt; that has no raises, by leaving its &lt;code&gt;EvaluateRaise()&lt;/code&gt; method empty, and the code that uses employees will not notice.&lt;/li&gt;
  &lt;li&gt;introduce a &lt;code&gt;ProbationEmployee&lt;/code&gt; that has no bonus policy, by leaving its &lt;code&gt;EvaluateBonus()&lt;/code&gt; method empty, and the code that uses employees will not notice.&lt;/li&gt;
  &lt;li&gt;introduce an &lt;code&gt;InMemoryEmployee&lt;/code&gt; that has empty &lt;code&gt;Save()&lt;/code&gt; method, and the code that uses employees will not notice.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you see, by asking the objects less, and telling it more, we get greater flexibility to create alternative implementations and the composability, which we talked about yesterday, increases!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; I see... So telling objects what to do instead of asking them for their data makes the interactions between objects more abstract, and so, more stable, increasing composability of interacting objects. This is a valuable lesson - it is the first time I hear this and it seems a pretty powerful concept.&lt;/p&gt;

  &lt;h3&gt;A Quick Retrospective&lt;/h3&gt;

&lt;p&gt;In this post, Benjamin learned that the composability of objects (not to mention clarity) is reinforced when interactions between them are: abstract, logical and stable. Also, he discovered, with Johnny&#39;s help, that it is further strengthened by following a design style where objects are told what to do instead of asked to give away information to somebody who the makes the decision on their behalf. This is because if an API of an abstraction is built around answering to specific questions, the clients of the abstraction tend to ask it a lot of questions an are coupled to both those questions and some aspects of the answers (i.e. what it in the return values). This makes creating another implementation of abstraction harder, because each new implementation of the abstraction needs to not only provide answers to all those questions, but the answers are constrained to what the client expects. When abstraction is merely told what its client wants it to achieve, the clients is decoupled from most of the details of how this happens. This makes introducing new implementations of abstraction easier - it often even lets us define implementations with all methods empty without the client noticing at all.&lt;/p&gt;

&lt;p&gt;These are all important conclusions that will lead us towards TDD with mock objects.&lt;/p&gt;

&lt;p&gt;Time to leave Johnny and Benjamin for now. In the next posts, I&#39;m going to reiterate on their discoveries and put them in a broader context.&lt;/p&gt;
</description><link>http://feelings-erased.blogspot.com/2014/05/road-to-mock-objects-pt-2-telling-not.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-6990602765457285151</guid><pubDate>Sun, 13 Apr 2014 11:40:00 +0000</pubDate><atom:updated>2014-04-13T13:40:52.828+02:00</atom:updated><title>Road To Mock Objects, pt. 1: On Objects Composability</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;https://github.com/grzesiek-galezowski/tdd-ebook#readme&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;

  &lt;p&gt;In this post, I will try to outline briefly why objects&#39; composability is a goal worth achieving and how it can be achieved. I am going to start with an example of unmaintainable code and will gradually fix its flaws in the next posts. For now, we are going to fix just one of the flaws, so the code we will end up will not be perfect by any means, still, it will be better by one quality.&lt;/p&gt;

&lt;p&gt;In the coming posts, we will learn more valuable lessons resulting from changing this little piece of code and slowly arrive at justification for using mock objects.&lt;/p&gt;

  &lt;h1 id=&quot;u1b304157-2049-4846-92dc-f3500e72432e&quot;&gt;Another task for Johnny and Benjamin&lt;/h1&gt;

  &lt;p&gt;Remember Johnny and Benjamin? Looks like they managed their previous task and are up to something else. Let us listen to their conversation as they are working on another project...&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; So, what&#39;s this assignment about?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Actually, it&#39;s nothing exciting - we&#39;ll have to add two features to a legacy application that&#39;s not prepared for the changes.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; What is the code for?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; It is a&amp;nbsp;C#&amp;nbsp;class that implements company policies. As the company has just started using this automated system and it was started recently, there is only one policy implemented: yearly incentive plan. Many corporations have what they call incentive plans. These plans are used to promote good behaviors and exceeding expectations by employees of a company.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; You mean, the project has just started and is already in a bad shape?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Yep. The guys writing it wanted to &quot;keep it simple&quot;, whatever that means, and now it looks pretty bad.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; I see...&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; By the way, do you like riddles?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Always!&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; So here&#39;s one: how do you call a development phase when you ensure high code quality?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; ... ... No clue... So what is it called?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; It&#39;s called &quot;now&quot;.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Oh!&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Getting back to the topic, here&#39;s the company incentive plan.&lt;/p&gt;

  &lt;p&gt;Every employee has a pay grade. An employee can be promoted to a higher pay grade, but the mechanics of how that works is something we will not need to deal with.&lt;/p&gt;

  &lt;p&gt;Normally, every year, everyone gets a raise by 10%. But to encourage behaviors that give an employee a higher pay grade, such employee cannot get raises indefinitely on a given pay grade. Each grade has its associated maximum pay. If this amount of money is reached, an employee does not get a raise anymore until they reach a higher pay grade.&lt;/p&gt;

  &lt;p&gt;Additionally, every employee on their 5th anniversary of working for the company, gets a special, one-time bonus which is twice their current payment.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Looks like the source code repository just finished synchronizing. Let&#39;s take a bite at the code!&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Sure, here you go:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp;&quot;&gt;public class CompanyPolicies : IDisposable
{
  readonly SqlRepository _repository
    = new SqlRepository();
  
  public void ApplyYearlyIncentivePlan()
  {
    var employees = _repository.CurrentEmployees();

    foreach(var employee in employees)
    {
      var payGrade = employee.GetPayGrade();
      //evaluate raise
      if(employee.GetSalary() &amp;lt; payGrade.Maximum)
      {
        var newSalary 
          = employee.GetSalary() 
          + employee.GetSalary() 
          * 0.1;
        employee.SetSalary(newSalary);
      }
      
      //evaluate one-time bonus
      if(employee.GetYearseOfService() == 5)
      {
        var oneTimeBonus = employee.GetSalary() * 2;
        employee.SetBonusForYear(2014, oneTimeBonus);
      }
      
      employee.Save();
    }
  }
  
  public void Dispose()
  {
    _repository.Dispose();
  }
}&lt;/pre&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Wow, there is a lot of literal constants all around and functional decomposition is barely done!&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Yeah. We won&#39;t be fixing all of that today. Still, we will follow the scout rule and &quot;leave the campground cleaner than we found it&quot;.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; What&#39;s our assignment?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; First of all, we need to provide our users a choice between an SQL database and a NoSQL one. To achieve our goal, we need to be somehow able to make the &lt;code&gt;CompanyPolicies&lt;/code&gt; class database type-agnostic. For now, as you can see, the implementation is coupled to the specific &lt;code&gt;SqlRepository&lt;/code&gt;, because it creates a specific instance itself:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp;&quot;&gt;public class CompanyPolicies : IDisposable
{
  readonly SqlRepository _repository
    = new SqlRepository();
&lt;/pre&gt;

  &lt;p&gt;Now, we need to evaluate the options we have to pick the best one. What options do you see, Benjamin?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Well, we could certainly extract an interface from &lt;code&gt;SqlRepository&lt;/code&gt; and introduce an if statement to the constructor like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp;&quot;&gt;public class CompanyPolicies : IDisposable
{
  readonly Repository _repository;

  public CompanyPolicies()
  {
    if(...)
    {
      _repository = new SqlRepository();
    }
    else
    {
      _repository = new NoSqlRepository();
    }
  }
&lt;/pre&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; True, but this option has few deficiencies. First of all, remember we&#39;re trying to follow the scout rule and by using this option we introduce more complexity to the CommonPolicies class. Also, let&#39;s say tommorow someone writes another class for, say, reporting and this class will also need to access the repository - they will need to make the same decision on repositories in their code as we do in ours. This effectively means duplicating code. Thus, I&#39;d rather evaluate further options and check if we can come up with something better. What&#39;s our next option?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Another option would be to change the SqlRepository itself to be just a wrapper around the actual database access, like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp;&quot;&gt;public class SqlRepository : IDisposable
{
  readonly Repository _repository;

  public SqlRepository()
  {
    if(...)
    {
      _repository = new RealSqlRepository();
    }
    else
    {
      _repository = new RealNoSqlRepository();
    }
  }

  IList&amp;lt;Employee&amp;gt; CurrentEmployees()
  {
    return _repository.CurrentEmployees();
  }
&lt;/pre&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Sure, this is an approach that could work and would be worth considering for very serious legacy code, as it does not force us to change the &lt;code&gt;CompanyPolicies&lt;/code&gt; class at all. However, there are some issues with it. First of all, the &lt;code&gt;SqlRepository&lt;/code&gt; name would be misleading. Second, look at the &lt;code&gt;CurrentEmployees()&lt;/code&gt; method - all it does is delegating a call to the implementation chosen in the constructor. With every new method required of the repository, we&#39;ll need to add new delegating methods. In reality, it isn&#39;t such a big deal, but maybe we can do better than that?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Let me think, let me think... I evaluated the option where &lt;code&gt;CompanyPolicies&lt;/code&gt; class makes the choice between repositories. I also evaluated the option where we hack the &lt;code&gt;SqlRepository&lt;/code&gt; to makes this choice. The last option I can think of is leaving this choice to another, &quot;3rd party&quot; code, that would choose the repository to use and pass it to the &lt;code&gt;CompanyPolicies&lt;/code&gt; via constructor, like this:&lt;/p&gt;

  &lt;pre class=&quot;brush: csharp;&quot;&gt;public class CompanyPolicies : IDisposable
{
  private readonly Repository _repository;

  public CompanyPolicies(Repository repository)
  {
    _repository = repository;
  }
 &lt;/pre&gt;

&lt;p&gt;This way, the &lt;code&gt;CompanyPolicies&lt;/code&gt; won&#39;t know what exactly is passed to it via constructor and we can pass whatever we like - either an SQL repository or a NoSQL one!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Great! This is the option we&#39;re looking for! For now, just believe me that this approach will lead us to many good things - you&#39;ll see why later.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; OK, so let me just pull the &lt;code&gt;SqlRepository&lt;/code&gt; instance outside the &lt;code&gt;CompanyPolicies&lt;/code&gt; class and make it an implementation of &lt;code&gt;Repository&lt;/code&gt; interface, then create a constructor and pass the real instance through it...&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Sure, I&#39;ll go get some coffee.&lt;/p&gt;

&lt;p&gt;&lt;emph&gt;... 10 minutes later&lt;/emph&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Ha ha! Look at this! I am SUPREME!&lt;/p&gt;

  &lt;pre class=&quot;brush: csharp;&quot;&gt;public class CompanyPolicies : IDisposable
{
  //_repository is now an interface
  readonly Repository _repository; 

  // repository is passed from outside.
  // We don&#39;t know what exact implementation it is.
  public CompanyPolicies(Repository repository)
  {
    _repository = repository;
  }
  
  public void ApplyYearlyIncentivePlan()
  {
    //... body of the method. Unchanged.
  }
  
  public void Dispose()
  {
    _repository.Dispose();
  }
}&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Hey, hey, hold your horses! There is one thing wrong with this code.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Huh? I thought this is what we were aiming at.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Yes, with the exception of the &lt;code&gt;Dispose()&lt;/code&gt; method. Look closely at the &lt;code&gt;CompanyPolicies&lt;/code&gt; class. it is changed so that it is not responsible for creating a repository for itself, but it still disposes of it. This is wrong because &lt;code&gt;CompanyPolicies&lt;/code&gt; instance does not have any right to assume it is the only object that is using the repository. If so, then it cannot determine the moment when the repository becomes unnecessary and can be safely disposed of.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Ok, I get the theory, but why is this bad in practice? Can you give me an example?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Sure, let me sketch a quick example. As soon as you have two instances of &lt;code&gt;CompanyPolicies&lt;/code&gt; class, both sharing the same instance of &lt;code&gt;Repository&lt;/code&gt;, you&#39;re cooked. This is because one instance of &lt;code&gt;CompanyPolicies&lt;/code&gt; may dispose of the repository while the other one may still want to use it.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; So who is going to dispose of the repository?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; The same part of the code that creates it, for example the &lt;code&gt;Main&lt;/code&gt; method. Let me show you an example of how this may look like:&lt;/code&gt;


&lt;pre class=&quot;brush: csharp;&quot;&gt;
public static void Main(string[] args)
{
  using(var repo = new SqlRepository())
  {
    var policies = new CompanyPolicies(repo);

    //use policies for anything you like
  }
}
&lt;/pre&gt;

&lt;p&gt;This way the repository is created at the start of the program and disposed of at the end. Thanks to this, the &lt;code&gt;CompanyPolicies&lt;/code&gt; has no disposable fields and it itself does not have to be disposable - we can just delete the &lt;code&gt;Dispose()&lt;/code&gt; method:&lt;/p&gt;

&lt;pre class=&quot;brush: csharp;&quot;&gt;//not implementing IDisposable anymore:
public class CompanyPolicies 
{
  //_repository is now an interface
  readonly Repository _repository; 

  //New constructor
  public CompanyPolicies(Repository repository)
  {
    _repository = repository;
  }
  
  public void ApplyYearlyIncentivePlan()
  {
    //... body of the method. No changes
  }

  //no Dispose() method anymore
}&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Cool. So, what now? Seems we have the &lt;code&gt;CompanyPolicies&lt;/code&gt; class depending on repository abstraction instead of an actual implementation, like SQL repository. My guess is that we will be able to make another class implementing the interface for NoSQL data access and just pass it through the constructor instead of the original one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Yes. For example, look at &lt;code&gt;CompanyPolicies&lt;/code&gt; component. We can compose it with a repository like this:&lt;/p&gt;

&lt;pre class=&quot;brush: csharp;&quot;&gt;var policies 
  = new CompanyPolicies(new SqlRepository());&lt;/pre&gt;

&lt;p&gt;or like this:&lt;/p&gt;

&lt;pre class=&quot;brush: csharp;&quot;&gt;var policies 
  = new CompanyPolicies(new NoSqlRepository());&lt;/pre&gt;

&lt;p&gt;without changing the code of &lt;code&gt;CompanyPolicies&lt;/code&gt;. This means that &lt;code&gt;CompanyPolicies&lt;/code&gt; does not need to know what &lt;code&gt;Repository&lt;/code&gt; exactly it is composed with, as long as this &lt;code&gt;Repository&lt;/code&gt; follows the required interface and meets expectations of &lt;code&gt;CompanyPolicies&lt;/code&gt; (e.g. does not throw exceptions when it is not supposed to do so). An implementation of &lt;code&gt;Repository&lt;/code&gt; may be itself a very complex and composed of another set of classes, for example something like this:&lt;/p&gt;

&lt;pre class=&quot;brush: csharp;&quot;&gt;new SqlRepository(
  new ConnectionString(&quot;...&quot;), 
  new AccessPrivileges(
    new Role(&quot;Admin&quot;), 
    new Role(&quot;Auditor&quot;)),
  new InMemoryCache());&lt;/pre&gt;

&lt;p&gt;but the &lt;code&gt;CompanyPolicies&lt;/code&gt; neither knows or cares about this, as long as it can use our new &lt;code&gt;Repository&lt;/code&gt; implementation just like other repositories.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; I see... So, getting back to our task, shall we proceed with making a NoSQL implementation of the &lt;code&gt;Repository&lt;/code&gt; interface?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; First, show me the interface that you extracted while I was looking for the coffee.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; Here: &lt;/p&gt;
  
&lt;pre class=&quot;brush: csharp;&quot;&gt;
public interface Repository
{
  IList&amp;lt;Employee&amp;gt; CurrentEmployees();
}
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Ok, so what we need is to create just another implementation and pass it through the constructor depending on what data source is chosen and we&#39;re finished with this part of the task.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benjamin:&lt;/strong&gt; You mean there&#39;s more? &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Johnny:&lt;/strong&gt; Yeah, but that&#39;s something for tomorrow. I&#39;m exhausted today.&lt;/p&gt;


  &lt;h1&gt;Quick Retrospective&lt;/h1&gt;

&lt;p&gt;In this post, Benjamin learned to appreciate the composability of objects, i.e. the ability to compose object with other objects into more complex structures with more complex behaviors without changing the implementation of the object&#39;s class. This means that potentially, a composable object might trigger different behaviors depending on what it is composed with. We&#39;ll talk more about this property in the coming posts.&lt;/p&gt;

&lt;p&gt;As I said, the code Johnny and Benjamin worked on in this posts still has some serious flaws. For now, our characters did not encounter a desperate need to address those flaws yet, but this is going to change in the next posts.&lt;/p&gt;

&lt;p&gt;Also, after we part again with Johnny and Benjamin, we are going to reiterate the ideas they stumble upon in a more disciplined manner.&lt;/p&gt;


</description><link>http://feelings-erased.blogspot.com/2014/04/road-to-mock-objects-pt-1-on-objects.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-8559323667823415796</guid><pubDate>Sun, 05 Jan 2014 19:34:00 +0000</pubDate><atom:updated>2014-03-14T07:12:48.071+01:00</atom:updated><title>Mocks &quot;break encapsulation&quot;? Here&#39;s why I disagree...</title><description>&lt;p&gt;&lt;strong&gt;note that when I say &quot;statement&quot; in this blog post, I mean &quot;unit test&quot;.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For some time, I am witnessing discussions whether using mocks is something that &quot;breaks encapsulation&quot; and thus should be used sparingly. The time has come for me to voice my opinion.&lt;/p&gt;

&lt;h3&gt;Is &quot;breaking encapsulation&quot; even the right charge?&lt;/h3&gt;

&lt;p&gt;First of all, we must decrypt what &quot;breaking encapsulation&quot; means. It&#39;s not so simple actually, for two reasons.&lt;/p&gt;

&lt;p&gt;The first reason is that encapsulation is &lt;a href=&quot;http://stackoverflow.com/questions/13913174/encapsulation-vs-information-hiding&quot;&gt;understood differently by different people&lt;/a&gt; and is sometimes used synonymously with information hiding and sometimes a distinction is made between the two.&lt;/p&gt;

&lt;p&gt;If we decide to simplify things and treat encapsulation as &quot;information hiding&quot;, it is still unclear what it means to &quot;break&quot; it. Does it mean to &quot;reveal information&quot;? In this case, almost any object breaks encapsulation, because any object reveals &lt;emph&gt;some&lt;/emph&gt; information. In other words, there&#39;s not such thing as &quot;full encapsulation&quot;, because if everything was hidden, objects would not be able to communicate at all.&lt;/p&gt;

&lt;p&gt;So, what does it mean to &quot;break encapsulation&quot; in case of charges made against mocks?&lt;/p&gt;

&lt;h3&gt;What is the actual charge?&lt;/h3&gt;

&lt;p&gt;The thing many people have problem with is that unit-level specification makes statements on how an object uses (or more precisely, communicates with) its collaborators. For example, let&#39;s assume that I have a class that sends a packet through a connection and write the following unit-level statement:&lt;/p&gt;

&lt;pre&gt;[Test] public void
ShouldOpenConnectionThenSendAndThenCloseItWhenAskedToSendPacket()
{
  //GIVEN
  var connection = Substitute.For&amp;lt;Connection&amp;gt;();
  var sending = new Sending(connection);
  var packet = Any.Instance&amp;lt;Packet&amp;gt;();

  //WHEN
  sending.PerformFor(packet);

  //THEN
  Received.InOrder(() =&amp;gt;
  {
    connection.Open();
    connection.Send(packet);
    connection.Close();
  });
}&lt;/pre&gt;

&lt;p&gt;Note that this statement is coupled not only to the public methods of a class, but also to the way it uses objects of another class. The usual charge made against such statements is based on the following deduction chain:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;How an object uses its collaborators is not part of the object&#39;s public interface, hence it&#39;s an implementation detail&lt;/li&gt;
  &lt;li&gt;Mocks are all about how an object uses its collaborators&lt;/li&gt;
  &lt;li&gt;So it seems that statements using mocks are coupled to the implementation details of specified class&lt;/li&gt;
  &lt;li&gt;If we change the class so that it uses different collaborators or uses them differently, it may still do its job from the perspective of the clients of those objects (who just call the methods and expect return values). But, the statements will be failing in such case, because they&#39;re coupled to how object uses its collaborators.&lt;/li&gt;
  &lt;li&gt;The statements using mocks are brittle&lt;/li&gt;
  &lt;li&gt;Mocks should be avoided&lt;/li&gt;
  &lt;li&gt;Well... unless they&#39;re necessary to get high code coverage in places where just invoking methods and checking results is not enough&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the next section, I&#39;ll try to point why I think this kind of thinking is flawed.&lt;/p&gt;

&lt;h3&gt;Dependency Injection changes the game&lt;/h3&gt;

&lt;p&gt;The first point of this deduction chain we just talked about tells that it&#39;s object&#39;s private business who and how it calls to achieve this goal.&lt;/p&gt;

&lt;p&gt;This may even be true for an object that is instantiated like this:&lt;/p&gt;

&lt;pre&gt;var sending = new Sending();&lt;/pre&gt;

&lt;p&gt;But is utterly false when the object is instantiates like this:&lt;/p&gt;

&lt;pre&gt;Connection c = ...; //get object that implements Connection interface
var sending = new Sending(connection);&lt;/pre&gt;

&lt;p&gt;What is changed, you may ask - it&#39;s just adding a constructor parameter! Well, no it&#39;s not just this. The point is, the &lt;code&gt;Sending&lt;/code&gt; class now can have its dependency injected. This is very important, because the whole point of dependency injection is that the object is not the owner of its dependencies. Thus, such object effectively says: &quot;Listen up, my client, it&#39;s your problem what you give me, as long as I am able to use it&quot;. In other words, each client of the &lt;code&gt;Sending&lt;/code&gt; class can have their own class implementing the &lt;code&gt;Connection&lt;/code&gt; interface and each new user of the class can write their own implementation if they wish so.&lt;/p&gt;

&lt;p&gt;So now the real question kicks in:&lt;/p&gt;

&lt;div style=&quot;border: solid thin black; padding: 1em;&quot;&gt;
How can anyone provide a custom implementation to work with a class without knowing how the custom implementation will be used?
&lt;/div&gt;

&lt;p&gt;Remember, you can&#39;t just implement all methods of an &lt;code&gt;Connection&lt;/code&gt; interface anyway you want. By doing so, you have a nice chance to violate the Liskov Substitution Principle. Thus, the custom implementation of &lt;code&gt;Connection&lt;/code&gt; a client provides must not only implement the interface, it must also adhere to a certain protocol required by the &lt;code&gt;Sending&lt;/code&gt; class that will be using it.&lt;/p&gt;

&lt;p&gt;This leads us to one conclusion: if a custom implementation of &lt;code&gt;Connection&lt;/code&gt; must be coded with a knowledge of the protocol between &lt;code&gt;Sending&lt;/code&gt; and &lt;code&gt;Connection&lt;/code&gt;, this protocol is not a private business of &lt;code&gt;Sending&lt;/code&gt; class. While it may not be part of the public API, it&#39;s still part of the public contract.&lt;/p&gt;

&lt;h3&gt;Other examples&lt;/h3&gt;

&lt;p&gt;There are many examples out there that what I just wrote is true. For example, let&#39;s look at &lt;a href=&quot;http://docs.oracle.com/javaee/6/tutorial/doc/bnafi.html&quot;&gt;JEE Servlet lifecycle&lt;/a&gt; documentation and see what we can read there:&lt;/p&gt;

&lt;blockquote cite=&quot;http://docs.oracle.com/javaee/6/tutorial/doc/bnafi.html&quot; style=&quot;background-color: #f6eeb6; padding: 1em;&quot;&gt;
&lt;p&gt;The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If an instance of the servlet does not exist, the web container&lt;/li&gt;
&lt;li&gt;Loads the servlet class.&lt;/li&gt;
&lt;li&gt;Creates an instance of the servlet class.&lt;/li&gt;
&lt;li&gt;Initializes the servlet instance by calling the &lt;strong&gt;init&lt;/strong&gt; method. Initialization is covered in Creating and Initializing a Servlet.&lt;/li&gt;
&lt;li&gt;Invokes the &lt;strong&gt;service&lt;/strong&gt; method, passing request and response objects. Service methods are discussed in Writing Service Methods.&lt;/li&gt;
&lt;li&gt;If it needs to remove the servlet, the container finalizes the servlet by calling the servlet’s &lt;strong&gt;destroy&lt;/strong&gt; method. For more information, see Finalizing a Servlet.&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;For comparison, let&#39;s take a look at what we can read at &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms178472.aspx&quot;&gt;ASP.NET web page life cycle documentation&lt;/a&gt;. Again, there&#39;s a table where we can find the names of the methods called at each stage, the order of the methods called and what we can expect when implementing each method.&lt;/p&gt;

&lt;p&gt;These aren&#39;t necessarily examples of dependency injection, but are examples of inversion of control, which DI is a particular application of.&lt;/p&gt;

&lt;p&gt;So, ekhem... would you really say that putting knowledge on what methods and in what order are performed breaks encapsulation of JSP container or ASP.NET runtime? Or, in better words, is it exposing implementation details? No, it&#39;s just another part of the class public contract. Another example might be unit-testing frameworks, where you write so called &quot;test classes&quot; knowing, that &quot;Setup&quot; method is called before a test and &quot;teardown&quot; is called after.&lt;/p&gt;

&lt;p&gt;And this is my view on the whole encapsulation dillema - as soon as you make the dependencies of the class injectable (or use any other forms of inversion of control), how this class uses those dependencies becomes a part of public contract of a class, not private implementation detail. This public contract should be specified and thus we write unit level statements unit mock objects.&lt;/p&gt; 

&lt;p&gt;Of course, nothing, never, prevents you from exposing private implementation details while using any technique, it&#39;s just that mocks don&#39;t seem different in this regard in any particular way.&lt;/p&gt;

&lt;p&gt;What do YOU think?&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2014/01/mocks-are-breaking-encapsulation-heres.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-8775738051342517909</guid><pubDate>Sun, 08 Dec 2013 21:33:00 +0000</pubDate><atom:updated>2013-12-09T23:18:10.598+01:00</atom:updated><title>Moving to NUnit from MsTest - experience report</title><description>&lt;p&gt;Recently, I was a part of migration of some tests from MsTest to NUnit. I was in a situation where some of the tests were written in NUnit and some (legacy ones) in  MsTest and it was too costly to maintain both tools, so the money were put on NUnit. The goal was to convert existing tests as fast as possible, leaving refactoring and cleanup of test and production code for later. I didn&#39;t know much about MsTest before, and here&#39;s what I learned about it and the transition:&lt;/p&gt;

&lt;h4&gt;Assertions&lt;/h4&gt;

&lt;p&gt;Much to my astonishment, the number of assertions MsTest supports is rather small, compared to NUnit. You cannot assert something is greater than something else, cannot assert a value is in a certain range etc. This way, a lot of assertions looked like this (remember this was ugly legacy test code :-)):&lt;/p&gt;

&lt;pre&gt;Assert.True(numberOfMessages &amp;lt;= 1000 
  &amp;&amp; numberOfMessages &amp;gt;= 950, &quot;numberOfMessages&quot;)&lt;/pre&gt;

&lt;p&gt;This, at failure, gives you the a message like: &quot;Expected true, got false&quot;. Pretty helpful, isn&#39;t it (sarcasm)? Sure, you can make the message better, but you have to work hard on it yourself. The NUnit&#39;s (better) equivalent is:&lt;/p&gt;

&lt;pre&gt;Assert.That(numberOfMessages, Is.InRange(950, 1000));&lt;/pre&gt;

&lt;p&gt;Usually, when writing good unit tests, I don&#39;t really need this kind of assertions, but this was legacy code and it tested many kinds of weird situations over a large set of objects put together.&lt;/p&gt;

&lt;p&gt;On the other hand, MsTest has a strongly typed assertions in form of &lt;code&gt;Assert.AreEqual&amp;lt;T&amp;gt;()&lt;/code&gt; which are missing from NUnit. This, however, is not a big deal, because creating a custom wrapping assertions which will give you this benefit in NUnit is trivial. For example:&lt;/p&gt;

&lt;pre&gt;public class XAssert
{
  public static void AreEqual&amp;lt;T&amp;gt;(T expected, T actual)
  {
    NUnit.Framework.Assert.AreEqual(expected, actual);
  }
}&lt;/pre&gt;

&lt;p&gt;Lessons learned:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If you ever use MsTest, do yourself a favor and pick &lt;a href=&quot;https://github.com/dennisdoomen/fluentassertions&quot;&gt;an external assertion library&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;If you use NUnit, writing strongly typed wrappers over common assertions may be a good idea.&lt;/li&gt;

&lt;/ol&gt;

&lt;h4&gt;Deployment Items in .testsettings file&lt;/h4&gt;

&lt;p&gt;MsTest has this little feature of deployment items that can be configured in solution-wide .testsettings file to be copied to the output directory before a test  is run (usually these are some extra files etc.).&lt;/p&gt;

&lt;p&gt;But wait! &lt;a href=&quot;http://www.artima.com/weblogs/viewpost.jsp?thread=126923&quot;&gt;Why on earth would someone be willing to use that kind of feature in unit tests at all?&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Unfortunately, this was my case - the deployment items were used to load an XML configuration :-(. The problem with Deployment Items is that some 3rd party runners support it, and some don&#39;t (namely: NCrunch and Gallio, which makes running tools like Sonar over such tests pretty difficult). Also, some 3rd party unit testing tools do not run tests from the build output directory, but create their owne  custom directories somewhere on the hard drive (e.g. NCrunch does), but the paths coded in Deployment Items are not adjusted and get gopied to the same directories as always, leading to failed runs.&lt;/p&gt;

&lt;p&gt;Lessons learned:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;If you&#39;re using Deployment Items in MsTest for unit tests, you don&#39;t even give me a chance to think you&#39;re serious.&lt;/li&gt;
  &lt;li&gt;When Deployment Items are used to copy some additional files to the build output, this mechanism can be replaced with including these config files in test project &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/vstudio/9f4t9t92(v=vs.100).aspx&quot;&gt;as links&lt;/a&gt; and setting their &quot;Copy Local&quot; property to copy them to the build output directory.&lt;/li&gt;
  &lt;li&gt;Do not write or load files in unit tests!!!&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;PrivateType and PrivateObject&lt;/h4&gt;

&lt;p&gt;I was shocked when I discovered that MsTest includes helpers for accessing private instance/static methods: &lt;code&gt;PrivateType&lt;/code&gt; and &lt;code&gt;PrivateObject&lt;/code&gt;. Even for legacy code, there are better strategies to apply. Anyway, what shocks me more is that anyone can even think that using these may be a good idea (it is not). Thus, when converting to NUnit, I found such constructs in the code. They lead to brittle tests that are accessing members using strings and reflection. It seems like MsTest allows generating accessors that are strongly typed and use strings and reflection under the hood, but this is still coupling to implementation details, plus I saw PrivateType and PrivateObject being used directly many times.&lt;/p&gt;

&lt;p&gt;Lessons Learned:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;When writing new tests, forget that &lt;code&gt;PrivateType&lt;/code&gt; and &lt;code&gt;PrivateObject&lt;/code&gt; exist. &lt;a href=&quot;http://feelings-erased.blogspot.com/2012/06/how-to-test-private-methods.html&quot;&gt;Look for the real problem&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;PrivateType&lt;/code&gt; and &lt;code&gt;PrivateObject&lt;/code&gt; are just helpers over a reflection API, so they don&#39;t require being executed under MsTest to work properly. During transition to NUnit, you can leave references to MsTest assembly and change all code references to include namespace e.g. from &lt;code&gt;PrivateObject&lt;/code&gt; to &lt;code&gt;Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject&lt;/code&gt;. The code will still work.&lt;/li&gt;
&lt;/ol&gt;


&lt;h4&gt;Cost of Transition&lt;/h4&gt;

&lt;p&gt;In general, it&#39;s a lot simpler to migrate from MsTest to NUnit than the other way round. This is because NUnit requires only that an assembly references nunit.framework.dll and marks certain methods with &lt;code&gt;[Test]&lt;/code&gt; attribute. On the other hand, MsTest requires a special type of project (a Test Project) to hold the tests. Also, as I said, MsTest&#39;s assertions are for the most part a subset of NUnit&#39;s. Anyway, to convert a project from MsTest to NUnit, the following steps are usually sufficient:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Reference nunit.framework.dll from the test project.&lt;/li&gt;
  &lt;li&gt;Convert Deployment Items into links in project copied to the build output folder.&lt;/li&gt;
  &lt;li&gt;Search-Replace the following:
    &lt;ol&gt;
      &lt;li&gt;&lt;code&gt;[TestClass]&lt;/code&gt; -&amp;gt; &lt;code&gt;[TestFixture]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code&gt;[TestMethod]&lt;/code&gt; -&amp;gt; &lt;code&gt;[Test]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code&gt;[TestInitialize]&lt;/code&gt; -&amp;gt; &lt;code&gt;[SetUp]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code&gt;[TestCleanup]&lt;/code&gt; -&amp;gt; &lt;code&gt;[TearDown]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code&gt;[TestClassInitialize]&lt;/code&gt; -&amp;gt; &lt;code&gt;[TestFixtureSetUp]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code&gt;[TestClassCleanup]&lt;/code&gt; -&amp;gt; &lt;code&gt;[TestFixtureTearDown]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code&gt;using Microsoft.VisualStudio.TestTools.UnitTesting;&lt;/code&gt; -&amp;gt; &lt;code&gt;using NUnit.Framework;&lt;/code&gt;&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
  &lt;li&gt;Change &lt;code&gt;Assert.IsInstanceOfType(x, typeof(X))&lt;/code&gt; to &lt;code&gt;Assert.IsInstanceOf&amp;lt;X&amp;gt;(x);&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Change &lt;code&gt;Assert.AreEqual&amp;lt;X&amp;gt;(x, y)&lt;/code&gt; to &lt;code&gt;Assert.AreEqual(x, y)&lt;/code&gt;&lt;/li&gt; 
  &lt;li&gt;Fix references to some MsTest-specific classes (like &lt;code&gt;PrivateObject&lt;/code&gt;)&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;Summary&lt;/h4&gt;

&lt;p&gt;And that&#39;s it. These were the lessons learned and tips for dealing with the transition as fast as possible. I advise to do a real cleanup of the test and production code sooner than later, but the tips I outlined here let you defer this cost.&lt;/p&gt;
</description><link>http://feelings-erased.blogspot.com/2013/12/moving-to-nunit-from-mstest-experience.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>7</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-6080672902439868327</guid><pubDate>Tue, 08 Oct 2013 07:09:00 +0000</pubDate><atom:updated>2013-10-08T09:09:09.155+02:00</atom:updated><title>Developing TDD style by example</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;http://grzesiek-galezowski.github.io/tdd-ebook/&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;(&lt;strong&gt;Note that I use a term &quot;Statement&quot; instead of &quot;test&quot; and &quot;Specification&quot; instead of &quot;Test Suite&quot; in this post&lt;/strong&gt;)&lt;/p&gt;


  &lt;p&gt;Throughout this blog, you have seen me using quite extensively a utility class called &lt;code&gt;Any&lt;/code&gt;. The time has come to explain a little bit more carefully what principles lie under this technique and tool. I&#39;ll also use this technique as a case study to show you how one develops a style of Test-Driven Development.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_42&quot;&gt;A style?&lt;/h3&gt;

  &lt;p&gt;Yep. Why am I wasting your time writing about style instead of giving you the hardcore technical details? The answer is simple. Before I started writing this tutorial, I read four or five books solely on TDD and maybe two others that contain chapters on TDD. All of this sums up to about two or three thousands of paper pages, plus numerous posts on many blogs. And you know what I noticed? No two authors use exactly the same sets of techniques for test-driving their code! I mean, sometimes, when you look techniques they&#39;re suggesting, the suggestions from two authorities contradict each other. As each authority has their followers, it&#39;s not uncommon to observe and take part in discussions about whether this or that technique is better than a competing one or which one leads to trouble in the long run.&lt;/p&gt;

  &lt;p&gt;I did this, too. I also tried to understand how come people praise techniques I KNEW were wrong and led to disaster. Then, Finally, I got it. I understood that it&#39;s not a &quot;technique A vs. technique B&quot; debate. There are certain sets of techniques that work together and choosing one technique leaves us with issues we have to resolve by adopting other techniques. This is how a style is created.&lt;/p&gt;

  &lt;p&gt;Developing a style starts with underlying set of principles. These principles lead us to adopt our first technique, which makes us adopt another one and, ultimately, a coherent style emerges. Using Constrained Non-Determinism as an example, I&#39;ll try to show you how part of a style gets derived from a technique that is derived from a principle.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_43&quot;&gt;Principle: Tests As Specification&lt;/h3&gt;

  &lt;p&gt;As I already stressed, I strongly believe that unit tests constitute an executable specification. Thus, they should not only pass input values to an object and assert on the output, they should also convey to their reader the rules according to which objects and functions work. The following oversimplified example shows a Statement where it&#39;s not explicitly stated what&#39;s the relationship between input and output:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot; &gt;[Fact] public void 
ShouldCreateBackupFileNameContainingPassedHostName()
{
  //GIVEN
  var fileNamePattern = new BackupFileNamePattern();
  
  //WHEN
  var name = fileNamePattern.ApplyTo(&quot;MY_HOST_NAME&quot;);
  
  //THEN
  Assert.Equal(&quot;backup_MY_HOST_NAME.zip&quot;);
}&lt;/pre&gt;

  &lt;p&gt;Although the relationship can be guessed quite easily, remember it&#39;s just an example. Also, seeing code like that makes me ask questions like: is the &quot;backup_&quot; prefix always applied? What if I actually pass &quot;backup_&quot; instead of &quot;MY_HOST_NAME&quot;? Will the name be &quot;backup_backup_.zip&quot;, or &quot;backup_.zip&quot;? Also, is this object responsible for any validation of passed string?&lt;/p&gt;

  &lt;p&gt;This makes me invent a first technique to provide my Statements with better support for the principle I believe in.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_44&quot;&gt;First technique: Anonymous Input&lt;/h3&gt;

  &lt;p&gt;I can wrap the actual value &quot;MY_HOST_NAME&quot; with a method and give it a name that better documents the constraints imposed on it by the specified functionality. In our case, we can pass whatever string we want (the object is not responsible for input validation), so we&#39;ll name our method &lt;code&gt;AnyString()&lt;/code&gt;:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldCreateBackupFileNameContainingPassedHostName()
{
  //GIVEN
  var hostName = AnyString();
  var fileNamePattern = new BackupFileNamePattern();
  
  //WHEN
  var name = fileNamePattern.ApplyTo(hostName);
  
  //THEN
  Assert.Equal(&quot;backup_MY_HOST_NAME.zip&quot;);
}

public string AnyString()
{
  return &quot;MY_HOST_NAME&quot;;
}&lt;/pre&gt;

  &lt;p&gt;By using &lt;strong&gt;anonymous input&lt;/strong&gt;, we provide a better documentation of the input value. Here, I wrote &lt;code&gt;AnyString()&lt;/code&gt;, but of course, there can be a situation where I use more constrained data, e.g. &lt;code&gt;AnyAlphaNumericString()&lt;/code&gt; when I need a string that does not contain any characters other than letters and digits. Note that this technique &lt;strong&gt;is applicable only when the particular value of the variable is not important, but rather its &quot;trait&quot;&lt;/strong&gt;. Taking authorization as an example, when a certain behavior occurs only when the input value is &lt;code&gt;Users.Admin&lt;/code&gt;, there&#39;s &lt;strong&gt;no sense&lt;/strong&gt; making it anonymous. On the other hand, for a behavior that occurs for all values other than &lt;code&gt;Users.Admin&lt;/code&gt;, it makes sense to use a method like &lt;code&gt;AnyUserOtherThan(Users.Admin)&lt;/code&gt; or even &lt;code&gt;AnyNonAdminUser()&lt;/code&gt;.&lt;/p&gt;

  &lt;p&gt;Now that the Statement itself is freed from the knowledge of the concrete value of &lt;code&gt;hostName&lt;/code&gt; variable, the concrete value of &quot;backup_MY_HOST_NAME.zip&quot; looks kinda weird. There&#39;s no clear indication of the kind of relationship between input and output and whether there is any at all (one may reason whether the output is always the same string or maybe it depends on the string length). It is unclear which part is added by the production code and which part depends on the input we pass to the method. This leads us to another technique.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_45&quot;&gt;Second Technique: Derived Values&lt;/h3&gt;

  &lt;p&gt;To better document the relationship between input and output, we have to simply derive the expected value we assert on from the input value. Here&#39;s the same Statement with the assertion changed:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldCreateBackupFileNameContainingPassedHostName()
{
  //GIVEN
  var hostName = AnyString();
  var fileNamePattern = new BackupFileNamePattern();
  
  //WHEN
  var name = fileNamePattern.ApplyTo(hostName);
  
  //THEN
  Assert.Equal(string.Format(&quot;backup_{0}.zip&quot;, hostName);
}
public string AnyString()
{
  return &quot;MY_HOST_NAME&quot;;
}&lt;/pre&gt;

  &lt;p&gt;This looks more like a part of specification, because we&#39;re documenting the format of the backup file name and show which part of the format is variable and which part is fixed. This is something you&#39;d probably find documented in a paper specification for the application you&#39;re writing - it would probably contain a sentence saying: &quot;The format of a backup file should be &lt;strong&gt;backup_H.zip&lt;/strong&gt;, where &lt;strong&gt;H&lt;/strong&gt; is the current local host name&quot;.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Derived values&lt;/strong&gt; are about defining expected output in terms of the input that was passed to provide a clear indication on what is the &quot;transformation&quot; of the input required of the specified production code.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_46&quot;&gt;Third technique: Distinct Generated Values&lt;/h3&gt;

  &lt;p&gt;Let&#39;s assume that some time after our initial version is shipped, we&#39;re asked to make the backup feature applied locally per user only for this user&#39;s data. As the customer doesn&#39;t want to confuse files from different users, we&#39;re asked to add name of the user doing backup to the backup file name. Thus, the new format is &quot;backup_H_U.zip&quot;, where H is still the host name and U is the user name. Our Statement for the pattern must change as well to include this information. Of course, we&#39;re trying to use the anonymous input again as a proven technique and we end up with:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldCreateBackupFileNameContainingPassedHostNameAndUserName()
{
  //GIVEN
  var hostName = AnyString();
  var userName = AnyString();
  var fileNamePattern = new BackupFileNamePattern();
  
  //WHEN
  var name = fileNamePattern.ApplyTo(hostName, userName);
  
  //THEN
  Assert.Equal(string.Format(
    &quot;backup_{0}_{1}.zip&quot;, hostName, userName);
}

public string AnyString()
{
  return &quot;MY_HOST_NAME&quot;;
}&lt;/pre&gt;

  &lt;p&gt;Now, we can clearly see that there is something wrong with this Statement. AnyString() is used twice and each time it returns the same value, which means that evaluating the Statement does not give us any guarantee, that both values are applied and that they&#39;re applied in the correct places. For example, the Statement will be evaluated to true when user name is used instead of host name in specified production code. This means that if we still want to use the anonymous input effectively, we have to make the two values distinct, e.g. like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldCreateBackupFileNameContainingPassedHostNameAndUserName()
{
  //GIVEN
  var hostName = AnyString();
  var userName = AnyString2();
  var fileNamePattern = new BackupFileNamePattern();
  
  //WHEN
  var name = fileNamePattern.ApplyTo(hostName, userName);
  
  //THEN
  Assert.Equal(string.Format(
    &quot;backup_{0}_{1}.zip&quot;, hostName, userName);
}

public string AnyString()
{
  return &quot;MY_HOST_NAME&quot;;
}

public string AnyString2()
{
  return &quot;MY_USER_NAME&quot;;
}&lt;/pre&gt;

  &lt;p&gt;We solved the problem (for now) by introducing another helper method. However, this, as you can see, isn&#39;t a very scalable solution. Thus, let&#39;s try to reduce the amount of helper methods for string generation to one and make it return a different value each time:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldCreateBackupFileNameContainingPassedHostNameAndUserName()
{
  //GIVEN
  var hostName = AnyString();
  var userName = AnyString();
  var fileNamePattern = new BackupFileNamePattern();
  
  //WHEN
  var name = fileNamePattern.ApplyTo(hostName, userName);
  
  //THEN
  Assert.Equal(string.Format(
    &quot;backup_{0}_{1}.zip&quot;, hostName, userName);
}

public string AnyString()
{
  return Guid.NewGuid.ToString();
}&lt;/pre&gt;

  &lt;p&gt;This time, we&#39;re not returning an understandable string, but rather a guid, which gives us the fairly strong guarantee of generating distinct value each time. The string not being understandable (contrary to something like &quot;MY_HOST_NAME&quot;) may leave you worried that maybe we&#39;re losing something, but hey, didn&#39;t we say &lt;strong&gt;Any&lt;/strong&gt;String()?&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Distinct generated values&lt;/strong&gt; means that each time we need a value of a particular type, we get something different (if possible) than the last time and each value is generated automatically using some kind of heuristics.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_47&quot;&gt;Fourth technique: Constant Specification&lt;/h3&gt;

  &lt;p&gt;Let us consider another modification that we&#39;re requested to make - this time, the backup file name needs to contain version number of our application as well. Remembering that we want to use Derived Values, we won&#39;t hardcode the version number into our Statement. Instead, we&#39;re going to use a constant that&#39;s already defined somewhere else in the application (this way we also avoid duplication of this version number across the application):&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldCreateBackupFileNameContainingPassedHostNameAndUserNameAndVersion()
{
  //GIVEN
  var hostName = AnyString();
  var userName = AnyString();
  var fileNamePattern = new BackupFileNamePattern();
  
  //WHEN
  var name = fileNamePattern.ApplyTo(hostName, userName);
  
  //THEN
  Assert.Equal(string.Format(
    &quot;backup_{0}_{1}_{2}.zip&quot;, 
    hostName, userName, Version.Number);
}

public string AnyString()
{
  return Guid.NewGuid.ToString();
}&lt;/pre&gt;

  &lt;p&gt;Note that I didn&#39;t use the literal constant value, but rather, the value inside the &lt;code&gt;Version.Number&lt;/code&gt; constant. This allows us to use derived value, but leaves us a little worried about whether the value of the constant is correct - after all, we&#39;re using it for creation of our expected value, but it&#39;s a part of production code - i.e. is something that should be specified itself!&lt;/p&gt;

  &lt;p&gt;To keep everyone happy, we write a single Statement just for the constant to specify what the value should be:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldContainNumberEqualTo1_0()
{
  Assert.Equal(&quot;1.0&quot;, Version.Number);
}&lt;/pre&gt;

  &lt;p&gt;By doing so, we make the value in the production code just echo what&#39;s in our executable Specification, which we can fully trust.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_48&quot;&gt;Summary of the example&lt;/h3&gt;

  &lt;p&gt;In this example, I tried to show you how a style can evolve from the principles you value when doing TDD. I did so for two reasons:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;To introduce to you a set of techniques I personally use and recommend and to do it in a fluent and logical way.&lt;/li&gt;

    &lt;li&gt;To help you better communicate with people that are using different styles. Instead of just throwing &quot;you&#39;re doing it wrong&quot; at them, try to understand their principles and how their techniques of choice support those principles.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;Now, let&#39;s take a quick summary of all the techniques introduced in example:&lt;/p&gt;

  &lt;dl&gt;
    &lt;dt&gt;Anonymous Input&lt;/dt&gt;

    &lt;dd&gt;moving the output out of the Statement code and hide it behind a method that to emphasize the constrain on the data used rather than what&#39;s its value&lt;/dd&gt;

    &lt;dt&gt;Derived Values&lt;/dt&gt;

    &lt;dd&gt;defining expected output in terms of the input in order to document the relationship between input and output&lt;/dd&gt;

    &lt;dt&gt;Distinct Generated Values&lt;/dt&gt;

    &lt;dd&gt;When using Anonymous Input, generate a distinct value each time (in case of types that have very few values, like boolean, try at least not to generate the same value twice in a row) in order to make the Statement more reliable.&lt;/dd&gt;

    &lt;dt&gt;Constant Specification&lt;/dt&gt;

    &lt;dd&gt;Write a separate Statement for a constant and use the constant instead of its literal value in all other Statements to create a Derived Value.&lt;/dd&gt;
  &lt;/dl&gt;

  &lt;h3 id=&quot;sigil_toc_id_49&quot;&gt;Constrained non-determinism&lt;/h3&gt;

  &lt;p&gt;When we combine anonymous input together with distinct generated values, we get something that&#39;s called &lt;strong&gt;Constrained Non-Determinism&lt;/strong&gt;. This is a term coined by Mark Seemann and basically means three things:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Values are anonymous i.e. we don&#39;t know the actual value we&#39;re using&lt;/li&gt;

    &lt;li&gt;The values are generated in as distinct as possible sequence (which means that, whenever possible, no two values generated one after another hold the same value)&lt;/li&gt;

    &lt;li&gt;The non-determinism in generation of the values is constrained, which means that the algorithms for generating values are carefully picked in order to provide values that are not special in any way (e.g. when generating integers, we don&#39;t allow generating &#39;0&#39; as it&#39;s usually a special-case-value)) and that are not &quot;evil&quot; (e.g. for integers, we generate small positive values first and go with bigger numbers only when we run out of those small ones).&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;There are multiple ways to implement constrained non-determinism. Mark Seemann himself invented the AutoFixture library for C# that&#39;s &lt;a href=&quot;https://github.com/AutoFixture/AutoFixture&quot;&gt;freely available to download by anyone&lt;/a&gt;. Here&#39;s a shortest possible snippet to generate an anonymous integer using AutoFixture:&lt;/p&gt;

  &lt;pre class=&quot;brush: csharp&quot;&gt;Fixture fixture = new Fixture();
var anonymousInteger = fixture.Create&amp;lt;int&amp;gt;();&lt;/pre&gt;

  &lt;p&gt;I, after Amir Kolsky and Scott Bain, like to use &lt;code&gt;Any&lt;/code&gt; class. Any takes a slightly different approach than AutoFixture (although it shamelessly uses AutoFixture internally and actually obscures its impressive abilities). My implementation of Any class is &lt;a href=&quot;https://github.com/grzesiek-galezowski/tdd-toolkit&quot;&gt;available to download as well&lt;/a&gt;.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_50&quot;&gt;Summary&lt;/h3&gt;

  &lt;p&gt;That was a long ride, wasn&#39;t it? I hope that this post gave you some understanding of how different TDD styles came into existence and why I use some of the techniques I do (and how these techniques are not just a series of random choices). In the next posts, I&#39;ll try to introduce some more techniques to help you grow a bag of neat tricks - a coherent style.&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2013/10/developing-tdd-style-by-example.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-2435249677153639949</guid><pubDate>Sun, 11 Aug 2013 19:50:00 +0000</pubDate><atom:updated>2013-08-11T21:50:41.781+02:00</atom:updated><title>How is TDD about analysis and what&#39;s with the GIVEN-WHEN-THEN structure?</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;http://grzesiek-galezowski.github.io/tdd-ebook/&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;(&lt;strong&gt;Note that I use a term &quot;Statement&quot; instead of &quot;test&quot; and &quot;Specification&quot; instead of &quot;Test Suite&quot; in this post&lt;/strong&gt;)&lt;/p&gt;

  &lt;h3&gt;Is there really a commonality between analysis and TDD?&lt;/h3&gt;

  &lt;p&gt;From Wikipedia:&lt;/p&gt;

  &lt;blockquote cite=&quot;https://en.wikipedia.org/wiki/Analysis&quot;&gt;
    Analysis is the process of breaking a complex topic or substance into smaller parts to gain a better understanding of it.
  &lt;/blockquote&gt;

  &lt;p&gt;Thus, in order for TDD to be about analysis, it has to fulfill two conditions:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Be a process of breaking a complex topic into smaller parts&lt;/li&gt;

    &lt;li&gt;Allow gaining a better understanding of such broken topics&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;In the &lt;a href=&quot;http://feelings-erased.blogspot.com/2013/06/an-expert-and-novice-practicing-tdd.html&quot;&gt;story about Johnny, Benjamin and Jane&lt;/a&gt;, I included a part where they analyze requirements using concrete examples. Johnny explained that this is a part of a technique called Acceptance Test-Driven Development. The process followed by the three characters fulfilled both mentioned conditions for a process to be analytical. But what about TDD itself?&lt;/p&gt;

  &lt;p&gt;Actually, I used parts of ATDD process in the story to make the analysis part more obvious, but similar things happen at pure technical levels. For example, when starting development with a failing application-wide Statement (we&#39;ll talk about levels of granularity of Statements some time later. For now the only thing you need to know is that the so called &quot;unit tests level&quot; is not the only level of granularity we write Statements on), we may encounter a situation where we need to call a web method and assert its result. This makes us think: what should this method be called? What are the scenarios supported? What do I need to get out of it? How should its user be notified about errors? Many times, this leads us to either a conversation (if there&#39;s another stakeholder that needs to be involved in the decision) or rethinking our assumptions. This is how we gain a better understanding of the topic we&#39;re analyzing, which makes TDD fulfill the first of the two requirements for it to be an analysis method.&lt;/p&gt;

  &lt;p&gt;But what about the first requirement? What about breaking a complex logic into smaller parts?&lt;/p&gt;

  &lt;p&gt;If you go back to our example, you&#39;ll note that both when talking to a customer and when writing code, Johnny and Benjamin used a TODO list. This list was first filled with whatever scenarios they came up with, but later, they would add a smaller unit of work. This is one way complex topics are decomposed into smaller items that all land on the TODO list (the other way is mocking, but we won&#39;t get into that yet). Thanks to this, we can focus on one thing at a time, crossing off item after item from the list after it&#39;s done. If we learn something new or encounter new issue that needs our attention, we can add it to the TODO list and get back to it later, for now continuing our work on the current point of focus.&lt;/p&gt;

  &lt;p&gt;An example TODO list from the middle of implementation may look like this (don&#39;t read trough it, I put it here only to give you a glimpse):&lt;/p&gt;

&lt;div style=&quot;border: dashed thin black; background: #FFFF99;&quot;&gt;
  &lt;ol style=&quot;font-style: italic;&quot;&gt;
    &lt;li&gt;
      &lt;del&gt;Create entry point to the module (top-level abstraction)&lt;/del&gt;
    &lt;/li&gt;

    &lt;li&gt;
      &lt;del&gt;Implement main workflow of the module&lt;/del&gt;
    &lt;/li&gt;

    &lt;li&gt;
      &lt;del&gt;Implement Message interface&lt;/del&gt;
    &lt;/li&gt;

    &lt;li&gt;
      &lt;del&gt;Implement MessageFactory interface&lt;/del&gt;
    &lt;/li&gt;

    &lt;li&gt;Implement ValidationRules interface&lt;/li&gt;

    &lt;li&gt;
      &lt;del&gt;Implement behavior required from Wrap method in LocationMessageFactory class&lt;/del&gt;
    &lt;/li&gt;

    &lt;li&gt;Implement behavior required from ValidateWith method in LocationMessage class for Speed field&lt;/li&gt;

    &lt;li&gt;Implement behavior required from ValidateWith method in LocationMessage class for Age field&lt;/li&gt;

    &lt;li&gt;Implement behavior required from ValidateWith method in LocationMessage class for Sender field&lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;

  &lt;p&gt;Note that some items are already crossed out as done, while other remain undone and waiting to be addressed.&lt;/p&gt;

  &lt;p&gt;Ok, That&#39;s it for the discussion. Now that we&#39;re sure that TDD is about analysis, let&#39;s focus on the tools can use to aid and inform it.&lt;/p&gt;

  &lt;h3&gt;Gherkin&lt;/h3&gt;

  &lt;p&gt;Hungry? Too bad, because the Gkerkin I&#39;m gonna talk about is not edible. It&#39;s a notation and a way of thinking about behaviors of the specified piece of code. It can be applied on different levels of granularity - any behavior, whether of a whole system or a single class, may be described using it.&lt;/p&gt;

  &lt;p&gt;I actually talked about Gherkin before on this blog, just did not name it. It&#39;s the GIVEN-WHEN-THEN structure that you can see everywhere, even in code samples as comments. This time, we&#39;re stamping a name on it and analyzing it further.&lt;/p&gt;

  &lt;p&gt;In Gherkin, a behavior description consists of three parts:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Given - a context&lt;/li&gt;

    &lt;li&gt;When - a cause&lt;/li&gt;

    &lt;li&gt;Then - a effect&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;In other words, the emphasis is on causality in a given context.&lt;/p&gt;

  &lt;p&gt;As I said, there are different levels you can apply this. Here&#39;s an example for such a behavior description from the perspective of its end user (this is called acceptance-level Statement):&lt;/p&gt;
  &lt;pre&gt;Given a bag of tea costs $20
When I buy two of them
Then I pay 30$ due to promotion&lt;/pre&gt;

  &lt;p&gt;And here&#39;s one for unit-level (note the line starting with &quot;And&quot; that adds to the context):&lt;/p&gt;
  &lt;pre&gt;Given a list with 2 items
When I add another item
And check count of items
Then the count should be 3&lt;/pre&gt;

  &lt;p&gt;While on acceptance level we put such behavior descriptions together with code as the same artifact (If this doesn&#39;t ring a bell, look at tools like SpecFlow or Cucumber or FIT to get some examples), on the unit level the description is usually not written down literally, but in form of code only. Still, this structure is useful when thinking about behaviors required from an object or objects, as we saw when we talked about starting from Statement rather than code. I like to put the structure explicitly in my Statements - I find that it makes them more readable. So most of my unit-level Statements follow this template:&lt;/p&gt;
  &lt;pre&gt;[Fact]
public void Should__BEHAVIOR__()
{
  //GIVEN
  ...context...

  //WHEN
  ...trigger...

  //THEN
  ...assertions etc....
}
&lt;/pre&gt;

  &lt;p&gt;Sometimes the WHEN and THEN sections are not so easily separable - then I join them, like in case of the following Statement specifying that an object throws an exception when asked to store null:&lt;/p&gt;
  &lt;pre&gt;[Fact]
public void ShouldThrowExceptionWhenAskedToStoreNull()
{
  //GIVEN
  var safeList = new SafeList();

  //WHEN - THEN
  Assert.Throws&amp;lt;Exception&amp;gt;(
    () =&amp;gt; safeList.Store(null)
  );
}
&lt;/pre&gt;

  &lt;p&gt;By thinking in terms of these three parts of behavior, we may arrive at different circumstances (GIVEN) at which the behavior takes place, or additional ones that are needed. The same goes for triggers (WHEN) and effects (THEN). If anything like this comes to our mind, we add it to the TODO list.&lt;/p&gt;

  &lt;h3&gt;TODO list... again!&lt;/h3&gt;

  &lt;p&gt;As we said previously, a TODO list is a repository for anything that comes to our mind when writing or thinking about a Statement, but is not a part o the current Statement we&#39;re writing. We don&#39;t want to forget it, neither do we want it to haunt us and distract us from our current task, so we write it down as soon as possible and continue with our current task.&lt;/p&gt;

  &lt;p&gt;Suppose you&#39;re writing a piece of small logic that allows user access when he&#39;s an employee of a zoo, but denies access if he&#39;s a guest of the zoo. Then, after starting writing a Statement it gets to you that actually any employee can be a guest as well - for example, he might choose to visit the zoo with his family during his vacation. Still, the two previous rules hold, so not to allow this case to distract you, you quickly add an item to the TODO list (like &quot;TODO: what if someone is an employee, but comes to the zoo as a guest?&quot;) and finish the current Statement. When you&#39;re finished, you can always come back to the list and pick item to do next.&lt;/p&gt;

  &lt;p&gt;There are two important questions related to TODO lists: &quot;what exactly should we add as a TODO list item?&quot; and &quot;How to efficiently manage the TODO list?&quot;. We&#39;ll take care of these two questions now.&lt;/p&gt;

  &lt;h4&gt;What to put on the TODO list?&lt;/h4&gt;

  &lt;p&gt;Everything that you need addressed but is not part of the current Statement. Those items may be related to implementing unimplemented methods, to add whole functionalities (such items are usually followed my more fine-grained sub tasks as soon as you start implementing the item), there might be reminders to take a better look at something (e.g. &quot;investigate what is this component&#39;s policy for logging errors&quot;) or questions about the domain that need to get answered. If you get carried away too much in coding that you forget to eat, you can even add a reminder (&quot;TODO: get something to eat!&quot;). The list is yours!&lt;/p&gt;

  &lt;h4&gt;How to pick items from TODO list?&lt;/h4&gt;

  &lt;p&gt;Which item to choose from the TODO list when you have several? I have no clear rule, although I tend to take into account the following factors:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Risk - if what I learn by implementing or discussing a particular item from the list can have big impact on design or behavior of the system, I tend to pick such items first. An example of such item is that you start implementing validation of a request that arrives to your application and want to return different error depending on which part of the request is wrong. Then, during the development, you discover that more than one part of the request can be wrong at a time and you have to answer yourself a question: which error code should be returned in such case? Or maybe the return codes should be accumulated for all validations and then returned as a list?&lt;/li&gt;

    &lt;li&gt;Difficulty - depending on my mental condition (how tired I am, how much noise is currently around my desk etc.), I tend to pick items with difficulty that best matches this condition. For example, after finishing an item that requires a lot of thinking and figuring out things, I tend to take on some small and easy items to feel wind blowing in my sails and to rest a little bit.&lt;/li&gt;

    &lt;li&gt;Completeness - in simplest words, when I finish test-driving an &quot;if&quot; case, I usually pick up the &quot;else&quot; next. For example, after I finish implementing a Statement saying that something should return true for values less than 50, then the next item to pick up is the &quot;greater or equal to 50&quot; case. Usually, when I start test-driving a class, I take items related to this class until I run out of them, then go on to another one.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;h3&gt;Where to put a TODO list?&lt;/h3&gt;

  &lt;p&gt;There are two ways of maintaining a TODO list. The first one is on a sheet of paper, which is nice, but requires you to take your hands off the keyboard, grab a pen or pencil and then get back to coding every time you think of something. Also, the only way a TODO item written on a sheet of paper can tell you which place in code it is related to, is (obviously) by its text.&lt;/p&gt;

  &lt;p&gt;Another alternative is to use a TODO list functionality built-in into an IDE. Most IDEs, such as Visual Studio (and Resharper plugin has its own enhanced version), Xamarin Studio or eclipse-based IDEs have such functionality. The rules are simple - you put special comments in the code and a special view in your IDE aggregates them for you, allowing you to navigate to each. Such lists are great because:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;They don&#39;t force you to take your hands off keyboard to add an item to the list.&lt;/li&gt;

    &lt;li&gt;You can put such item in a certain place in the code where is makes sense and then navigate back to it with a click of a mouse. This, apart from other advantages, lets you write shorter notes than if you had to do it on paper. For example, a TODO item saying &quot;TODO: what if it throws an exception?&quot; looks out of place on the paper, but when added as a comment to your code in the right place, it&#39;s mighty sufficient.&lt;/li&gt;

    &lt;li&gt;Many TODO lists automatically add items for certain things. E.g. in C#, when you are yet to implement a method that was automatically generated by a tool, its body usually consists of a line that throws a NotImplementedException exception. Guess what - NotImplementedException occurences are added to the TODO list automatically, so don&#39;t have to manually add notes to implement the methods where they occur.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;There are also some downsides. The biggest is that people often add TODO items for other means than to support TDD and they never go back to such items. Some people joke that a TODO left in the code means &quot;Once, I wanted to...&quot;. Anyway, such items may pollute your TDD-related TODO list with so much cruft that your own items are barely findable. To work around it, I tend to use a different tag than TODO (many IDEs let you define your own tags, or support multiple tag types out of the box. E.g. with Resharper, I like to use &quot;bug&quot; tag, because this is something no one would leave in the code) and filter by it. Another options is, of course, getting rid of the leftover TODO items - if no one addressed it for a year, then probably no one ever will.&lt;/p&gt;

  &lt;p&gt;Another downside is that when you work with multiple workspaces/solutions, your IDE will gather TODO items only from current solution/workspace, so you&#39;ll have few TODO lists - one per workspace or solution. Fortunately, this isn&#39;t usually a big deal.&lt;/p&gt;
</description><link>http://feelings-erased.blogspot.com/2013/08/how-is-tdd-about-analysis-and-whats.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-3514968762495227013</guid><pubDate>Wed, 10 Jul 2013 19:14:00 +0000</pubDate><atom:updated>2013-07-10T21:14:49.988+02:00</atom:updated><title>How to start with a test, not implementation - part 4</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;http://grzesiek-galezowski.github.io/tdd-ebook/&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;(&lt;strong&gt;Note that I use &quot;Statement&quot; instead of &quot;test&quot; and &quot;Specification&quot; instead of &quot;Test Suite&quot; in this post&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;This is the last installment of &quot;how to start with a test&quot; series. This time, we&#39;re gonna take on the last of the typical techniques, useful when there&#39;s already some existing code to fit in.&lt;/p&gt;

  &lt;h1 id=&quot;sigil_toc_id_32&quot;&gt;Start by invoking a method when you have one&lt;/h1&gt;

  &lt;p&gt;Sometimes, we have to add a new class that implements an existing interface required by another class. The fact of implementing an interface imposes what methods should the new class support. If this point is already decided, we can start our Statement by first calling the method and then discovering what we need to supply.&lt;/p&gt;

  &lt;h3&gt;A simple example&lt;/h3&gt;

  &lt;p&gt;Suppose we have an application holding a lot of data that, among other things, handles importing am existing database from another instance of the application. As importing a database can be a lengthy process, a message box is displayed each time when user chooses to perform the import and this message box displays the following message: &quot;Johnny, please sit down and enjoy your coffee for a few minutes as we take time to import your database&quot; (given user name is Johnny). The class that implements it looks like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;public class FriendlyMessages
{
 public string 
 HoldOnASecondWhileWeImportYourDatabase(string userName)
 {
   return string.Format(&quot;{0}, &quot;
     + &quot;please sit down and enjoy your coffee &quot;
     + &quot;for a few minutes as we take time &quot;
     + &quot;to import your database&quot;,
     userName);
 }
}&lt;/pre&gt;

  &lt;p&gt;Now, imagine that our management told us that they need to ship a trial version with some features disabled, including importing an existing database. Among all the things we need to do to make it happen, we also need to display a different string with message saying that this is a trial version and the feature is locked. We can do it by extracting an interface from the &lt;code&gt;FriendlyMessages&lt;/code&gt; class and using it to put in an instance of another class implementing this interface when the application discovers that it is being run as a trial version. The extracted interface looks like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;public interface Messages
{
  string HoldOnASecondWhileWeImportYourDatabase(string userName);
}&lt;/pre&gt;

  &lt;p&gt;So our new implementation is forced to support the &lt;code&gt;HoldOnASecondWhileWeImportYourDatabase&lt;/code&gt; method. Thus, we when implementing the class, we start with the following:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;public class TrialVersionMessages : Messages
{
 public string HoldOnASecondWhileWeImportYourDatabase(string userName)
 {
   throw new NotImplementedException();
 }
}&lt;/pre&gt;

  &lt;p&gt;Now, we&#39;re ready to start writing a Statement. Assuming we don&#39;t know where to start, we just start with creating an object and invoking the method that needs to be implemented:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] 
public void TODO()
{
 //GIVEN
 var trialMessages = new TrialVersionMessages();
 
 //WHEN
 trialMessages.HoldOnASecondWhileWeImportYourDatabase();

 //THEN
 Assert.True(false); //to remember about it
}&lt;/pre&gt;

  &lt;p&gt;As you can see, we added an assertion that always fails at the end because we don&#39;t have any assertions yet and the Statement would otherwise be already evaluated as true and we&#39;d rather have it remind ourselves that it is not finished. Other than this, the Statement does not compile anyway, because the method &lt;code&gt;HoldOnASecondWhileWeImportYourDatabase&lt;/code&gt; takes a string argument and we passed none. This makes us ask the question what is this argument and what&#39;s its role in the behavior triggered by the &lt;code&gt;HoldOnASecondWhileWeImportYourDatabase&lt;/code&gt; method. Seems like it is a user name and we want it to be somewhere in the result of the method. Thus, we can add it to the Statement like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] 
public void TODO()
{
 //GIVEN
 var trialMessages = new TrialVersionMessages();
 var userName = Any.String();
 
 //WHEN
 trialMessages.
  HoldOnASecondWhileWeImportYourDatabase(userName);

 //THEN
 Assert.True(false); //to remember about it
}&lt;/pre&gt;

  &lt;p&gt;Now, this compiles but is evaluated as false because of the guard assertion that we put at the end. Our goal is to substitute it with a real assertion for a real expected result. The return value of the &lt;code&gt;HoldOnASecondWhileWeImportYourDatabase&lt;/code&gt; is a string message, so all we need to do is to come up with the message that we expect in case of trial version:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] 
public void TODO()
{
 //GIVEN
 var trialMessages = new TrialVersionMessages();
 var userName = Any.String();
 
 //WHEN
 var message = trialMessages.
  HoldOnASecondWhileWeImportYourDatabase(userName);

 //THEN
 var expectedMessage = 
  string.Format(&quot;{0}, better get some pocket money!&quot;, userName);

 Assert.Equal(expectedMessage, message);
}
&lt;/pre&gt;

  &lt;p&gt;and all that is left is to find a good name for the Statement. This isn&#39;t an issue since we already specified the desired behavior in the code, so we can just summarize it as something like &lt;code&gt;ShouldYieldAMessageSayingThatFeatureIsLockedWhenAskedForImportDatabaseMessage&lt;/code&gt;.&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2013/07/how-to-start-with-test-not_10.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-5474680515857644197</guid><pubDate>Thu, 04 Jul 2013 07:42:00 +0000</pubDate><atom:updated>2013-07-04T09:42:41.608+02:00</atom:updated><title>How to start with a test, not implementation - part 3</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;http://grzesiek-galezowski.github.io/tdd-ebook/&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;(&lt;strong&gt;Note that I use &quot;Statement&quot; instead of &quot;test&quot; and &quot;Specification&quot; instead of &quot;Test Suite&quot; in this post&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://feelings-erased.blogspot.com/2013/06/how-to-start-with-test-not.html&quot;&gt;In the first part&lt;/a&gt;, I discussed how a good name is a great start for writing a Statement when there&#39;s no production code to invoke. In the &lt;a href=&quot;http://feelings-erased.blogspot.com/2013/06/how-to-start-with-test-not_25.html&quot;&gt;second part&lt;/a&gt;, I elaborated on usefulness of thinking in terms of GIVEN-WHEN-THEN structure and translating it almost literally to code. Today, I&#39;d like to introduce to you another technique - one that may appear awkward, but is actually very useful.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_30&quot;&gt;Start from the end&lt;/h3&gt;

  &lt;p&gt;This is a technique that I suggest to people that seem to have absolutely no idea how to start. I got it from Kent Beck&#39;s book Test Driven Development by Example. It seems funny at start, but is quite powerful. The trick is to write the Statement &#39;backwards&#39;, i.e. starting with what the Statement asserts to be true (in terms of the GIVEN-WHEN-THEN structure, we&#39;d say that we start with our THEN).&lt;/p&gt;

  &lt;p&gt;This works because, while we&#39;re many times quite sure of our goal (i.e. what the outcome of the behavior should be), but are unsure of how to get there.&lt;/p&gt;

  &lt;h3&gt;A simple example&lt;/h3&gt;

  &lt;p&gt;Imagine we&#39;re writing a class for granting access to a reporting functionality based on roles. We don&#39;t have any idea what the API should look like and how to write our Statement, but we know one thing: in our domain the access can be either granted or denied. Let&#39;s take the successful case (just because it&#39;s the first one we can think of) and, starting backwards, start with the following assertion:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;//THEN
Assert.True(accessGranted);&lt;/pre&gt;

  &lt;p&gt;Ok, that part was easy, but did we make any progress with that? Of course we did - we now have a non-compiling code and the compilation error is because of the &lt;code&gt;accessGranted&lt;/code&gt; variable. Now, in contrast to the previous approach (with translating our GIVEN-WHEN-THEN structure into a Statement), our goal is not to make this compile as soon as possible. The goal is to answer ourselves a question: how do I know whether the access is granted or not? The answer: it is the result of authorization of the allowed role. Ok, so let&#39;s just write it down, ignoring everything that stands in our way (I know that most of us have a habit to add a class or a variable as soon as we find out that we need it. If you&#39;re like that, then please turn off this habit while writing Statements - it will only throw you off the track and steal your focus from what&#39;s important. The key to doing TDD successfully is to learn to use something that does not exist yet like it existed):&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;//WHEN
var accessGranted 
 = authorization.IsAccessToReportingGrantedTo(
  roleAllowedToUseReporting);
&lt;/pre&gt;

  &lt;p&gt;Note that we do not know what &lt;code&gt;roleAllowedToUseReporting&lt;/code&gt; is, neither do we know what&#39;s &lt;code&gt;authorization&lt;/code&gt;, but that didn&#39;t stop us from writing this line. Also, the &lt;code&gt;IsAccessToReportingGrantedTo()&lt;/code&gt; method is just taken from the top of our head. It&#39;s not defined anywhere, it just made sense to write it like this, because it&#39;s the most direct translation of what we had in mind.&lt;/p&gt;

  &lt;p&gt;Anyway, this new line answers the question on where do we take the &lt;code&gt;accessGranted&lt;/code&gt; from, but makes us ask further questions:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Where does the &lt;code&gt;authorization&lt;/code&gt; variable come from?&lt;/li&gt;

    &lt;li&gt;Where does the &lt;code&gt;roleAllowedToUseReporting&lt;/code&gt; variable come from?&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;As for &lt;code&gt;authorization&lt;/code&gt;, we don&#39;t have anything specific to say about it other than that it is an object of a class that we don&#39;t have yet. In order to proceed, let&#39;s pretend that we have such a class. How do we call it? The instance name is &lt;code&gt;authorization&lt;/code&gt;, so it&#39;s quite straightforward to name the class &lt;code&gt;Authorization&lt;/code&gt; and instantiate it in the simplest way we can think of:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;//GIVEN
var authorization = new Authorization();
&lt;/pre&gt;

  &lt;p&gt;Now for the &lt;code&gt;roleAllowedToUseReporting&lt;/code&gt;. The first question that comes to mind when looking at this is: which roles are allowed to use reporting? Let&#39;s assume that in our domain, this is either an Administrator or an Auditor. Thus, we know what&#39;s going to be the value of this variable. As for the type, there are various ways we can model a role, but the most obvious one for a type that has few possible values is an enum. So:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;//GIVEN
var roleAllowedToUseReporting = Any.Of(Roles.Admin, Roles.Auditor);
&lt;/pre&gt;

  &lt;p&gt;And so, working our way backwards, we have arrived at the final solution (we still need to give this Statement a name, but, provided what we already know, this is an easy task):&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void
ShouldAllowAccessToReportingWhenAskedForEitherAdministratorOrAuditor()
{
 //GIVEN
 var roleAllowedToUseReporting = Any.Of(Roles.Admin, Roles.Auditor);
 var authorization = new Authorization();

 //WHEN
 var accessGranted = authorization
  .IsAccessToReportingGrantedTo(roleAllowedToUseReporting);

 //THEN
 Assert.True(accessGranted);
}&lt;/pre&gt;</description><link>http://feelings-erased.blogspot.com/2013/07/how-to-start-with-test-not.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>9</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-6972225349772287472</guid><pubDate>Tue, 25 Jun 2013 21:18:00 +0000</pubDate><atom:updated>2013-06-30T17:56:03.010+02:00</atom:updated><title>How to start with a test, not implementation - part 2</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;http://grzesiek-galezowski.github.io/tdd-ebook/&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;(&lt;strong&gt;Note that I use &quot;Statement&quot; instead of &quot;test&quot; and &quot;Specification&quot; instead of &quot;Test Suite&quot; in this post&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://feelings-erased.blogspot.com/2013/06/how-to-start-with-test-not.html&quot;&gt;In the previous part&lt;/a&gt;, I discussed how a good name is a great start for writing a Statement when there&#39;s no production code to invoke. Today, I&#39;ll introduce to you another technique.&lt;/p&gt;

  &lt;h1 id=&quot;sigil_toc_id_31&quot;&gt;Start by filling the GIVEN-WHEN-THEN structure with the obvious&lt;/h1&gt;

  &lt;p&gt;This is applicable when you come up with a GIVEN-WHEN-THEN structure for the Statement or a good name for it (GIVEN-WHEN-THEN structure can be easily derived from a good name and vice versa). Anyway, this method is about taking the GIVEN-WHEN-THEN parts and translating them almost literally into code, then add all the missing pieces that are required for the code to compile and run.&lt;/p&gt;

  &lt;h3&gt;An example speaks a thousand words&lt;/h3&gt;

  &lt;p&gt;Let&#39;s take a simple example of comparing two users. We assume that a user should be equal to another when it has the same name as the other one:&lt;/p&gt;
  &lt;pre style=&quot;padding: 1em; border: dashed thin gray;&quot;&gt;GIVEN a user with any name
WHEN I compare it to another user with the same name
THEN it should appear equal to this other user
&lt;/pre&gt;

  &lt;p&gt;Let&#39;s start with the translation&lt;/p&gt;

  &lt;p&gt;The first line:&lt;/p&gt;
  &lt;pre style=&quot;padding: 1em; border: dashed thin gray;&quot;&gt;GIVEN a user with any name&lt;/pre&gt;

  &lt;p&gt;can be translated literally to code like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;var user = new User(anyName);&lt;/pre&gt;

  &lt;p&gt;Then the second line:&lt;/p&gt;
  &lt;pre style=&quot;padding: 1em; border: dashed thin gray;&quot;&gt;WHEN I compare it to another user with the same name&lt;/pre&gt;

  &lt;p&gt;can be written as:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;user.Equals(anotherUserWithTheSameName);&lt;/pre&gt;

  &lt;p&gt;Great! Now the last line:&lt;/p&gt;
  &lt;pre style=&quot;padding: 1em; border: dashed thin gray;&quot;&gt;THEN it should appear equal to this other user&lt;/pre&gt;

  &lt;p&gt;and its translation into the code:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;Assert.True(areUsersEqual);&lt;/pre&gt;

  &lt;p&gt;Ok, so we&#39;ve made the translation, now let&#39;s summarize this and see what&#39;s missing to make this code compile:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldAppearEqualToAnotherUserWithTheSameName()
{
  //GIVEN
  var user = new User(anyName);

  //WHEN
  user.Equals(anotherUserWithTheSameName);

  //THEN
  Assert.True(areUsersEqual);
}
&lt;/pre&gt;

  &lt;p&gt;As we expected, this will not compile. Notably, our compiler might point us towards the following gaps:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;A declaration of &lt;code&gt;anyName&lt;/code&gt; variable.&lt;/li&gt;

    &lt;li&gt;A declaration of &lt;code&gt;anotherUserWithTheSameName&lt;/code&gt; object.&lt;/li&gt;

    &lt;li&gt;The variable &lt;code&gt;areUsersEqual&lt;/code&gt; is both not declared and it does not hold the comparison result.&lt;/li&gt;

    &lt;li&gt;If this is our first Statement, we might not even have the &lt;code&gt;User&lt;/code&gt; class defined at all.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;The compiler created a kind of a small TODO list for us, which is nice. Note that while we don&#39;t have full compiling code, filling the gaps boils down to making a few trivial declarations and assignments:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;&lt;code&gt;anyName&lt;/code&gt; can be declared as &lt;code&gt;var anyName = Any.String();&lt;/code&gt;&lt;/li&gt;

    &lt;li&gt;&lt;code&gt;anotherUserWithTheSameName&lt;/code&gt; can be declared as &lt;code&gt;var anotherUserWithTheSameName = new User(anyName);&lt;/code&gt;&lt;/li&gt;

    &lt;li&gt;&lt;code&gt;areUsersEqual&lt;/code&gt; can be declared and assigned this way: &lt;code&gt;var areUsersEqual = user.Equals(anotherUserWithTheSameName);&lt;/code&gt;&lt;/li&gt;

    &lt;li&gt;If &lt;code&gt;User&lt;/code&gt; class does not exist, we can add it by simply stating: &lt;code&gt;public class User {}&lt;/code&gt;&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;Putting it all together:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp&quot;&gt;[Fact] public void 
ShouldAppearEqualToAnotherUserWithTheSameName()
{
  //GIVEN
  var anyName = Any.String();
  var user = new User(anyName);
  var anotherUserWithTheSameName = new User(anyName);

  //WHEN
  var areUsersEqual = user.Equals(anotherUserWithTheSameName);

  //THEN
  Assert.True(areUsersEqual);
}
&lt;/pre&gt;

  &lt;p&gt;And that&#39;s it - the Statement is complete!&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2013/06/how-to-start-with-test-not_25.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6040130426871585154.post-7784586110354583017</guid><pubDate>Sun, 23 Jun 2013 09:29:00 +0000</pubDate><atom:updated>2013-06-30T14:22:51.662+02:00</atom:updated><title>How to start with a test, not implementation - part 1</title><description>&lt;p&gt;(this post is adapted from my &lt;a href=&quot;http://grzesiek-galezowski.github.io/tdd-ebook/&quot;&gt;work-in-progress open source TDD tutorial&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note that I use &quot;Statement&quot; instead of &quot;test&quot; and &quot;Specification&quot; instead of &quot;Test Suite&quot; in this post&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://feelings-erased.blogspot.com/2013/06/how-to-start-with-test-not_25.html&quot;&gt;Part 2 of this series is ready!&lt;/a&gt;&lt;/p&gt;

  &lt;p&gt;Whenever I sat down with a person that was about to write their first code in a Statement-first manner, the person would first stare at the screen, then at me, then would say: &quot;what now?&quot;. It&#39;s easy to say: &quot;You know how to write code, you know how to write a unit test for it, just this time start with the latter rather than the first&quot;, but for many people, this is something that blocks them completely. If you&#39;re one of them, don&#39;t worry - you&#39;re not alone. I decided to dedicate this series of posts solely to techniques for starting to write a Statement when there&#39;s no code. I do not use mocks in this series on purpose, to keep it simple. However, all of these techniques are proven to work when using mocks.&lt;/p&gt;

  &lt;h1 id=&quot;sigil_toc_id_25&quot;&gt;Start with a good name&lt;/h1&gt;

  &lt;p&gt;It may sound obvious, but really some people are having trouble describing the behavior they expect from their code. If you can name such behavior, it&#39;s a great starting point.&lt;/p&gt;

  &lt;p&gt;I know some people don&#39;t pay attention to naming their Statements, mainly because they&#39;re considered as tests and second-level citizens - as long as they run and &quot;prove the code does not contain defects&quot;, they&#39;re considered sufficient. We&#39;ll take a look at some examples of bad names and then I&#39;d like to introduce to you some rules of good naming.&lt;/p&gt;

  &lt;h3 id=&quot;sigil_toc_id_27&quot;&gt;Consequences of bad naming&lt;/h3&gt;

  &lt;p&gt;As I said, many people don&#39;t really care how their Statements are named. This is a symptom of treating the Specification as garbage or leftovers - something that just &quot;runs through your code&quot;. Such situation is dangerous, because as soon as this kind of thinking is established, it leads to bad, unmaintainable Specification that looks more like lumps of accidental code put together in a haste than a living documentation. Imagine that your Specification consists of names like this:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code&gt;TrySendPacket()&lt;/code&gt;&lt;/li&gt;

    &lt;li&gt;&lt;code&gt;TrySendPacket2()&lt;/code&gt;&lt;/li&gt;

    &lt;li&gt;&lt;code&gt;testSendingManyPackets()&lt;/code&gt;&lt;/li&gt;

    &lt;li&gt;&lt;code&gt;testWrongPacketOrder1()&lt;/code&gt;&lt;/li&gt;

    &lt;li&gt;&lt;code&gt;testWrongPacketOrder2()&lt;/code&gt;&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;and try for yourself how difficult it is to answer the following questions:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;How do you know what situation each Statement describes?&lt;/li&gt;

    &lt;li&gt;How do you know whether the Statement describes a single situation, or few of them at the same time?&lt;/li&gt;

    &lt;li&gt;How do you know whether the assertions inside those Statements are really the right ones assuming each Statement was written by someone else or was written a long time ago?&lt;/li&gt;

    &lt;li&gt;How do you know whether the Statement should stay or be removed when you modify the functionality it specifies?&lt;/li&gt;

    &lt;li&gt;If your changes in production code make a Statement evaluate to false, how do you know whether the Statement is no longer correct or the production code is wrong?&lt;/li&gt;

    &lt;li&gt;How do you know whether you will not introduce a duplicate Statement for a behavior that&#39;s already specified by another Statement when adding to Specification originally created by another team member?&lt;/li&gt;

    &lt;li&gt;How do you estimate, by looking at the runner tool report, whether the fix for failing Statement will be easy or not?&lt;/li&gt;

    &lt;li&gt;How do you answer a new developer in your team when they ask you &quot;what is this Statement for?&quot;&lt;/li&gt;

    &lt;li&gt;How can you keep track of the Statements already made about the specified class vs those that still need to be made?&lt;/li&gt;
  &lt;/ol&gt;

  &lt;h3 id=&quot;sigil_toc_id_26&quot;&gt;What&#39;s in a good name?&lt;/h3&gt;

  &lt;p&gt;For the name of the Statement to be of any use, it has to describe the expected behavior. At minimum, it should describe what happens at what circumstances. Let&#39;s take a look at one of the names Steve freeman and Nat Pryce came up in their great book Growing Object Oriented Software Guided By Tests:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp;&quot;&gt;notifiesListenersThatServerIsUnavailableWhenCannotConnectToItsMonitoringPort()&lt;/pre&gt;

  &lt;p&gt;Note few things about the name of the Statement:&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;It describes a behavior of an instance of a specified class. Note that it does not contain method name, because what is specified is not a method, but a behavior that has its entry point and expected result. The name simply tells that what an instance does (notifies listeners that server is unavailable) under certain circumstances (when cannot connect to its monitoring port). It&#39;s important because such description is what you can derive from thinking about responsibilities of a class, so you don&#39;t need to know any of its methods signatures or the code that&#39;s inside of the class. Hence, this is something you can come up without before implementing - you just need to know why you created this class and feed on it.&lt;/li&gt;

    &lt;li&gt;
      &lt;p&gt;The name is long. Really, really, &lt;strong&gt;really&lt;/strong&gt; don&#39;t worry about it. As long as you&#39;re describing a single behavior, it&#39;s alright. I know usually people are hesitant to give long names to the Statements, because they try to apply the same rules to those names as method names in production code. Let me make it clear - these two cases are different. In case of Statements, they&#39;re not invoked by anyone besides the automatic runner applications, so they won&#39;t obfuscate any code that would need to call them. Sure, we could put all the information in the comment instead of Statement name and leave the name short, like this:&lt;/p&gt;
      &lt;pre class=&quot;brush: csharp;&quot;&gt;[Fact]
//Notifies listeners that server 
//is unavailable when cannot connect
//to its monitoring port
public void Statement_002()
{
 //...
}
&lt;/pre&gt;

      &lt;p&gt;There are two downsides of this solution: one is that we now have to put extra information (&lt;code&gt;Statement_002&lt;/code&gt;) which is required only by compiler, because every method needs to have a name - there&#39;s usually no value a human could derive from such a name. The second downside is that when the Statement is evaluated to false, the automated runner shows you the following line: &lt;code&gt;Statement_002: FAILED&lt;/code&gt; - note that all the information included in the comment isn&#39;t present in the failure report. It&#39;s really better to receive a report such as: &lt;code&gt;notifiesListenersThatServerIsUnavailableWhenCannotConnectToItsMonitoringPort: FAILED&lt;/code&gt;, because all the information about the Statement that fails is present in the runner window.&lt;/p&gt;
    &lt;/li&gt;

    &lt;li&gt;Using a name that describes a (single) behavior allows you to track quickly why the Statement is false when it is. Suppose a Statement is true when you start refactoring, but in the meantime it turns out to be false and the report in the runner looks like this: &lt;code&gt;TrySendingHttpRequest: FAILED&lt;/code&gt; - it doesn&#39;t really tell you anything more than an attempt is made to send a HTTP request, but, for instance, does not tell you whether your specified object is the sender (that should try to send this request under some circumstances) or the receiver (that should handle such request properly). To actually know what went wrong, you have to go to the code to scan its source code. Now compare it to the following name: &lt;code&gt;ShouldRespondWithAnAckWheneverItReceivedAHttpRequest&lt;/code&gt;. Now when it evaluates to false, you can tell that what is broken is that the object no longer responds with an ACK to HTTP request. Sometimes this is enough to deduct which part of the code is in fault of this evaluation failure.&lt;/li&gt;
  &lt;/ol&gt;

  &lt;h3 id=&quot;sigil_toc_id_28&quot;&gt;My favourite convention&lt;/h3&gt;

  &lt;p&gt;There are many conventions for naming Statements appropriately. My favorite is the one developed by Dan North, which makes each Statement name begin with the word &lt;code&gt;Should&lt;/code&gt;. So for example, I&#39;d name a Statement: &lt;code&gt;ShouldReportAllErrorsSortedAlphabeticallyWhenItEncountersErrorsDuringSearch()&lt;/code&gt;. The name of the Specification (i.e. class name) answers the question &quot;who should do it?&quot;, i.e. when I have a class named &lt;code&gt;SortingOperation&lt;/code&gt; and want to say that it &quot;should sort all items in ascending order when performed&quot;, I say it like this:&lt;/p&gt;
  &lt;pre class=&quot;brush: csharp;&quot;&gt;public class SortingOperationSpecification
{
 [Fact] public void
 ShouldSortAllItemsInAscendingOrderWhenPerformed()
 {
 }
}
&lt;/pre&gt;

  &lt;p&gt;It&#39;s important to focus on what result is expected from an object when writing names along this convention. If you don&#39;t, you quickly find it troublesome. As an example, one of my colleague was specifying a class &lt;code&gt;UserId&lt;/code&gt; and wrote the following name for the Statement about comparison of two identifiers: &lt;code&gt;EqualOperationShouldPassForTwoInstancesWithTheSameUserName()&lt;/code&gt;. Note that this is not from the perspective of a single object, but rather from the perspective of an operation that&#39;s executed on it, which means that we stopped thinking in terms of object responsibilities and started thinking in terms of operation correctness, which is farther away from our assumption that we&#39;re writing a Specification consisting o Statements. This name should be changed to: &lt;code&gt;ShouldReportThatItIsEqualToAnotherObjectWhenItHasTheSameUserName()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And this is the end of part 1 of the series. In the next installment, we&#39;ll take a look at another technique - brute force translation of prose description written with GIVEN-WHEN-THEN structure to code.&lt;/p&gt;</description><link>http://feelings-erased.blogspot.com/2013/06/how-to-start-with-test-not.html</link><author>noreply@blogger.com (Grzegorz Gałęzowski)</author><thr:total>0</thr:total></item></channel></rss>