Philosophy Behind The Offensive Programming

football-1149952_640

Recently I was listening to a podcast and there was this really smart guy Piwai talking about something that instantly captivated by attention. That was the coining of the term Offensive Programming.

What is offensive programming?

Well, you can find the literature on  Wikipedia and also I am not the best person to explain that. So check that out please. But fundamentally, offensive programming refers to a style of programming that is exact opposite of the more famous counter-part the defensive programming.

Defensive programming refers to coding style which adheres to dealing gracefully with conditions that should not happen.

Offensive programming on the other hand, well just tells you to let the app crash. Don’t try to recover, don’t try to handle the exception, just log the stack trace and crash.

The reason behind this is that in reality the problem can be much bigger and somewhere else in the code, as a side effect of you are getting this error in first place. This forces you to fix the problem at the source and will possibly result in a healthier code base.

When it makes sense to be offensive?

This was my exact concern while I was listening to this podcast. Thankfully, Piwai answered that himself. I also, talked about it with a really smart guy at the office and he also made the same remarks.

So at Square (the company who do payments and author libraries) what they do is, they stick to a defensive style of programming  for interfaces and parts of code that deals with external interfaces and/or user interactions. Basically, something that is not in your control.

But, for the internal interfaces, where the classes you wrote are going to interact with each other, you don’t have to be that paranoid about that. This is where he (Piwai) said you should switch to the offensive approach. You have full control over the classes you wrote, and the expected behaviour is in your control. If it fails to do so, it’s better to just crash and let the problem to be fixed at the source.

That is the exact reason he said at Square, they make very liberal use of assertions in the code. Assertions are not forgiving at all.

Example Please!

I would attempt to point to examples here, one that the Piwai himself talked in very brief and the one that I’ve encountered myself where I thought it made sense.

In this example, say we are handling credit card objects. There is no point to internally validate the credit card object every time you deal with it.

As soon as we get a credit card, we decorate it with a validated credit card. That’s all the defensiveness we had to offer.

Now internally, we go offensive and throw exceptions or assertions every time we encounter an invalidate credit card object.

The code below is not perfect, but can give you an idea.

class ValidatedCreditCard extends CreditCard{

    CreditCard creditCard;
    
    ValidatedCreditCard(CreditCard creditCard){
      // Handling external user interactions defensively.
      try{
        creditCard.validate();
      }
      catch (CreditCardValidationError e) {
        // Handle and try to fix the error
        tryToFixTheCardDetails();
      }
      this.creditCard = creditCard;
    }
}

public static void main(String[] args){

    CreditCard c  = getCreditCardFromUser();
    c = ValidatedCreditCard(c);
    // Time to go offensive
    // ...
    if (c == null){
      throw new CardInvalidException();
    }
}

Another example I can think of is a much simpler one and more relatable.
Suppose, we have a utility function that uploads a file to s3.
It would make sense to follow offensive programming style and just throw an exception if somehow they file or the key reaching the function is None.

def upload_file_to_s3(file, key):
    if file is None or key is None:
        raise TypeError

 

Few more tips from the podcast

1. How to start with offensive programming?

Best way is to start putting assertions in the code, where you think is suitable. Yeah, we’ll experience more crashes and that’s awesome!

Because now we know that we have a problem.

2.  We feel more confident about the code base:

We just know that, this method doesn’t try to handle nulls, thus I can confidently say that it was not null or it would’ve crashed.

3. Do incremental roll outs.

When you ship a code, roll it out like for 1% of users. We’ll have a ton of crash reports, and that’s good! I mean not for the 1% users but they are taking one for the team!

4. Crash at preventable errors and recover from expect-able errors :

Preventable errors are invalid arguments, NPEs etc. Go offensive on these.

Expectable errors are like resource depletion, invalid user inputs etc.

Try to recover from these.

 

Overall, it was nice to listen to a guy who works at a company like Square talking about how they use offensive programming for a healthier code base. And if Square is doing something, we all can learn something from that!

Advertisements

Zen and the Art of Motorcycle Maintenance : Reading Experience

The Japanese motorcycle maintenance guide says “ Assembly of Japanese bicycle requires great piece of mind”. There is a thing about everything you build, including bikes. If you build it with non-serene mind, then you build your problems into it.

The book takes you on a cross country bike journey that will teach you mind opening lessons that leave lasting impressions on your mind. Your mind will simple refuse to contract itself to older stage.

One of the most important lesson that book teaches you is to enjoy the common little things that life has for you. There is as much Buddha in cogs of bike, as there is at the top of the mountain.

Towards the beginning of the book the author says, “If you want to set out for the most amazing bike journey, you have learn the art of motorcycle maintenance.” The quote has so many meanings at different levels that your mind can explore the words in infinite ways.

As the bike journey progresses, author makes the point that the key to be doing great work is to be completely involved in it. Not like mechanics who listen music while working on the bike with no intention to make it great, the noise of the tools should be music.

How we see the world affects how we think about it. There are two ways to see the world, the classical way where everything is logical and the other is the romantic way.

Classical way of thinking runs the knife on views, something is cut. And when the logic in the logic is found, the beauty of the unknown is lost.

Romantic way of thinking is all about enjoying the continuum of things.

Quality is the thing that author says that you know what it is, but still you can not define it. Like you know what makes a tomato soup good, but yet you can not define what makes up its quality, both materialistic and spiritual.

World consists of three things : Mind, Matter and Quality.

The author was a student of University of California at one point, before his nervous breakdown. Studying there he made some amazing point on the thinking of Plato and Aristotle. How dialectic way of thinking is different from rhetoric way of thinking, but at the same time one doesn’t proves the other wrong.

My two the favorite quotes from the book are :

  1. “The only zen you’ll find at the top of the mountain, is the zen you take with you”.
  2. “The test of the machine is the satisfaction it gives you. There isn’t any other test. If the machine produces tranquillity it’s right. If it disturbs you it’s wrong until either the machine or your mind is changed.”

This is the best book that I have ever read. No matter what you are doing in your life and how old are you, this books touches your mind at levels so deep that you didn’t even think it was possible. But you’ll have to keep the beginner’s mind to learn.

As the author states, “sometimes it is better to travel than to arrive”. I was carried away with the philosophical ideas presented in the book and the serenity that the country side description provides.

Knowing that Chris, the son of the author, with whom he set out for this bike journey is dead was a little sad. But again in snap that increases the importance of all the lesson and the author was expounding throughout the book about life and zen.

A recommended read for everyone.

The next book that I have picked is “The Blue Ocean Strategy”.