Comments

I apologise for the pompous title; I wrote it just for fun. If this “demystifies” anything, I’ll consider that a coincidence.

Of the SOLID principles, the most pompous-sounding is the one named for a person: Barbara Liskov. I don’t label her pompous – I never knew her – but of those five principles, only LSP has a common formulation that looks like the kind of mathematics so many programmers like to avoid, while others flock to.

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

Or, if you prefer:

Subtypes must not change any supertype’s significant behavior. Here, “significant behavior” means behavior upon which clients of those objects expressly depend.

If you like the language of contracts, then you might prefer this formulation: Read on →

Comments

Just a fun link today.

I read about Design by Contract first, didn’t understand it, then read about Test-Driven Development and began to think of TDD as a kind of DbC by example. Accordingly, I have respect for both practices and have even combined them on projects. Moreover, “Integrated Tests are a Scam” amounts to little more than Isolating Layers by Contract.

When I saw the Vigil programming language today, I fell in love. To quote its README:

When a Vigil program is executed, Vigil itself will monitor all oaths (implorations and swears) that have been made. If an oath is broken, the offending function (the caller in the case of implore and the callee in the case of swear) will be duly punished.

I know for sure I’ll try Vigil at the next Code Retreat.

Comments

I really like Octopress, which is built on Jekyll. You can read a lot of articles about the advantages and disadvantages of pre-baked blogs, so I won’t bore you with those details. Instead, I’ll bore you on the subject of the one feature I miss with pre-baked blogs: scheduling posts for later publication.

When I switched to a pre-baked blogging tool like Octopress, I gave up the ability to upload a post, but publish it later. Well, I didn’t really give it up entirely, but pre-baking my blog means thinking of my blog as a static web site, rather than a dynamic one, which implies having to re-deploy every time I wanted to change its content. This makes scheduling posts in the future a bit more tricky.

Using Heroku and its read-only file system make it even trickier, since I can’t regenerate the blog in production.

I just wanted to share my solution with you, in case it interests you. Read on →

Comments

I’m pleased to announce that I have started writing a new book, entitled Responsible Design for Android. I really envision this as a series of short books, not wanting to repeat the 750-page behemoth that was JUnit Recipes.

In Part 1, Dancing with the Android SDK, I explore a sensible architecture for the basic Android app, emphasising context independence to avoid letting the Android framework swallow my app whole. I use tactics that have worked to great effect in working with older frameworks such as Servlets and EJB.

I toyed with the idea of writing an Android app in Ruby using Rhodes, but decided to return to my roots and Java, so if you’re writing Android apps in Java, and have run into maintenance or extensibility problems, then I’m writing this book for you.

I say “I’m writing”, because I’ve decided to use LeanPub to compose and publish the book. This means that you can read the book as I write it, and your feedback and questions could help direct its contents. As of this writing, I’ve published three versions of the book, and plan to publish a new version approximately twice per week until I’ve written enough.

The sooner you purchase the book, the less you pay, and once you purchase the book, you receive all future updates free of charge. I have already raised the minimum price of the book once, as I have published more content.

If you’d like to take a look, click here to download a sample chapter, then click here to buy the book.

Comments

I’m coding like it’s 2000, meaning in Java. I thought I’d never see anything new regarding writing a test that expects to catch a specific exception. I saw something new, and I wonder who else has independently discovered it.

(TestingIoFailure.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
public void ioFailure() throws Exception {
    final IOException ioFailure = new IOException("Simulating a failure writing to the file.");
    try {
        new WriteTextToFileActionImpl() {
            @Override
            protected FileWriter fileWriterOn(File path) throws IOException {
                return new FileWriter(path) {
                    @Override
                    public void write(String str, int off, int len) throws IOException {
                        throw ioFailure;
                    }
                };
            }
        }.writeTextToFile("::text::", new File("anyWritableFile.txt"));
        fail("How did you survive the I/O failure?!");
    } catch (IOException success) {
        if (success != ioFailure)
            throw success;
    }
}

Please add your comments at gist.github.com.

(If you can’t see the code snippet inline, then click here.)

Comments

I wish that I could take credit for this article, but I can’t. Instead, I have to credit two people: Lasse Koskela and Miško Hevery. I credit Lasse for writing the manuscript that led me to Miško’s article. Look for Lasse’s upcoming book Unit Testing in Java at Manning Publications’ site. Let me summarise Miško’s article here, then you can read the details at his blog.

Why would I simply summarise someone else’s article on this site? Isn’t that dishonest? Not in this case: Miško wrote essentially the same thing that I say over and over again in my own articles and in my training classes. I consider it unfortunate that he and I have never met nor worked together. We really should. You should read his stuff.

So… 10 ways to kill your design.

  1. Instantiate Services wherever the hell you want.
  2. Grab what you want when you want it.
  3. Do real work in your constructors.
  4. Publicise state.
  5. Embrace singletons.
  6. Make methods static. (Admittedly, this is more of a problem in Java/C# than Ruby/Python.)
  7. Inherit implementation.
  8. Reimplement polymorphism.
  9. Mix Services and Values.
  10. Keep conjunctions in your variable, method and class names.

Read more about the problems that these “techniques” cause.

Comments

Dale Emery [We might choose to] write tests so that a failure in a predecessor test causes dependent tests not to execute. In object tests, we do this by writing a test method with multiple assertions. – Dale Emery

When multiple assertions check very tightly related things, I don’t mind them, but when they check relatively loosely related things, they act as integrated tests for multiple behaviors that we should consider separating. This is even subtler than the simpler idea of “one action per test”.

If you’d like a Novice algorithm to follow:

  1. Look for any test with multiple assertions.
  2. Move those assertions to the bottom of the test. (If they aren’t already at the bottom, then you might have more than one action per test; this refactoring will help you discover that.)
  3. Extract all the assertions together into a single method.

Now look at the new method. How many different objects does the method use?

If it’s more than one, then you almost certainly have unrelated assertions in the same place, so consider splitting the unrelated assertions into separate methods, then split the test into two so that each test invokes one of the two new separated assertion methods.

If your new assertion method uses only one object, then it might not be so clear whether those assertions are related. You can try this simple test: put all the values you’re checking in your assertions into a single object. Can you think of a good name for it? If yes, then perhaps you’ve just identified a missing abstraction in your system; and if not, then perhaps the assertions have too little to do with each other, in which case, try the trick in the preceding paragraph.

I apologise for not having a good example of this right now. If you point me to one, I’ll analyse it in this space.

Comments

The 30-second version

  • Where did that yak come from?
  • When you try to learn a new library at the same time as explore the behavior and design of your application, you slow down more than you think.
  • When you can’t figure out how to make the new library work for this thing you want to build, you might spend hours fighting, debugging, swearing.

Stop. Write a Learning Test.

  1. Start a new test suite, test class, spec file, whatever you want to call it.
  2. Write a test that checks the things you tried to check earlier with debug statements.
  3. Write a test that has nothing to do with your application and its domain.
  4. Remove unnecessary details from your test.

When this test passes, then you understand what that part of the library does. If it behaves strangely, then you have the perfect test to send to the maintainers of the library.1

Read on →
Comments

The 30-second version

  • Invert the dependency on a Service, moving the new statement up one level in the call stack.1
  • Repeat for all dependencies on Services until the corresponding new statements arrive at your application’s entry point. The entry point now creates a large object graph of all your Services in its initialise function.
  • Remove duplication in EntryPoint.initialise():
    • Instantiate common objects only once, passing them into the necessary constructors, replacing any Singletons with plain objects.
    • Extract the choice of implementation for each Service interface into a lookup table mapping interface type to implementation type.
    • Externalise the lookup table to a file, if you like.

Now you have a customised Dependency Injection Container for your application. To go a little farther:

  • Remove duplication in EntryPoint.initialise() among three applications.

Now you have a generic Dependency Injection Container that probably provides 80% or more of the features you’ll ever need.

I recommend trying this incrementally. Think of the new statements flowing up the call stack, into the entry point, then changing from code into data. Nice, no?

The Details

I don’t have much to add.

I hope this helps to demystify dependency injection containers. To read about the technique of injecting dependencies, I refer you to one of my articles and then a trusty web search.

This technique applies the Dependency Inversion Principle repeatedly to move the choice of implementation for an interface up the call stack. This way, concrete things depend on abstract things.

Removing duplication in the entry point respects the principle Abstractions in Code, Details in Data, but it does rely on reflection, which can cause some problems. All the better not to scatter this reflection throughout the code causing a serious cohesion problem. Using reflection like this, all in one place, helps balance using a powerful technique with a design that everyone can understand.

Now you know what about 70% of what a dependency injection container does. You can build one. Even if you don’t go that far, the Dependency Inversion Principle will help reducing coupling and highlight cohesion problems in your design. It provides another set of mechanics to practise on the way to becoming an accomplished designer.

  1. I mean “Service” in the Domain-Driven Design sense.

Comments

After running a handful of Legacy Code Retreats I’ve had the chance to try a number of exercises related to rescuing legacy code. I’d like to share one that has met with very positive reactions from people: extracting pure functions. I use the term pure function to describe a function that only operates on local variables and parameters, but does not touch any state outside the function. No object fields, no global data. I have very little experience in functional programming, so I hope I use the term in a standard way.

No doubt you already know about the Composed Method design pattern, which we commonly use to help understand code as we read it. Most commonly you encounter a block of code with a comment that describes what that code does. You then extract that block of code into a method whose name matches the comment. I’ve used this technique for well on a decade to raise the level of abstraction in code, help code document itself, and eliminate misleading comments. While introducing these methods helps me read the code, it sometimes hides the tangle of dependencies that makes separating responsibilities so difficult. For this reason, I recommend trying to extract pure functions instead.

To introduce a pure function, start with a block of code and extract a method for it. Now look at all the fields and global variables that the method reads and introduce each one as a parameter to the method. Now look at all the fields and global variables that the method writes to and turn these into return values. Where the old code invokes the new function, assign each new return value to the corresponding field or global variable. You know you’ve done this correctly if, of course, the overall behhavior of the program hasn’t changed and you can mark the new function as static or whatever your language calls a class-level function.

In some languages, like Java, you’ll have to introduce a new little class to allow you to return multiple values from the new function. If you don’t want to do that right away, then return a Map of return values. Once you see that you need to return similar Maps from different functions, consider replacing those Maps with a new class. Perhaps that new class will attract some code!

When I’ve used this technique, two key things have happened: either I’ve noticed duplication in the parameter lists of the new functions or introducing a parameter has changed the behavior of the system. In the first case, I introduce Parameter Objects for the duplicated parameters, which then probably attract code and become useful domain objects. In the second case, I’ve detected temporal coupling, which requires me to separate the function into two smaller ones so that some output from the first becomes input to the second. This helps me uncover cohesion problems, usually of the type of different things written too close together.

I realise that an example would help right about now, but I would rather create some screencasts than write out examples in code, but I don’t know when exactly I intend to do that. I wanted to share this idea with you without waiting for the energy to put together a suitable screencast.

I invite you to try introducing pure functions into some legacy code and practising the technique as a kata. Get used to the various maneuvers, like introducing Parameter Objects or Return Value Objects or solving temporal coupling by splitting the function in two. It sounds crazy, but I’d like to try a Legacy Code Retreat where we practise only this technique all day. I don’t know whether anyone else would find it valuable enough to try it together for an entire day, over and over and over.

Would you? Add your comments below.