I’m speaking at Agile Eastern Europe 2010 in Kyiv, Ukraine. Please join me at my master class Agile Design: Beyond the Basics and my session Integrated Tests Are A Scam.

6 days ago
Comments
Blaming mock objects for your design and testing troubles is a lot like a fat guy blaming his pain on the situps he’s doing.

Blaming mock objects for your design and testing troubles is a lot like a fat guy blaming his pain on the situps he’s doing.

1 week ago
Comments

Irregular Stand-Up: Rails and PostgreSQL’s logging

I would like to silence PostgreSQL’s STDERR warnings from time to time when I run my specs. Ideally, I’d like to change the log level to ERROR by default, but be able to pass the log level as a parameter on the command line when I need more information. I know that I can invoke the client_min_messages= method on the PostreSQL adapter, but I don’t know how to get an instance of the current database adapter. Can my fellow Rails programmers guide me here?

1 week ago
Comments

Make your checks (or tests or specs) less brittle

I found a little situation where I changed the way I checked something in a specification in order to avoid brittleness, and I wanted to share that with you. I won’t bore you with the details, because it relates to tax, but I will tell you that I want to label an entry as posted in a certain period if the entry matches another entry. This leads to two simple checks: copy the “posted in” label when the entries match and don’t when they don’t. I originally wrote those checks like so:

Notice the “doesn’t match” spec checks that the log_entry is not posted (at all). That doesn’t quite match what I mean. I don’t care whether it’s posted; I just don’t want it to be posted when the non-matching entry was posted. By checking that it is not posted, I assume that entries start out life as not posted, and I have no reason to guarantee that invariant yet.

I find my designs benefit from making the weakest assumptions possible. This makes a change less likely to ripple through the system. Too many assumptions lead to viscosity (in the Bob Martin sense).

So far, I am only willing to assume that the log_entry is not posted in the database_entry’s posting period.

Of course, this means that I should verify that log_entry wasn’t already posted in 2007Q3. This means that I should set the posted_in property to something other than 2007Q3. Unfortunately, I haven’t needed to make the posted_in property writable yet, and I have no easy way in the parse method to express that posted_in is "anything except 2007Q3".

Is the great chess writer Irving Chernev liked to say, “There’s a clue in that last sentence.”

Why do I create log_entry with parse? I don’t need that here; I pasted it from a previous specification. I could simplify the specification and avoid resorting to adding unnecessary code by creating the entry directly.

I think I’ve made these specifications as effective as I can: I find them easy to understand and I believe they resistant irrelevant changes quite well. We’ll just have to see.

2 weeks ago
Comments

Now that’s dedication…

2 weeks ago
Comments

Avoiding brittle specs by clarifying intent

I had one of those annoying moments with setting an expectation on a message (method invocation) that makes some people curse mock objects. In doing some performance optimization on my Rails project, blog.jbrains.ca, I changed the implementation of the “Recent Postings” feature. This is the section of my site that displays the recent postings, oddly enough.

Recent Postings at jbrains.ca: you'll have to take my word for it

I found a simple-enough optimization: avoiding the classic n+1 SQL problem by adding an :include => :categories to my find method. Sadly, doing this made a spec fail.

Damn brittle mocks!!

Or… damn careless programmer. What do I want this spec to check for me? I want to know that when I ask for 10 articles, the model only selects 10 articles. I don’t consider eagerly loading the categories an essential part of the behavior, so I decided to change the spec to better reflect my intent. (That’s the third element of simple design, as you know.) Fortunately, RSpec makes this quite easy. It took longer to find the solution than to apply it.

By adding hash_including(expected_hash_items) I allow for additional options, a ubiquitous feature of Rails design. I will try using hash_including() as a matter of course in writing specs for a while and see whether that hurts me. I suspect it won’t. I will have trouble remembering, though. I will have even more trouble stopping myself from retrofitting all my old specs.

Nah. I have to deliver this feature. My customer’s on my back about it.

2 weeks ago
Comments

Use your singletons wisely: ten years later

I recently received this comment at IBM DeveloperWorks about my now-decade-old article, Use your singletons wisely. I really like knowing that people continue to read that article, since it was the first I published online somewhere other than my own web site.

Brent Arias, also known as mystagogue, wrote:

There is such a thing as singletons, in some languages, that can be “property” dependency injected, which essentially nullifies the suggested reason (viz. testability) for avoiding them (I do this with C#). Also, Liskov Substitution is not violated by singletons, because Liskov Substitution does not apply to constructors (which in part is why there is no such thing as “virtual constructors”). Finally, dependency injection is not without its own hazards. For example, many interim classes are forced now to take dependencies they don’t need, simply to pass them on to child classes which do need them. As such, dependency injection actually increases coupling between classes!!!

I’d like to thank Brent for his comment. Of course, I didn’t know then what I know now, so I didn’t mention the points that Brent raised in his recent comment. I’d like to address those points now.

First, Brent says that since he can inject a dependency through a property in C#, there is no testability problem. I disagreed with this in JUnit Recipes, recipes 14.3 and 14.4, which cover testing singletons and their clients. I agree that being able to inject the singleton instance makes run-time substitution in the tests possible, it defeats the purpose of designing the class as a singleton. Yes, you can resort to making the setInstance() method or Instance property writable only in the tests, but this serves only to complicate the design, rather than simplify it, and so I’d typically prefer to use this as an intermediate step towards a simpler design.

Next, Brian says that since the Liskov Substitution Principle does not apply to constructors, then a singleton-based design does not violate the principle. I had never thought about this before, so I researched the topic a little. The principle states that any property provable about a type must also be true of any subtype of that type. I suppose that, since constructors belong to the type class and not objects of the type, then Brent is correct: LSP does not apply to constructors. Even so, I had written this:

[…] any change in how the supplier class is instantiated ripples into the client class. This violates the Liskov Substitution Principle, which states that you should allow any application the freedom to tell the client class to collaborate with any subclass of the supplier.

I had written about the consequences of LSP, and not the principle itself, in rather a sloppy fashion. While one can subclass a singleton in a way that respects LSP, in order to use that subclass, one would have to make a choice between two poor alternatives: change clients to invoke Subclass.getInstance() instead of Superclass.getInstance() or change Superclass.getInstance() to become a proper Factory for the Superclass hierarchy. Choosing the first option violates the benefit of LSP, if not LSP itself: when you violate LSP you make changes that ripple out into your client, and so to avoid affecting your client, among other things, respect LSP. Choosing the second option leads you to a Singleton/Factory hybrid in which Superclass knows about Subclass, violating even more fundamental design principles, like Open/Closed. I don’t like either choice. I wish I had written this instead of what I wrote in the original article.

Finally, Brent says that, with dependency injection, “many interim classes are forced now to take dependencies they don’t need, simply to pass them on to child classes which do need them”. I agree with Brent, but strongly point out that dependency injection uncovers symptoms like these of deeper design problems, rather than creating these design problems in the first place. Unfortunately, I don’t have a concrete example to offer you, so I have to resort to one of those hopelessly abstract examples. I hope you’ll bear with me. If I find a better example, I’ll use it.

Consider three classes, unimaginatively named A, B and C. In our design, A uses B, and then B uses C. Since this design doesn’t yet inject dependencies, we have something like this:

class A {
    public A() {
        this.b = new B();
    }
}

class B {
    public B() {
        this.c = new C();
    }
}

So far, so good. Now we want to switch to a dependency injection-based design to make it collaborators more pluggable. (I won’t bother with the reasons here; in a purely abstract example, there are no reasons.) This means that I first inject C into B through its constructor:

class B {
    public B(C c) {
        this.c = c;
    }
}

Now A needs to give B a C, but where does the C come from?

class A {
    public A() {
        this.b = new B(new C());
    }
}

This doesn’t look right, so we could decide to make the client give A a C, so that A can pass that on to B:

class A {
    public A(C c) {
        this.b = new B(c);
    }
}

class Client {
    someMethod() {
        A a = new A(new C());
    }
}

But now, of course, we have the case where A knows about C even though A doesn’t use it directly. If I understand Brent correctly, then this is his objection. One problem: why does A create the B directly? Why not inject that, too?

class A {
    public A(B b) {
        this.b = b;
    }
}

Now the client, which was already creating a C, simply creates a B, too:

class Client {
    someMethod() {
        A a = new A(new B(new C()));
    }
}

This way, A need not know anything about C, although if A eventually does need to use C directly, it can easily do so:

class Client {
    someMethod() {
        C c = new C();
        A a = new A(new B(c), c);
    }
}

This duplication, however, leads me to ask a few questions:

Do A and B use C differently? If they do, then maybe I should split C into two classes, D and E:

class Client {
    someMethod() {
        A a = new A(new B(new D()), new E());
    }
}

Do A and B use C for a similar reason? If they do, then maybe A and B duplicate some effort. Since A is B’s client, I would probably move that behavior from B to A, so that B no longer uses C at all:

class Client {
    someMethod() {
        A a = new A(new B(), new C());
    }
}

Is there some combination of both? If so, then likely I need to do both. Fortunately, that’s just another formulation of the first possibility.

There might be more questions, but that will do. While injecting the dependency appeared to make the classes more tightly coupled, it simply revealed the coupling that already existed. A was already tightly coupled to B and B to C. When we tried to inject the dependency, we made that coupling more explicit and easier to remove.

So thanks, Brent, for your comment, as it gave me an opportunity to follow up on my thinking about Singletons and design. I hope this response helps you understand why I don’t worry about the issues you brought up. Thanks, as well, for pointing out the error in my exposition about the Liskov Substitution Principle. I freely admit that, as a new face, I mostly wanted to sound smart.

1 month ago
Comments

I asked, and Ben Rady answered. Contract Tests work the way I’d expect in JUnit 4.

3 months ago
Comments

Corey Haines interviewed me at the Golden Tulip Times Hotel in Bucuresti, Romania on the topic of Primitive Obsession: the dangers of using simple data types to represent complex information.

6 months ago
Comments

Meta: I need your opinion about reading this blog with RSS

Dear Readers, as you know, I post a lot of code samples in these articles and I use gists to do it. When I embed code samples in these articles, I use Javascript to do it, and almost certainly your RSS feed reader doesn’t render the code samples correctly. I have proposed a solution, but I want your feedback.

I have edited RSpec, have_tag(), Spec::Matcher, and Nokogiri to include links to the code samples for those browsers that have disabled Javascript. I have to duplicate a lot of code to make that happen, which I want to eliminate, but first I wanted to know how much you liked this, so please help me perfect the way I display code samples to browsers without Javascript.

Add a comment with what you like about my solution, and how you might improve it. Either subscribe by a standard RSS feed reader or disable Javascript in your browser (at least for thecodewhisperer.com, and of course, only temporarily), read the article I’ve edited and tell me if you have a better idea. Please, if you suggest something, then include a link to how to do it. I prefer not to break new ground here.

Thank you for your help.

6 months ago
Comments

Blue Theme by David