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!

6.00.1x: Introduction to Computer Science and Programming Using Python : The Experience

Hi, guys. I am a very active participant of MOOC. In my previous post I shared my experience with LFS101x : Introduction to linux .And this time I am back with a new course.

It was summer of 2014, I was having my semester break. And 6.00.1x was on my enrollment list on edx. I was really excited to get started with it.

As this course says, it is meant for people with little to no programming experience, I was there having some programming experience but quiet a novice to python. And will to learn python was my driving force here (of-course the MIT and Honor Code Certificate were also there 😉 ) . I started this course around May,14 and managed to finish it with all the quizzes and psets by August,14. There by I got my honor code certificate issued on 15th of August.

The course starts with very gentle introduction to computing : Prof. Eric Grimson very effectively introduces us to legendary  problems in CS like Tower of Hanoi , Fabonacci series etc.

Each week they give a pset, based on the lectures delivered that week. And trust me guys, these pset are very interesting and kind off invokes the sleeping programmer in you.  It will be no wonder to see you are skipping meals to work on the psets. Psets sometimes get brainstorming and those hide and seek champion bugs really pisses us, but in the end it is fun, and coding is all about fun :).

By week three , in pset3 we build a Hangman game. They provided us with the distribution code which we were supposed to complete. This pattern helps to improve code reading habit and understand how to write well designed code.

By week 5 comes the first quiz. It was not that tough. I scored 94% in it. So nothing to worry about it. You can do that easily too.

Week 6 introduces us to OOP(Object Oriented Programming , for the non-programming people). And in the corresponding pset6 we coded an application to decrypt   the encrypted text present in a text file. It was amazing to see it working , and feeling like a cryptography expert for a while ;).

Week 7 and pset 7 was my favorite. We get to code a RSS reader in python using Tkinter as GUI library (of-course there is the template provided by them as distribution code) . This RSS reader fetched news from Google News according to the tags provided by the users (Cool na!). This was the project I will be continuing to make something out of it.

On the basis of this pset, I am working on a intelligent RSS news reader. (Stay tuned for that).

By the last week of the course they provide additional research videos highlighting applications of python and programming in various fields of engineering and medical.

Then it is there, the day has come for the final exam. Believe it was not too difficult at all. I passed it. And managed to get a score of 97% overall in the course.

There by i received my Honor Code certificate by edx.

At the end of this Post! I want to say It was great experience for me to learn from world best professors & its not last I’ll keep learning. If you are also passionate about technology and believe in learning then you can explore yourself with best universities of the World.