Migrating my blog

I have decided to move all entries on my personal blog related to software development over to my professional website. This puts my technical content in one place and makes it easier to compose and manage my blog entries.

Going forward, I will only post non-technical articles on my personal blog. Anything related to software development will go on my professional website. I am leaving existing technical posts here, but have copied their content to my professional blog.

Unfortunately, my new blog solution is not set up to automatically email subscribers with new blog entries. If you wish to continue to be apprised of new technical blog entries, please follow me on Mastodon or on LinkedIn. I will mention new blog entries in both places. Thank you!

Posted in Uncategorized | Leave a comment

Exploring the AWS Lambda SDK in Rust

Recently the general availability of the AWS SDK for Rust was announced. I thought this might be a good occasion to write about my recent experiences writing and testing with AWS Lambda and Rust.

When I started my freelancing business, I set up a website with a contact form. I looked around at existing solutions, but couldn’t find anything which quite ticks all the boxes. So, I decided to write my own backend.

The job of the backend is pretty simple: get the data from the form, pack them in an email, and send that email to a specific destination. It also needed a way to protect from bots, such as a captcha.

For the backend itself, I chose AWS Lambda. This makes sense given the low traffic volume I expect. The AWS API Gateway exposes the backend as an HTTP endpoint. The lambda sends emails via SMTP using the AWS Simple Email Service. I use a (privacy- and accessibility-friendly) captcha solution called FriendlyCaptcha. Credentials for both of these are stored in the AWS Secrets Manager.

Writing a Lambda in Rust

I decided to write the lambda in Rust to see how the AWS Rust SDK works. It runs as an ordinary binary which can process any number of lambda events. It has some modest boilerplate to call into the AWS SDK to set up a listener for lambda events and invoke a handler on each event. It runs in the Tokio runtime and uses non-blocking variants of all APIs, so each running instance could actually handle a lot of traffic if it needed to.

use lambda_http::{
    http::StatusCode, run, service_fn, Body, Error, Request, Response
};

#[tokio::main]
async fn main() -> Result<(), Error> {
    let handler = ContactFormMessageHandler::new().await;
    run(service_fn(|event| handler.handle(event))).await
}

struct ContactFormMessageHandler {...}

impl ContactFormMessageHandler {
    async fn handle(&self, event: Request) -> Result<Response<Body>, Error> {...}
}

The request and response are essentially the HTTP request and response received from, respectively sent to the user agent. The Lambda SDK provides facilities for parsing the payload and constructing the response:

#[derive(Deserialize)]
struct ContactFormMessage {
    name: String,
    email: String,
    subject: String,
    body: String,
}

async fn handle(&self, event: Request) -> Result<Response<Body>, Error> {
    let Some(message: ContactFormMessage) = event.payload()? else {
        return Ok(Response::builder()
            .status(StatusCode::BAD_REQUEST)
            .body("Could not extract message payload".into())
            .unwrap());
    };
    match self.process_message(message).await {
        Ok(_) => Ok(Response::builder()
            .status(StatusCode::OK)
            .body("Message sent".into())
            .unwrap()),
        Err(_) => Ok(Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .body("Could not send message".into())
            .unwrap()),
    }
}

async fn process_message(message: ContactFormMessage) -> Result<(), Error> {...}

This Rust program is compiled to a binary, packed into a Docker image, and uploaded to AWS. The Cargo Lambda tool builds and deploys the lambda automatically. AWS Lambda then launches instances of the binary to handle incoming events. Each instance typically runs for a short time, shutting down on its own if it is no longer needed to serve traffic.

Cross-compiling for arm64

AWS Lambda allows running functions on either the x86-64 architecture or arm64. The latter has somewhat lower costs, so I decided to target it to see how well that goes. This means compiling the lambda for the arm64 architecture. Nominally this requires just passing the flag --arm64 to the cargo lambda build command.

There is one twist, however. By default, the SMTP and HTTP clients my lambda uses rely on OpenSSL for TLS support. This means that to cross-compile the lambda, one must cross-compile the OpenSSL C++ library itself. This would mean going down a rabbit hole.

Fortunately, this is easily solved by configuring the SMTP and HTTP dependencies to use Rustls, a pure Rust TLS implementation. This requires just flipping a few feature flags in Cargo.toml:

[dependencies]
...
lettre = { version = "0.11.1", features = ["rustls-tls", "tokio1-rustls-tls", ...], default-features = false }
reqwest = { version = "0.11.22", features = ["rustls", "tokio-rustls", "__tls", "__rustls", "rustls-tls", ...], default-features = false }
...

Testing the lambda

I felt this project wouldn’t be complete without exploring how to perform automated testing on the solution. The lambda is the kind of component which gives unit testers headaches. It has relatively little business logic but a lot of integrations with external systems. The business logic which does exist is pretty critical, though. If something goes wrong and the message can’t go out, the user needs to see an alternative way to reach out to me. There’s just enough in there to trip one up when refactoring. At the same time, experience shows that it’s at the external integrations that things tends to go wrong.

Thus I wanted to cover as many of the external integrations as possible with tests, and in a way which is as close to a production setup as possible. I also wanted to cover the business logic without the tests running too slowly. With these requirements in mind, I created two test suites:

  • a single end-to-end integration test covering the happy path, and
  • a set of less integrated tests covering various error conditions.

The end-to-end test uses LocalStack running in Testcontainers to simulate real AWS services. The test runs the Lambda inside LocalStack and invokes it using the AWS SDK. It sets up its own fake SMTP server and fake FriendlyCaptcha verification server. The AWS Secrets Manager is provided by LocalStack. The following diagram summarises the setup. The component under test is in blue, components written as part of test are in green, and components supplied by LocalStack are in red.

The test invokes the Lambda with a valid request. It verifies that the email was sent through the simulated SMTP server and that the response is correct.

The major complication in this test setup is that the component under test runs inside a Docker container (managed by the Lambda environment), which itself runs inside another Docker container (LocalStack running with Testcontainers). This makes instrumentation of the component under test quite difficult. One must communicate with the lambda that it should connect with the fake SMTP and FriendlyCaptcha implementations and not attempt to use the real AWS services. I solved this with environment variables, which is not ideal but works well enough.

The test unfortunately leaves out the API gateway. This is because the required features of LocalStack are not available in the free version. For the same reason, it uses the Rust crate mailin-embedded for the fake SMTP server, simulating the AWS Simple Email Service.

The other tests have a much simpler architecture. They do not use LocalStack at all but instead invoke the event handler directly. They still use the fake SMTP server and FriendlyCaptcha running as in-process servers. But they replace the secrets manager with a test double.

To facilitate the test double for the secrets manager, I introduced a bit of hexagonal architecture in the lambda. The trait SecretRepository abstracts away communication with the secrets manager:

#[async_trait]
pub trait SecretRepository {
    async fn open() -> Self;
    async fn get_secret<T: DeserializeOwned>(
        &self,
        name: &'static str,
    ) -> Result<T, lambda_http::Error>;
}

The implementation for the AWS Secrets Manager is a straightforward wrapper over the AWS SDK. The unit tests use an implementation FakeSecretRepository which allows the test to provision and remove secrets as needed.

To install the correct version in the event handler, the lambda event handler use generics:

struct ContactFormMessageHandler<SecretRepositoryT: SecretRepository> {
    secrets_repository: SecretRepositoryT,
    ...
}

impl<SecretRepositoryT: SecretRepository> 
    ContactFormMessageHandler<SecretRepositoryT>
{
    async fn new() -> Self {
        let secrets_repository = SecretRepositoryT::open().await;
        Self {
            secrets_repository,
            ...
        }
    }

    ...
}

With this setup, the unit tests can access and manipulate all of the external systems the lambda backend uses. They can simulate any error condition which may come up and assert on the correct behaviour.

pub struct FakeSecretRepsitory(HashMap<&'static str, String>);

impl FakeSecretRepsitory {
    pub fn remove_secret(&mut self, name: &'static str) {
        self.0.remove(name);
    }
}

#[async_trait]
impl SecretRepository for FakeSecretRepository {...}

type ContactFormMessageHandlerForTesting = 
    ContactFormMessageHandler<FakeSecretRepsitory>;

#[googletest::test]
#[tokio::test]
async fn returns_contact_page_when_secrets_service_fails_for_smtp() {
    // ...other setup...
    let mut subject = ContactFormMessageHandlerForTesting::new().await;
    subject.secrets_repository
        .remove_secret(SMTP_CREDENTIALS_NAME);

    let response = subject.handle(event).await.unwrap();

    expect_that!(response.status().as_u16(), eq(500));
    expect_that!(
        response.body(),
        points_to(matches_pattern!(Body::Text(contains_substring(
            "Something went wrong"
        ))))
    );
}

Conclusion

This project was a worthwhile exploration of the AWS SDK for Rust, both using it and testing against it. While it was a bit more challenging than, say, a JavaScript runtime, it wasn’t too hard to get everything working. The biggest challenges were in the testing setup, but I was able to achieve fairly good coverage in the end. All in all, I’m satisfied with the result.

The complete solution is available on GitHub.

See also this blog post for another exploration of AWS Lambda with Rust with more information on using Lambda with Terraform as well as manual invocation through Cargo Lambda.

Posted in Uncategorized | Tagged , , , | Leave a comment

Agile like you mean it?

Recently I watched a talk by the author and consultant Allen Holub. He describes how what passes for “agile” in today’s organisations has nothing to do with the original thinking behind the concept. While I agree with much of his criticism, I find one key aspect deeply unsatisfactory, and worry that it could be counterproductive, even dangerous, if applied in practice.

Holub’s ideal vision

There are a lot of interesting ideas to digest in there and I do recommend listening to what he has to say. Scrum creates suffocating process and locks developers for hours in often pointless meetings and rituals. SaFE is even worse — it’s probably the polar opposite of true agility. OKRs often devolve into top-down task assignment. And I particularly appreciate his rejection of story point estimates in favour of just counting stories.

Allen Holub advocates making small, incremental changes, each intended to provide customer value, and getting customer feedback rapidly. He claims that this should happen on the scale of hours or days, not weeks or months. Every change should be in the service of the needs of the customer. He considers this to be the core of agile software development.

Of course, software does need to be refactored over time, and he is well aware of that. However, he feels that this should happen in the context of these incremental changes — “on the side,” one might say. This is similar to what Robert C. Martin writes in his book Clean Agile:

We do not create a project specifically to change the design. We do not reserve time in the schedule for such large refactorings. Instead, we migrate the code one small step at a time, while continuing to add new features during the normal Agile cycle. (p. 125)

So it seems to be a shared perspective among some of the original thought leaders behind Agile.

My story

At some point a few years ago, I was working for a large, reputable company with a well-regarded engineering organisation. A product was dropped into my lap and I suddenly had the responsibility to keep it running and make improvements to it. It was poorly designed and engineered, and its product story was a mess. But it was business critical.

Despite that, the department showed no interest in investing in it. And it desperately needed investment:

  • It couldn’t scale with the data volumes it had to process. If we had done nothing, critical processes would have soon just stopped working.
  • It depended on a critical way on other systems which were deprecated and marked for turndown. Had we not migrated the product away from these, the entire product would have stopped working.
  • It had serious bugs we could not fix due to fundamental problems in the architecture and data model.
  • Other bugs and customer issues took weeks to investigate and weeks more to fix. This was not just due to messy code, but to a failed architecture which hindered writing new tests and reasoning about the product’s behaviour.
  • Finally, there were unmet customer needs which were just piling up.

It took a herculean effort to clean up the mess. Taken together, the work amounted to an (in place) total rewrite of the product. The technical debt was too entrenched to fix “on the side” as we were delivering features. It needed real investment and a real strategy to tackle. The key migrations we needed to make were not customer-visible, so delivering them incrementally and getting customer feedback was impossible. One might say it was a kind of architectural debt.

Probably 90% of of the team’s capacity over the time of my tenure went to dealing with the architectural debt and its consequences. How could we have approached this situation whilst being “agile” as Holub and others define the term?

The idea of incremental changes, all bringing customer value, sounds great in theory: one gets extremely fast feedback and can adjust to changing needs quickly. But consider what this requires:

  • The entire engineering organisation has the right balance of experienced and inexperienced software engineers.
  • These teams are professionally superb and do not succumb to pressure to deliver products with subpar quality.
  • This has been true for the whole history of the organisation, or at least for the whole lifetime of all products still in active development.

And even if all of this is true, it still may not be enough. Requirements change unpredictably, and one can find oneself with a business-critical product which has been designed into a corner.

Taking Holub at his word, the way were worked through my tenure was not agile. One therefore might be led to think that one should therefore not tackle architectural debt. Lacking a way to ram this type of work into the agile mold, one may conclude that it were not worth doing. But that thinking is naive and dangerous. At best, the software will rot. In our case, it would have stopped working altogether, completely on its own, after a few months!

More generally, when I look back at my career, the vast majority of my capacity has been spent on large, multiquarter or multiyear programmes which only start delivering real value to the customer after a lot of investment has gone in. They may not require every detail to be designed and specified up front, but they require some up front design, planning, and strategy. They don’t need 100% of developer resources, but they need some dedicated allocation of resources. Cases where we could realistically have delivered value incrementally were mostly quite trivial: fix a UI bug, add a checkbox here, change this colour and so on.

I’ve read several works of the thought leaders in Agile and none seem to have a satisfying answer for this problem. Their mantra is, “just do everything right, be professional, and your problems will go away!”

Conclusion

So, what is their answer? From what I have read, I’m driven to one of two conclusions:

  • Don’t work on such products as described above. Let them be someone else’s problem. But this feels really unsatisfactory: the work still needs to be done. Much of the software development work which needs to be done just doesn’t fit in the agile box as defined by Nolub and others, and most of what does is the kind of stuff a recent university graduate could easily handle.
  • Maybe not everything has to be “agile”. Some projects just can’t be agile, and that’s okay. But, if it’s not agile, then what? What’s a viable approach for programmes whose value realistically cannot be delivered in increments every few hours or days?

In my experience, what Holub et al. call “agile” can only function for a relatively small set of idealised real-world situations. In practice, most engineering programmes require some upfront planning and strategy, and the customer might not be able to see and appreciate the work being done for much of the development process. That’s just reality. Our software development mindset — whether agile or not — has to be able to handle it. Just as with Scrum and SaFE, I worry that the appeal of calling one’s approach “agile” will lead teams to exactly the opposite.

Posted in Uncategorized | Leave a comment

Demystifying trait generics in Rust

One of the things I’ve always found mysterious about the Rust type system is the distinction between generic type parameters and associated types. They both allow one to define a trait with a placeholder type. When does one choose one over the other?

I recently ran into a surprising bug in GoogleTest Rust. The investigation of the cause and the eventual solution helped to shed some light on the difference between these concepts. I’ve tried to distill my learnings here.

A surprising limitation

GoogleTest is a test assertion library which uses matchers to specify what aspect of a value is to be asserted. For example, eq(123) asserts that the value is equal to the number 123, lt(123) asserts that it is a number less than 123, and gt(123) asserts that it is a number greater than 123. Matchers can be combined with the and method. For example, to assert that a number is strictly between 0 and 10, one can use:

verify_that!(value, gt(0).and(lt(10)))

To my surprise, I discovered that this did not work when the actual value being matched is a string. If we try the following with GoogleTest 0.5.0:

verify_that!("A string", starts_with("A").and(ends_with("string")))

it does not compile:

error[E0282]: type annotations needed
   --> example/src/example.rs:123:51
    |
123 |         verify_that!("A string", starts_with("A").and(ends_with("string")))
    |                                                   ^^^
    |
help: try using a fully qualified path to specify the expected types
    |
123 |         verify_that!("A string", <str_matcher::StrMatcher<&str> as conjunction_matcher::AndMatcherExt<T>>::and::<str_matcher::StrMatcher<&str>>(starts_with("A"), ends_with("string")))
    |                                  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++                ~

For more information about this error, try `rustc --explain E0282`.

To understand why this is happening, we need to look at how matchers are built.

The Matcher trait and generics

At the centre of GoogleTest is the trait Matcher. It uses a placeholder, which we call ActualT, to specify the type of the value being matched. Rust provides two ways to express this. One can define a generic trait with a type parameter:

trait Matcher<ActualT> {
    fn matches(&self, actual: &ActualT) -> bool;
}

Or one can add an associated type to the trait:

trait Matcher {
    type ActualT;

    fn matches(&self, actual: &Self::ActualT) -> bool;
}

We initially opted for the first option. Let’s consider what this implies.

A concrete type substituted for the type parameter becomes a part of the type name itself. One needs to specify it in order to name the type, that is, Matcher is not a type, but Matcher<String> is. Using a different type argument changes the type. For example, Matcher<&str> and Matcher<String> are two distinct types in Rust. One consequence of this is that a struct can implement the same generic trait twice, as long as different type arguments are provided to the trait:

impl Matcher<&str> for StringMatcher {…}

impl Matcher<String> for StringMatcher {…}

This means that the same matcher can match a string slice &str or an owned string String. Both of the following work:

let string_reference = "A string";
verify_that!(string_reference, starts_with("A"))

let owned_string = String::from("A string");
verify_that!(owned_string, starts_with("A"))

Now consider what happens when we try to combine matchers with and(). The method and() must be generic with respect to the matcher supplied as its argument:

trait Matcher<ActualT> {
    …

    fn and(self, right: impl Matcher<ActualT>) -> impl Matcher<ActualT> {…}
}

To resolve the call to and(), the compiler needs to identify the trait implementation being used. To do this, it must know the type ActualT. If the concrete matcher implements the generic Matcher trait for more than one type – as is the case when matching strings – the compiler does not know which one to pick! After all, the two implementations could define different and() bodies:

impl<'a> Matcher<&'a str> for StringMatcher {
    …
    fn and(self, right: impl Matcher<&'a str>) -> impl Matcher<&'a str> {
        …
        FooMatcher(…)
    }
}

impl Matcher<String> for StringMatcher {
    …
    fn and(self, right: impl Matcher<String>) -> impl Matcher<String> {
        …
        BarMatcher(…)
    }
}

See this playground for a complete example.

Associated types

Now we consider associated types and how they differ from generic type parameters. It will turn out that using an associated type for ActualT in the Matcher trait fixes the aforementioned ambiguity.

An associated type in a trait is a requirement, the same way as methods declared in traits are requirements. Requirements must be satisfied by the trait implementation. For methods, the body must be provided. For associated types, a concrete type must be named.

Associated types are sometimes called a trait’s output types and generic parameters the trait’s input types. The user of a trait specifies arguments for its generic parameters. An implementation of the trait specifies its associated types.

So, if we used an associated type, how would the implementation specify the type of the actual value being matched? Consider the situation above, where a single matcher can be matched against both &str and String. Unlike the case with type parameters, we can’t implement the trait twice with two different associated types:

impl Matcher for StringMatcher {
    type ActualT = String;
    …
}

impl Matcher for StringMatcher {  // Error! Implementing Matcher twice for StringMatcher!
    type ActualT = &str;
    …
}

This is disallowed because the compiler needs to pick a trait implementation every time we use StringMatcher as a Matcher. For example:

let x: <StringMatcher as Matcher>::ActualT; // Is this a String or an &str?

So, StringMatcher can’t match both &str and String. We need two distinct types:

struct StringMatcherValue;

impl Matcher for StringMatcherValue {
    type ActualT = String;
    …
}

struct StringMatcherSlice;

impl Matcher for StringMatcherSlice {
    type ActualT = &str;
    …
}

More succinctly, we can make StringMatcher itself generic with respect to the type it matches:

struct StringMatcher<ActualT> {…}

impl<ActualT> Matcher for StringMatcher<ActualT> {
    type ActualT = ActualT;
    …
}

In other words, the type of the matcher itself — not the implementation of the Matcher trait — encodes the type of the value it matches.

How this change fixes the ambiguity

Adding the constraint that concrete matchers must specify the concrete type they match solves the problem we had with and() and string matching. Let’s look at (roughly) the new definition of and():

trait Matcher {
    type ActualT;
    …

    fn and(self, right: impl Matcher<ActualT = Self::ActualT>) ->
        impl Matcher<ActualT = Self::ActualT>
}

This works with strings as one would expect:

verify_that!("A string", starts_with("A").and(ends_with("string")))
   // ActualT is &str because that is the type on which the final matcher is used

verify_that!(String::from("A string"), starts_with("A").and(ends_with("string")))
   // ActualT is String because that is the type on which the final matcher is used

Rust’s type inference is powerful enough to allow the type ActualT to be inferred by how the matcher is used. The type against which the matcher starts_with("A").and(ends_with("string")) is matched is &str in the first example above and String in the second. Each usage constrains what ActualT can be in a valid compilation unit. The type constraints in the definition of and() carry the inferred type for ActualT through each of the constituent matchers.

Importantly, for each concrete matcher type, there is only one implementation of the trait Matcher and therefore guaranteed only one implementation of the and() method. The Rust compiler does not have to choose which of two concrete trait implementations it must pick as it did when using a generic type parameter. It has a way to infer ActualT, but it does not know how to choose which is the right trait implementation just by looking at how the value is used.

What can we say in general?

The above case feels quite special. What can we say in general about which option to choose?

The Rust Book as well as Rust by Example both frame the choice to use associated types instead of generic type parameters in terms of ergonomics. With generic type parameters, the trait may be implemented more than once but the trait user must specify the parameters. With associated types, there can be only one trait implementation, but the name of the trait does not include the associated type. The example above shows that there is more to this difference: the wrong choice can create surprising limitations on the use of your API.

A quick look at the Rust standard library shows a general preference for associated types in traits. Common traits like Iterator and Future use associated types rather than type parameters.

There are some cases where generic type parameters are necessary:

  • The same generic trait instantiated with more than one concrete type should be implemented for a given concrete type. For example, with the From and TryFrom traits, since one might want to convert from many different types into a single type, so one implements the trait with each of the possible source types.
  • The associated type would have to carry additional information, such as a lifetime. The recently introduced generic associated types can help, but they still have some limitations. A use case which falls into one of these limitations may require the use of type parameters.

As a general rule, it’s best to use the least powerful feature of a language to achieve your goal. Thus I would recommend using associated types by default. Only if you need the extra flexibility should you use generic type parameters.

Conclusion

The decision of whether to use a type parameter or an associated type is important. I had naively made the decision to use a type parameter early on, and this turned out to lead to a surprising limitation in the library. Changing course after the fact was fairly expensive. Understanding conceptually what is behind the difference may help in making an informed decision. But when in doubt, use associated types.

Posted in Rust | Leave a comment

Technical design as an hourglass

Photo by SUNBEAM PHOTOGRAPHY on Unsplash

A few years ago my team received a bug report in our product whose solution required some technical design. A teammate felt it would be a great opportunity to try out the principle of “design as a team” and suggested that the whole team get together to work on the problem. So we did.

The exercise was a complete waste of time, except to show that this notion of “design as a team” is pure fantasy.

Some of the team members were not interested in the problem. They barely said a word in the meeting and could really have better used the time working on their own tasks.

Another team member insisted that we use his idea to solve the problem. We didn’t: it would have broken some key design principles in the product while providing no clear benefit over the alternatives. But he was so unhappy that we didn’t go with it that he spent the next couple of months complaining about this.

In the end, one team member designed and implemented a solution, not making use of any outcomes from the aforementioned team meeting. The implementation took about half an hour, completely solved the problem, and resulted in zero bug reports or complaints from users or stakeholders. The team meeting didn’t contribute anything to the successful design in the end.

How (not) to involve the team in design

But isn’t design as a team somehow a gold standard of collaboration? Is that not how we want to be building products nowadays?

This seemingly modern notion has an old name: design by committee. It’s well-understood not to work. When one brings the whole team together to do design, two things tend to happen:

  • Some of the team members, those with less stake in the design or its outcome, become disengaged and don’t really participate. The meeting becomes a waste of their time.
  • Some team members try to influence the design just to have their “fingerprints” on it (whether they are aware of this tendency or not). The resulting design becomes a muddled compromise of all the different people trying to take influence on the design.

One of the most important factors in the success of any technical design is conceptual integrity. Conceptually integral designs don’t arise from muddled compromise but from the focused work of one or two designers (see also The Design of Design by Frederick Brooks, chapter 6).

Beware the ivory tower architect

I would be remiss not to mention another well-known anti-pattern, the ivory tower architect.

I was once placed in a task force to solve some urgent architectural problems in a product. I expected that it would be designing the solution. I was rather surprised when, on the first day, the task force manager handed us a technical design he had created and told us that we would be implementing it.

I didn’t stay on the task force terribly long, but learnt later that the project utterly failed after several months. The entire product the team had developed was thrown away once it became clear that it would never successfully perform its function.

One key problem was that the manager played no role in the implementation. The engineers, on the other hand, had no feeling of ownership in the design, since it had just been handed to them from someone else. They felt like assembly line workers, just carrying out the work packets handed to them from above.

Technical design in a team done right

Engineering team is producing the most value when it is solving deep technical problems, which need deep technical design. How collaborative should that design be? How does the team create effective technical design while fostering a sense of shared ownership? To see the answer, I’m going to outline a design process consisting of several phases and show when different people can be involved, and how.

Step zero in a major technical design, as with any large project, should be creating alignment. It’s critical that the key stakeholders are onboard with the project and the need for the investment. How much alignment one needs to create depends on the amount of required investment and, crucially, the required involvement from other teams. In this step, one identifies a chief designer (modern language: tech lead) who takes primary ownership and responsibility for the design and implementation.

Broadly speaking, the design then goes through three phases: discovery, design, and feedback.

Discovery

The discovery phase is marked by the chief designer collecting information as broadly as possible to flow into the design. They speak to engineers and stakeholders, product managers and UX designers. They find out about expectations, constraints, and possible booby traps. Constraints include in particular any aspects of the architecture or design of the surrounding system which may block some alternatives. This phase is also a good point to collect from a broad range of colleagues initial ideas on how to proceed.

There are lots of formats to proceed with this. Some might informally chat with different parties and collect information. Others might organize a formal design sprint. The most important point is that this phase is expansionary: its success is measured on how much useful information and how many ideas are collected.

Design

In the design phase, the designer, or a group of at most two designers, uses the information and ideas collected to work out and document a detailed concept to solve the problem. This phase is consolidatory: ideas are discarded and merged while collected information is categorized.

This phase is critical to avoiding design by committee. The restriction to at most two designers enables conceptual integrity. Equally critical is that the designers be involved in the implementation so that they have a real stake in the success of the design.

The design need not work out every detail of every aspect of the solution. Parts of it can be carved out to be handed off to more junior designers (see below). But it should be clear that every aspect has a solution. One omitted detail shouldn’t be allowed to bring down the whole design. If that is in doubt, then the detail should be covered in the design.

The documented design must include a discussion of discarded alternatives. Why was a particular alternative not picked? Was the designer unaware of it or was there a good reason for this? This information is of particular importance when collecting feedback in the third phase.

Feedback

The designers share their concept with a larger round — including other team members and stakeholders — in the feedback phase. Here it is critical to get as wide a range of opinions as possible. Some may point out missed constraints, others missed alternatives. The earlier one knows that the design won’t actually solve the problem or has some severe defect, the better.

Depending on the feedback, it may be necessary to go back to revisit the previous two phases. The design process is iterative in that sense. However, the designer is not obligated to incorporate all the feedback they receive. Should the design be untenable — maybe it violates an unforeseen constraint — then the designer has little choice but to revise it or throw it out. But, when it comes to personal preference, it is up to their own judgement how to proceed.

An hourglass

Putting these phases together, one sees an hourglass of collaboration: the designer starts by involving a lot of people in discovery, then work alone or in a pair, and finally collects feedback from a wide group again. Many colleagues may be involved with the design by providing initial input and final feedback. But the ownership and main responsibility for working out a complete design lie with one or two key designers.

Hierarchical design

A team with a few relatively senior engineers is likely eager to be involved in the design process. This can’t happen if a single tech lead monopolizes the design work.

To involve the whole team, the tech lead builds an overarching concept for the problem and leaves parts of that design not fully specified. For example, the tech lead might come up with a concept for a new service and how that service would interact with other components in production. But they might not design the database schema or the data migration process, leaving those parts for other engineers to own.

The tech lead should leave the engineers a lot of leeway in making their own decisions, even if they consider a decision to be a mistake. It’s important that engineers have the opportunity to make mistakes and learn from them. Only if the design is untenable — and the designer unwilling to acknowledge that — should the tech lead put their foot down and forbid it.

Engineers must also be expected to deliver on their designs. Tech leads should hold their engineers’ feet to the fire, insisting on clear commitments about deliverables. If an engineer is dragging their feet on a design, the tech lead may have to take away responsibility for it.

Important is that the whole team, including the tech lead, be involved with the implementation of these individual pieces. This avoids the creation of knowledge silos within the team.

Conclusion

As a tech lead or a designer, don’t think you need to involve your whole team or organisation in a design effort. If more people on your team want real responsibility, parcel out parts of the design for them, but only if they will really be involved with the implementation of said design. Otherwise, they should be satisfied to provide ideas and feedback.

Posted in Uncategorized | Leave a comment

Cross-team mandates

Photo by Icons8 Team on Unsplash

Jane is a tech lead on a team building a new, exciting product for her company. She’s in her element: the project is technically challenging and the team is highly motivated. It’s important to her that the team be able to focus on the project in order to maximize the chances of success.

One day, she opens up the team backlog and finds a new ticket right at the top. It says only, “Replace dependency on frobnicator-service with flapulator-service”. The author: her manager. She’s concerned that the ticket is vaguely formulated and the — in any case extensive — required work will substantially distract the team from its roadmap. So she goes to her manager to ask what’s going on. He says only that there is a new mandate to switch to the flapulator service because the frobnicator service is deemed insecure. Sorry, but it has to be done. Pronto. We’ll pick up the project again later. Don’t worry — it’s one week of work, max. Promised.

She’s really concerned about losing momentum on the project, but concedes that the work is probably necessary. So she and her team do their part and carefully replace the dependency in their domain. It turns out the required work is not well documented and the work estimates did not take into account that they would need to add tests to a huge pile of legacy code they inherited, so this work occupies the whole team for several weeks.

After all that is done, she learns that the programme to replace frobnicator with flapulator has descended into chaos, with teams across the organization not having completed the required work by the deadline and other teams who claimed to have completed the work being asked to go back at the last minute to fix various issues they missed. Eventually, management throws up its arms and cancels the programme altogether, opting for the alternative to shore up the security of the frobnicator service.

Meanwhile, the future of Jane’s project is in doubt since — as Jane feared — the team lost its momentum and excitement while working on the mandated migration. Jane feels utterly dejected.

How not to establish a cross-team mandate

Cross-team mandates such as what Jane experienced are often necessary in engineering organizations. They may be needed to enforce a policy, such as beefed up security standards, or to unlock progress in the organization’s technical strategy. Or they may arise due to some unforeseen external factor, such as the deprecation of a service on which the stack depends.

Jane’s experience shows how not to establish a cross-team mandate. There was no transparency surrounding the decision and no opportunity for the technical leadership to offer feedback on the plan. No analysis of alternatives was apparent and the plan was presented as a done deal by management. They justified it by implicitly comparing their plan only with the alternative of doing nothing — a clear case of blindness to alternatives. That there was a better alternative was demonstrated by management’s eventually giving up and choosing that alternative, but only after an extraordinary waste of resources.

I’ve experienced some combination of these phenomena many times. Management seems to fall into a pattern of thinking, “We’re in charge, and we know best, so everyone else had better fall in line.” But ham-fisted mandates quickly burn the trust engineers have in their leadership, and that lost trust is really hard to get back.

Engineers whose project roadmaps are pulled out under them are not going to be happy, and many will resist the mandate. This may take the form of open challenge to the mandate, or it could have a more implicit (and sinister) form such as slow walking or sloppy implementation. Of course, the latter could be grounds for disciplinary action against the engineers in question, but that rarely improves the situation and is anyway predicated on being able to prove that they did these things deliberately, which is often impossible.

When engineers do openly object to the mandate, the answer they get is all to often stonewalling. The decision has already been made, there’s no option to revise it, the work has to be done. And can’t you please just be cooperative for once?

When a manager wants their report to do something, they have two options:

  1. Convince the report to do it.
  2. Order the report to do it.

Most managers nowadays loathe giving direct orders — with good reason. It’s understood to be bad management style to rely too much on orders. They are a last resort when things are going off the rails. The one who gives an order is fully responsible for its consequences, including potential failure of the team’s roadmap. Worse yet, giving to many orders to solid engineers is quick way to lose said engineers to other teams or other companies.

But convincing a report means actually convincing them. It means selling them on the benefits of the work, not manipulating them with entreaties to just cooperate or baseless claims that management must know best. As an engineer, these attempts at manipulation do a lot to damage one’s trust in management and make it much less likely that they will be able to truly convince me in the end.

A new mandate

A few months later, Jane is working on a new project to add audit logging to all services at the company. This requires that all services integrate with her new audit logging service and supply important data. It’s a critical legal requirement, and the company could face legal liability if it’s not implemented within the next three months. Her team has received from management a mandate to develop a solution and ensure that it is rolled out across all services at the company.

Jane still has the frobnicator deprecation burned in her memory. She’s determined to avoid a repeat of that fiasco. So she proceeds carefully.

First, she organizes a meeting with all of the top tech leads and the product manager in charge of the audit log programme. They present the legal requirements to the tech leads and explain the implications for their services. Importantly, she focuses on the what and not the how. She invites them to share any ideas they have for implementation and asks them to let her know of any pitfalls they see in their domains.

She puts together a document explaining the technical design of the implementation, including what work will be done by her team and what will be required of the other teams. The document shows the alternatives and explains the choices made. She shares this with the round of tech leads and asks for feedback.

Her team sets to work building the service as well as tooling to make implementation as easy as feasible for the teams. They put together a set of scripts which modify services to enable audit logging and already cover 90% of the required cases. They carefully and publicly document the audit log service as well as the tooling, and explain what cases cannot be automated and what the teams must do in those cases.

During implementation, she meets with each of the two dozen implementing teams to go through the project and the required work. She clears up any misconceptions about the programme and aligns with the teams on a timetable. The teams inform her of cases which they are not sure can be covered, and she is able to clear those cases up with them. She also prepares a project tracker with each of the required work packets and shares that with the teams in this meeting.

When the time comes for the teams to start work, they have already planned the work packets and are confident that the required work will go smoothly. They’re grateful that their concerns were heard. Most teams complete the work on time with few problems and minimal disruption to their roadmaps.

How to establish a mandate the right way

This example shows Jane taking pains to treat her fellow engineers with respect, to create alignment and to operate with the utmost transparency. These are the key criteria to establishing a mandate successfully.

  • The stakeholders behind the mandate must first establish alignment about the problem to be solved and the need to solve it. They must explain why it is so critical that it may take precedence over the teams’ own project roadmaps. Teams are normally quite understanding if there is a clear reason, such as a legal mandate. But they still want to be treated with respect.
  • The programme leaders must be absolutely transparent about the programme, including the alternatives investigated and why they went with the one they did. If engineers see that there are cheaper alternatives but don’t see any serious attempt to investigate them, they quickly lose trust.
  • The team doing the central work must make life as easy as feasible for the implementing teams, though good documentation and tooling. They should avoid casting work they could do themselves more efficiently to the other teams.
  • When feasible, and when the magnitude of the mandated work justifies it, the team managing the programme should meet individually with the teams implementing the required work packet to explain the required work and further establish alignment around it. They should use that opportunity to hear the teams’ concerns and address them. This establishes trust and makes it much more likely that the teams will be cooperative. They should also use the opportunity to establish a time frame for completion of the required work to which the team can commit.

Conclusion

Forcing a mandate on engineers with little transparency leads to resentment and resistance. Manipulating them with psychological pressure makes them distrustful and uncooperative. That the work is truly important, even backed by a legal mandate, makes little difference. One gets the best results by treating one’s engineers with respect and negotiating with them as equal partners.

Posted in Uncategorized | 1 Comment

On Time Bombs, Tar Pits, and Booby Traps

The software as craft movement is built on a premise of customer focus and personal responsibility. Let the customer decide the priorities, but be absolutely professional in delivering. Design the product with care, test everything, and use all the best practices, and you’re home free. The implication is that, if that really doesn’t work out, you’re just not a professional.

I find this premise deeply unsatisfying.

It can work really well when the team uses clean practices from day one. But how many of us have the good fortune even to be around on day one? Most of the time we inherit an existing application from other engineers and — let’s face it — the engineering standards we encounter are seldom up to par with our expectations. When it’s a matter of some missing tests or messy code, we can usually deal with it with legacy code techniques or refactoring in the context of feature delivery. But problems are all too often far deeper than that. Maybe the system architecture is broken, or the data model is unsuitable, or the application doesn’t even have well-defined build and deployment processes. These things could take a fully staffed team weeks or months to fix.

It can be difficult to get stakeholders on board with the necessary investments to fix such fundamental problems. Often the modus operandi is muddle through: live with the bad design and somehow continue to deliver the features stakeholders want. After all, nearly always muddling through for any one particular feature costs less than fixing the underlying mess. But, as we all know, this is a mirage: not only does this make an engineer’s life miserable, but it inevitably leads to piling more and more technical debt onto the application — exactly the opposite of what a professional software engineer should strive to do.

Realistically, to fix such problems, a team needs to devote so many resources to improving the architecture that their capacity to deliver features the stakeholders want is severely limited. So is a professional software engineer supposed to proceed?

Saying No

One answer may well be to say “no” to the whole project. That is, before even agreeing to work on a product or to join a team, carefully inspect their architecture and practices and see whether it is realistic to do the kind of work expected by the stakeholders. Reject any project which doesn’t meet the bar.

Were life only so simple! There are a couple of problems with such an approach:

  • One does not always have access to all the required information before joining. This is particularly true when joining a new company as an internal software engineer. Rarely will the company let you see their code before you sign the contract.
  • If one filters out all projects with severe architectural problems, one will quickly find that the selection of acceptable projects is practically empty.

Of course, this approach also doesn’t help one if one is already in such a project.

Kinds of architectural debt

I use the term architectural debt to describe problems whose scope is large enough that one cannot realistically solve them in the context of implementing a single feature or resolving a single bug. As opposed to technical debt, which can be paid down tactically “as one goes”, paying down architectural debt requires planning and strategy. Because of that, one can’t get around some degree of negotiation and alignment with product stakeholders. How that works depends on the alignment of the stakeholders’ interests with those of the engineers.

Here’s where a senior software engineer can get some extra “soft” skills to really stand out. Negotiation is not rocket science but it requires understanding where our natural human instincts (think fight or flight) can become a real hindrance. Successful negotiation requires recognizing our own (often poor) instincts and getting ahead of them. To learn more about this, I heartily recommend William Ury et al.’s seminal trilogy Getting to Yes, Getting Past No, and The Power of a Positive No.

I broadly define three types of architectural debt: time bombs, tar pits, and booby traps. These have different dynamics when aligning with stakeholders, as we will see below.

Time bombs

We speak of a time bomb when the product as it currently stands, or some important aspect of it, will stop working at some point in the future if no changes are made. Examples of this are:

  • A critical dependency of the product, such as an API, is to be turned down.
  • The load on the application is inexorably increasing and, after a certain amount of time, the product will no longer be able to scale to handle it.

In this case, the primary interest in resolving the problem lies with the stakeholders. They are, after all, interested in having a working product. Engineers certainly do not want to see their product stop working either. Thus there is a broad alignment of interests. Negotiating the work to eliminate the problem should be unproblematic, assuming both sides are acting in good faith.

Here the onus lies on the engineers to start the process. They have a professional ethical responsibility to ensure that the stakeholders are informed of potential time bombs as soon as they become apparent. Stakeholders should then be able to prioritize product work appropriately to defuse the time bomb before problems arise, assuming that is still possible.

Tar pits

A tar pit is an aspect of the application which greatly and unnecessarily increases engineering effort. Examples may include:

  • Lack of testability,
  • Convoluted design,
  • Slow or unreliable build and test processes.

In this case, the interests of the engineers are largely aligned with those of the stakeholders. Such problems make working on the product frustrating but also greatly increase development costs. In principle, stakeholders and engineers should be able to agree to prioritize the work to fix these problems if the engineers can clearly make a case that doing so reduces costs more than the required investment.

Of course, these costs can be hard to measure, especially if one considers the true cost: engineers don’t want to work in tar pits, so when faced with such problems, they tend to leave. Worse yet, it’s usually the best — the most creative, innovative, and efficient — engineers who leave. It’s worth making stakeholders aware of this, but be careful that it come across as a warning and not a threat.

Booby Traps

A booby trap is a too easily made potential mistake with real costs. The canonical example of this is missing test coverage: a well-meaning engineer may unknowingly break production code with no safeguard between their change and the costs which follow. There are many other examples.

This is the most problematic from the perspective of negotiation, since the primary interest lies with the engineer in solving the problem. The stakeholder has only a secondary interest in avoiding the costs of such mistakes. Unenlightened stakeholders may, however, simply argue that the danger is the “engineer’s problem”, that it’s “their responsibility not to make mistakes” and that they will not invest in measures to protect engineers from such problems.

Here I must be blunt: a professional software engineer has an ethical obligation to themselves, their colleagues, and ultimately their stakeholders to eliminate booby traps when they find them. This requirement, in my view, supersedes the stakeholder’s prerogative to prioritize product work. Indeed, the stakeholder is not in a position to evaluate the priority of such work, since they (normally) do not have the necessary technical background. The team should therefore plan and schedule such work itself and reduce its available capacity for product development as appropriate.

Conclusion

Senior software engineers have a professional obligation to look after the health of the products they developing. There is a natural tension of interests between the technical leadership of a team and the product stakeholders. A good engineer uses negotiation techniques to make sure the technical point of view is respected, even if it means that part of the team’s engineering capacity is not immediately available to do what product stakeholders would prefer. That’s the key to a healthy product: technical and product leadership negotiating as equal partners.

Posted in Uncategorized | Leave a comment

Decoupling: You’re gonna need it

One of the key properties of Clean Architecture (also known as hexagonal architecture, ports and adapters, or onion architecture) is that the domain model of an application or service is decoupled from all external integrations, including the persistence mechanism. (The latter decoupling also goes by the name persistence ignorance.) This means that all external integrations are hidden behind interfaces, so that there is no source code dependency from the business logic or domain model to any external system.

Some developers hear this and object with YAGNI: adding extra interfaces increases complexity and is a code smell, they claim. No interface should ever exist unless there are at least two implementations used in production, they say.

Of course, YAGNI is a real concern, but I claim that this kind of objection is not its intention.

What is the difference?

My answer to the YAGNI objection is, “But what if you do need it?” After all, you have no crystal ball to see what will change and what won’t.

Take persistence ignorance as example. The persistence layer and the domain model are different things which change for different reasons. This makes them exactly the right targets for decoupling.

When arguing that one should decouple the domain model and the persistence layer because one or the other could change, one often hears, “But that will never change,” normally thinking of a large scale change such as swapping out the entire database. Can one really guarantee that the two will never change independently of each other? Over 2, 5, 10 years? Remember, no one has a crystal ball.

Consider the simplest case of a change to the two components: adding a new field to the domain model to be persisted directly. This is a case where the two appear to change in lock-step. In fact, this type of change is commonly cited as a reason to use a tool like ORM to avoid explicit mappings: if the mapping is automatic, then this change is trivial, right?

But is it?

The change in the domain model might involve updating the business rules to make use of the new data. In the persistence layer, one must worry about data which predate the addition of the field. One needs to make sure the right thing happens when persisted domain objects are deserialized into the new domain model. Does one prepopulate the data? With a default value? With a value calculated by some rule? Or should one add some trigger when loading the data so that a suitable value is set when it is absent? Does all of this satisfy the assumptions of the business logic?

These are all solvable problems, but tackling these at the same time as worrying about the domain model is a lot on which to chew.

And this is only the simplest case! What if one is reorganizing the database by moving columns between tables or moving tables between schemata? Or refactoring the domain model? Replacing an int with a CustomerId? Changing the key of a Map? Each of these should have no effect on the other side, but suddenly one needs to think about both components at once and how they interact. Any refactoring in the domain model could suddenly be a change in the persistence layer, and any change in the persistence layer could affect how data are represented in the domain model.

And one tiny mistake could lead to data corruption.

I would wager that any serious application will undergo significant changes to its domain model, persistence mechanism, or both during its lifetime. And if it doesn’t, you probably shouldn’t be developing it. For that means that it’s a dead area: the problems have already been solved, and someone has solved them better than you will. Use their solution and be done with it.

So why use an interface?

It should be clear why we decouple the persistence mechanism from the domain model, but why do that via an interface? Why not encapsulate the persistence mechanism in a class and leave it at that? Some developers would object that an interface is unnecessary at this point.

The reason to use an interface is that a class would merely encapsulate the persistence layer, but would not decouple it from the domain model. Encapsulation is weaker than decoupling — it tends to leak. To understand this, consider the question: what language would the public interface of such a class speak?

In order to achieve a true decoupling, the domain model must drive the public interface provided by the integration with the external service, not the other way around. When the persistence layer is a concrete class, it tends to drive its interface.

This could be visible in the code itself. Let’s take a concrete example. Suppose we have a domain object Customer. We access the persistence mechanism for Customer through a class called CustomerRepository, whose public interface appears initially as follows:

class CustomerRepository {
  void persist(Customer customer);
  Customer load(CustomerId id);
}

Now suppose that some query functionality is to be added to the repository. One way to do this is to add one method for each kind of query:

class CustomerRepository {
  void persist(Customer customer);
  Customer load(CustomerId id);
  List<Customer> findByName(String name);
  List<Customer> findByCountry(CountryCode country);
  ...
}

Perhaps there is a need for more advanced queries, such as filtering by multiple criteria, sorting, pagination, and so on. If the repository is implemented by an SQL database, the temptation grows to add a method like this:

class CustomerRepository {
  void persist(Customer customer);
  Customer load(CustomerId id);
  List<Customer> findByQuery(String query);
}

The parameter query is a plain SQL statement. Now the domain model is tightly coupled to the persistence layer. A change in the persistence layer may require updating all parts of the domain model which use this method.

Even if one avoids this kind of direct coupling, more subtle forms of coupling can (and will) appear in the form of implicit assumptions about the behaviour of the persistence layer by the domain model. For example, suppose that one of the query methods is implemented so as to return the results in a particular sort order — perhaps due to the implementation of the underlying database. The domain model simply assumes that the results are sorted in that way, but this assumption is not made explicit anywhere. A change in that sort order could cause a production defect without any test preventing it.

How to prevent this?

Using an interface to decouple the two layers is only part of the solution. It is also necessary to have a reference implementation of this interface to be used in tests. It is then a fake, a specific type of test double, which constitutes the simplest possible implementation which satisfies the contract. No external integrations, no database — just a hash map in memory.

To ensure that the behaviour of both the fake and the database-based implementation used in production satisfy the contract assumed by the domain model, it is also necessary to write contract tests which run against all concrete implementations of the interface.

Sound like a lot of work? It’s not really that much: absent some mechanism to support complex flexible queries, the fake is nearly trivial to write. And the contract tests are tests one should have in any case, irrespective of whether one has an interface or just a concrete class.

This model reverses the natural inclination towards coupling which occurs when one uses a concrete class to encapsulate the persistence layer: it becomes most natural to let the domain model drive the interface to the persistence layer, and let the persistence layer implement that implementation to serve the domain model. A change in the persistence layer is contained to that layer and has little or no effect on the domain model. A change in the domain model might imply some changes to the code which translates from it to the language of the persistence layer (i.e. serializing and deserializing domain objects), but those changes are transparent and straightforward, and have no unintended effect on the persistence format. Life for developers and maintainers becomes much easier — over the entire lifetime of the product.

So where does YAGNI really apply?

The most common mistake developers make by which the YAGNI response is appropriate is probably premature generalization. One wants to solve a relatively straightforward problem and decides on a complex solution which can solve a far greater range of problems. Going back to the question, “But what if you do need it?” one has a simple answer: if one discovers the need, one can refactor the simple solution to a more general one later. Or one can add another simple solution to solve the next problem which comes. Or one can add a complex solution alongside the existing simple one. All of these solutions work just fine, and having settled for a simple solution doesn’t hinder the introduction of another solution later. There is no risk to picking the simple solution.

If one does not decouple components which change for different reasons, then one is introducing a strong assumption into the core of the application, namely, that the two components will remain in close connection with one another for the entire lifetime of the product. And the cost of changing an assumption which underlies the architecture of an application is huge.

Of course, one can’t avoid all assumptions. And one does not have a crystal ball to see what will change and what won’t. But inappropriate coupling under the assumption that some components will never change — or will only change in certain ways — over the lifetime of an application is likely to cause a lot of pain down the road.

Posted in Uncategorized | Leave a comment

Just say no to ORM

The allure looms large. Get rid of that pesky, tedious database code! Let a framework write it all for you! Object-relational mapping (ORM) tools such as Hibernate and Objectify promised to make the persistence of domain objects a trivial matter and letting them focus on the business logic which really delivers value.

That dream hasn’t really worked out.

In fact, I would argue that, over the long run, ORM brings far more problems than it solves and should not be used.

Coupling the domain model to the persistence layer

Consider how ORM is normally used: one annotates the domain objects and the framework automatically maps the objects to and from persisted data in the database. The mapping normally maps fields with database columns by name; the developer also has the option to specify via annotation an alternative database column name to which a field should be mapped.

Now, what happens when one renames a field? Normally, that would be a safe refactoring. Suddenly, absent further annotation, that implies a change in the representation of the object in the database. That might be a simple matter to fix, but what if the desired changes are more extensive: moving a set of fields to a different class, reorganizing the values of an enumuration, or changing a string-based representation of a value to a value object?

Over time, new and changing requirements may make such changes in the domain model desirable. Using ORM makes such changes far more complex, expensive, and potentially risky. The coupling with the persistence layer acts as a chain, forcing the developers to introduce ever more complex workarounds to maintain the clean mapping to the persistence layer. This is not sustainable.

Domain object validity

It is a useful property in the business logic of an application that one can always assume that all domain objects are in a valid state. The alternative is that, before taking any action, the business logic must ensure the validity of each domain object in play — a tedious and error-prone affair. This method is also subject also to immense duplication as such validation checks multiply across the business logic.

How do we ensure this property? First, we must maintain control over the instantiation of domain objects, so that no object can be instantiated in an invalid state. ORM defeats this process by providing a back door through which domain objects may be instantiated: via restoration from the database.

Now, one could argue that all such objects were once persisted by the same application, so they should already have been valid (this ignores cases where mutliple applications have access to the same underlying database — a situation one may come to regret but which often occurs in practice). But what about defects in the application, both present and past? What about prior versions? Can one guarantee that an object which was valid five years ago will always be valid in the current version, given the automatic mapping provided by ORM? Further, can one guarantee that only the application modifies data in the database? Often the database or application administrators have access to manipulate data outside the normal application business rules.

Make the mappings explicit…

What is the alternative? I am a big fan of DSLs such as jOOQ and Querydsl for access to SQL databases. They allow one to write SQL in a type-safe manner from within Java and present an enormous improvement over plain JDBC. Such solutions do not, however, take over the functions of an ORM: one must still normally write the mapping to and from domain objects oneself.

This is not a bad thing!

Many developers bristle at the idea of writing mapping code, particularly when that code seems trivial or tedious. This is often the case early in the history of an application. After ten years of accumulated history, not so much. Maintainers of older applications would often be thankful to see some straightforward mapping code rather than the tangled spaghetti accumulated on top of an ORM-enabled entity to keep up with changing requirements.

Writing the mapping explicitly allows that mapping to act as an anti-corruption layer, which ensures that, whatever is stored in the database, only valid domain objects are ever created. If incorrect data are persisted due to a defect in the application, one has two options: fix the data in the database, or update the application to correct the data upon loading. Often the latter is the preferable option — the former may even be out of the question due to technical or legal constraints.

What’s more: an implicit mapping as done by ORM makes such defects more likely over the lifetime of the application, since developers have a harder time understanding the effects of changes in the domain model. Such a mapping will almost certainly not be explicitly tested — why write a test that such-and-such domain object has such-and-such persisted representation and vice versa when the ORM should be doing that automatically? This only compounds the problem.

…and test them.

That point about testing merits further elaboration. Often one would hear the objection that such tests should be unnecessary, since they would effectively be testing the framework. But they aren’t just testing the framework — they’re testing how the framework is configured by the domain class structure and annotations (not to mention whatever other spaghetti exists on top of all that)! In fact, explicit tests of persistence are the most important tests one can write in an application. Break some key workflow and the solution is simple: roll your release back. Break persistence and you have data corruption, or even data loss. Rollback will not fix the problem. If your lucky, you can spend the next week struggling to repair your data to find a workaround in your application to work with the corrupted data. If you’re unlucky, the data are unrecoverable and you may be out of a job.

But if one is going to write such tests — and I mean properly, testing the persistence and retrieval of all domain objects in all the ways they can appear, including old versions of the application, defective data, and so on — then one might as well write the mapping anyway. The additional effort is fairly trivial at that point.

Peristence layer as a plugin

The cleanest way to design an application is to treat all external services — including persistence — as plugins. The domain model should define what interfaces they must satisfy and the code which interacts with those external services should simply implement the required interfaces. This is the idea behind what is variously called ports an adapters, hexagonal architecture, onion architecture, and clean architecture.

ORM defeats this idea by letting details of the persistence layer seep directly into the core of the application. It may seem tempting to avoid the effort to write an explicit mapping (particularly early in this history of an application, when that mapping seems trivial), but over time, that turns out to be a Faustian bargain. Just grit your teeth and write that mapping — you or your successors will be grateful.

Posted in Uncategorized | Leave a comment

Java date formatting aka Murphy’s Law

Here’s a lesson in Murphy’s Law (along with a PSA).

Last Thursday I held a session at the Softwerkskammer München on mutation testing. This included an exercise in which participants took a program with 100% code coverage through tests and tried to find changes in the production code which broke the tests.

This doesn’t work so well when the tests are already broken, as they were for at least three of the participants.

Of course I had made sure that all tests run smoothly beforehand. They were all simple unit tests, not depending on any exotic machinery or external systems.

So what happened?

The failing test in question was (roughly) of the following form:

result = process(..., LocalDate.of(2015, 12, 31));
assertThat(result.getDateAsString(), is(equalTo("31-12-2015")));

Nothing special here: the date is formatted to a string and put in a data structure. But on some (but not all) systems, the test failed with the message that the string in question was “2016-12-31”.

Huh?

It turned out, after a bit of frantic investigation, that the systems on which the code worked properly were set to the German locale, while those on which the code failed were in the English locale.

Why does this matter? Let’s take a look at the formatting code:

getDate().format(new DateTimeFormatterBuilder().appendPattern("d-M-Y").toFormatter())

Turns out the problem was with the date format pattern. Looking at the Javadoc for DateTimeFormatterBuilder.appendPattern:

...
y       year-of-era                 year              2004; 04
...
Y       week-based-year             year              1996; 96
...

So… the capital “Y” is not actually the year, but the “week-based year.” In Germany, the week begins on Monday, so the week-based year of 31 December 2015 is 2015. In English-speaking countries, the week begins on a Sunday, so the year is 2016.

Ugh.

The fix is easy: just replace “Y” in the format string with “y”. Given that this kind of bug leads to wrong results just a few days a year, and then only in some locales, I can’t imagine how many programs got it wrong.

Some takeaways:

  • This is, frankly, bad API design: “Y” and “y” are far too easy to confuse, especially given that they differ on only a few inputs.
  • Make sure to check the format strings of your programs for this error!
  • When testing any code with dates, make sure to include edge cases, like the last day of the year, and to test with different locales.
  • A program which works for you may fail for others for the strangest reasons. Murphy’s Law holds.
Posted in Uncategorized | Leave a comment