Gauge your code’s adherence to the single responsibility principle

September 26, 2016 @ 7:40 pm Posted to .Net, OO by Antony Koch

During a routine ponderance on software engineering, I was thinking about a conversation recently in which we discussed how and when to copy and paste code. The team agreed that it’s OK to copy code once or twice, and to consider refactoring on the third occasion. This led me to wonder about the size of the code we copy, and how it might indicate adherence to the single responsibility principle.

For the uninitiated reader, the single responsibility principle – one of the first five principles of Object Oriented Programming and Design – can be succinctly summed up as:

“A class should have one reason to change”

The subject of many an interview question, often recited as rote, yet often misunderstood, the core premise can – I think – be understood by just talking about the code block, or class, at hand, in the form of a response to the question: “Tell me all the reasons you might need to edit this class?” Responses such as:

  • “If we want to change the backing store, we have to change this class.”
  • “If we want to change the business rules for persisting, we have to change this class.”
  • “If we want to change the fields used in the response, we have to change this class.”

When recited in one’s mind, are all that are required. And by considering the answers carefully, we can make an informed decision about whether to refactor, or that we’re actually happy with what we have, and are left with the option to change the class easily at a later date. The latter part of this sentence is critical to becoming a better developer, because what we have might be acceptably incomplete, and refactoring might take an inordinate amount of time and fail to offer significant business value to justify the expense.

This said, is copying and pasting code OK? Mark Seemann wrote an excellent blog post on the subject – which I won’t attempt to better – suffice to say I agree, and that it’s OK to copy and paste under a certain set of circumstances. The primary concern is the tradeoff: to suitably generify code requires at most a deeper understanding of the abstractions in play, and at least the ability to introduce dependencies between classes and modules that might not have otherwise been required. A quick copy paste of code that’s unlikely to change is not going to kill anyone. It might introduce an overhead should the code’s underlying understanding change, however volatile concepts do not in the first place represent good candidates for copying and pasting.

Now to wistfully return to the subject at hand – how can we use copying and pasting to judge our code’s adherence to the single responsibility principle? Quite simply: if we can copy only a line or two, then the surrounding code within the method body is perhaps not doing as targeted a job as we might hope. If we can copy entire classes, we can say that we’ve adhered strictly to the core tenets of the single responsibility principle: this class has such a defined person it can be lifted and shifted around the codebase with ease.

This means we can judge any of our code in a couple of ways: answer the question “what reasons does this class have to change?” as well as being honest with ourselves about our ability to copy and paste this code into a different codebase without being refactored.  Would half of the class be thrown away? Would we have to change a bunch of code in order to fit a different persistence model, say copying from a SQL Server backed system to a system backed by Event Store? I think it’s an interesting idea, and definitely one I’m going to keep trying in the coming days.

1 comment

OO Principles, #1: Tell don’t ask

October 30, 2013 @ 8:21 am Posted to .Net, Java, OO by Antony Koch

I first heard “Tell don’t ask” during a course being given by ThoughtWorks and it’s certainly one of a set of phrases and one-liners that run through my head when coding.

I find that a core set of easy to remember principles help govern my coding both during the planning, implementation and refactor and ultimately save me quite a bit of time in the process. One could argue that I’m performing a miniaturised version of Agile in my head, holding a planning session, then performing code reviews before having a retrospective, all in the space of a few minutes.

The main principal behind “Tell, don’t ask” (which I’ll refer to as TDA from now on) is that you should tell your objects what you want them to do, rather than asking them about their state and performing additional callsbased on the answer. This encapsulates the business logic in the correct place and can prevent mutable properties from leaking to external classes where their state can be changed incorrectly, causing a direct and negative effect on the system’s overall state.

Example

Here’s a trivial example but hopefully it helps to explain the principle in greater detail.

public class Converter {
    private boolean convertFromBase;
    private IMap mapper;

    {
        convertFromBase = false;
        mapper = new XmlResponseMapper();
    }

    public boolean getConvertFromBase() {
        return this.convertFromBase;
    }

    public void setConvertFromBase(boolean convertFromBase) {
        this.convertFromBase = convertFromBase;
    }

    public MappedObject createFrom(Response response) {
        return mapper.map(response);
    }

    public MappedObject convertFromBase(Response response, MappedObject mappedObject) {
        return mapper.map(response, mappedObject);
    }
}

So here we have a simple class that performs conversion to either a fresh instance of an object, or maps properties from the response into an existing object. Nothing too daring. Let’s look at an example of this object’s consumer:

public class ResponseConsumer {
    private Converter converter = new Converter();
    private MappedObject mappedObject;
    public ResponseConsumer(MappedObject mappedObject) {
        this.mappedObject = mappedObject;
    }

    public MappedObject handleResponse(Response response) {
        converter.setConvertFromBase(mappedObject != null);
        if (converter.getConvertFromBase()) {
            return converter.convertFromBase(response, this.mappedObject);
        }

        return converter.createFrom(response);
    }
}

This object consumes our convert and based on its own instantiation and state asks the converter if it should convert from base and then calls a different method based on whether the response is true or false. This is awful code and breaks a number of other paradigms in the process, but that only serves to prove the point!

The main focus of this code is the handleResponse method. We tell it to set convertFromBase to a boolean (meaning the class is mutable), then (stupidly, I’ll admit) ask it whether we should convert from base and call convertFromBase if it’s true and createFrom if it’s false. What this code, in effect, is doing is handling the business logic of conversion outside the converter class.

That doesn’t sound right.

So if we were to fix this, how might we do that? Well, for starters, let’s think about the abstraction. We have a response and we want to convert it into an object our system understands. So our class which understands how to handle response should hand off the response, or parts of it, to a class that understands how to convert it. So a single point of entry ‘convert’ would be ideal. Let’s make one! First of all, here’s our response consumer class:


public class ResponseConsumer {
    private Converter converter;

    public ResponseConsumer(MappedObject mappedObject) {
        converter = new Converter(mappedObject);
    }

    public MappedObject handleResponse(Response response) {
        return converter.convert(response);
    }
}

We can see this has been greatly reduced in size, with methods down to a single line, including our new ‘convert’ method. Let’s look at the converter class:


public class Converter {
    private final MappedObject mappedObject;
    private IMap mapper;

    {
        mapper = new XmlResponseMapper();
    }

    public Converter(MappedObject mappedObject) {
        this.mappedObject = mappedObject;
    }

    private boolean getConvertFromBase() {
        return this.mappedObject != null;
    }

    private MappedObject createFrom(Response response) {
        return mapper.map(response);
    }

    private MappedObject convertFromBase(Response response, MappedObject mappedObject) {
        return mapper.map(response, mappedObject);
    }

    public MappedObject convert(Response response) {
        if (getConvertFromBase())
            return convertFromBase(response, mappedObject);

        return createFrom(response);
    }
}

This now holds the logic of conversion, encapsulated within one method: convert. This method knows how to convert and knows it very well, handing off to other (now private) methods. The state of this class cannot be changed now either, making it immutable, therefore allowing instances to be more trustworthy.

The secret here was to first consider how we might tell the class what to do, in this case: convert. Once we realise we only have one thing to convert (a Response) then we should create the class according to that. We should tell the converter to convert and let it do all the dirty work.

Summary

I hope this made some sense, especially as it’s my first attempt at this sort of blog post. I also stopped writing it half way through to go on honeymoon so a bit of a refresh had to happen in order to finish it. The main crux is as soon as you spot branches of code using if/else structures, examine the object(s) upon which your if statement relies. If your if statement is asking another object to fulfill the business logic, that is an indicator to extract that into the object in question as a derived property (C#) or a method (java). Tell it to figure out the boolean value instead of asking it!

No comments (click to be first!)