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!

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”.

The Lean Startup : Reading Experience

 

My 3rd book of the year was The Lean Startup by Eric Ries. I first got to know about the existence of this book during a keynote video of Gary Vaynerchuk where it was up for display. Finally got the time to read it.

The book focuses on how the lean manufacturing using in Toyota can be used in startups as well. And it makes sense! The case studies to new terms defined all help you shape your mind to run your startup in a lean manner.

Part One : Vision

Start

Traditional management taught in business schools is just not what an entrepreneurial manager need. The uncertain market, the uncertain product requirements all needs to be taken care of. This can’t be done with classic managerial metrics. A startup needs new metrics to track itself.

Define

A startup is human institution designed to create new product or service under extreme uncertainty.

 

Validated Learning

Failure is over hyped in startup world. People are happy to fail and then masquerade it as learning. But are we actually learning in the process?

Validated learning is the metric that startup needs to track its progress that it is making by learning from failures. Validated learning focuses on making use of learning to make tangible progress.

Experiment 

Get into the market as quickly as possible. Bootstrap the product and hit the market. Get the feedback of the customer. Nobody wants to end up building something that nobody wants. Find it as soon as possible.

Part Two : Steer

Build-Measure-Learn Loops

Eric suggests that startup should continuously run Build-Measure-Learn loops within the organization. Use metrics like innovation accounting and learning milestones to track actionable metrics and not to dwell on vanity metrics.

Leap of Faiths

Leap of faiths are the assumptions you make as an entrepreneur that your business depends upon. Entrepreneurs should have foresight, ability and tools to discover which of their leap of faiths are working and which are not.

There are two major hypothesis a startup depends upon :

  1. Value Creation Hypothesis : How you are looking to give value to customers?
  2. Growth Hypothesis : How you think that your product will grow?

Minimum Viable Product : Test It Out

Only way to test your hypothesis and leap of faiths is to hit the market.

Best way to do so is to create an MVP, that consists of your core business features. Make sure that customer actually wants what you are building.

A very good example is Dropbox : Their MVP was a video showing how it will work. It was enough to let them know that there is need for there product in the market.

Concierge MVP  : It is testing MVP with selected customers that you take feedback from in exchange of VIP treatment and support.

Measure 

How do you know that your product is improving? Innovation Accounting is again a metric that allows you to do so. It involves 3 steps.

  1. MVP
  2. Learn – Lean towards working business model
  3. Pivot or Persevere

Cohort Analysis and Split Testing

How do you know which change in product is steering the change in customer behavior? Cohort analysis and split testing is used to test different versions of products with different customers at the same time. This allows us to test features and do innovation accounting properly.

Kanban or Capacity Constraints 

Kanban is an agile development methodology that doesn’t allow new features to be added in backlog until implemented features are validated.

Pivot or Persevere 

The most important decision for a startup is to persevere current approach or pivot.  Pivot is special kind of change designed to test new business hypothesis about the product.

Eric states 10 types of pivots in the book :

  1. Zoom in Pivot
  2. Zoom out Pivot
  3. Customer Segment Pivot
  4. Customer Need Pivot
  5. Platform Pivot
  6. Business Architecture Pivot
  7. Value Capture Pivot
  8. Engine of Growth Pivot
  9. Channel Pivot
  10. Technology Pivot

PART THREE : ACCELERATE

Batch

Eric focuses on the point that startups should now follow large batch production systems but instead work on small batches. This means shortest possible release cycles and always keeping customer involved.

Grow

Startups should focus on sustainable growth. A sustainable growth is when new customers are drive towards the product by the actions of previous customers.

Engine Of Growths

There are three engine of growths that can exist in a startup :

  1. Sticky Engine of Growth : Customers stick with the product for long term.
  2. Viral Engine if Growth : Customers spreading the name of the product as side effect of using the product.
  3. Paid Engine Of Growth : Promotions and stuff.

Paid engine of growth is only profitable when customer lifetime value is greater than cost per acquisition.

Building an Adaptive Organization

Startups should focus on building an adaptive organization. Don’t go too fast nor too slow, don’t get too structures neither lack any structure at all.

The 5 Whys

As used in Toyota. 5 Whys is asking 5 level of whys on every problem. This helps you to get to the root of the problem.

Beware this should not become game of 5 Blames where each team keeps blaming other.

Innovate

Startups should provide platform for their employees to innovate. Best way to do so is to create an innovation sandbox. New features are added within this sandbox and are tested on early adopters segment of customers. Take validated learning out of it and move forward.

Also key is to hold the internals of the startup accountable for their actions. This will increase sense of belonging-ness among the employees.

 

It was a great read. All stuff you read about makes perfect sense. All the problems the book states are real world problem and if you are in touch with startups are not new for you.

 

My next book is Founders At Work : Story of Startups’ Early Days. Excited to read this one.

 

 

 

Outliers: The Story of Success : Reading Review

Outliers book cover

 

My 6th book of the year was a handpicked one “Outliers: The Story of Success”. This book was actually recommended to me by my cousin as a “must read”. And actually I was amazed how great this book is. It takes your intellectual thinking to a roller coaster ride.

As the book description says :

In this stunning new book, Malcolm Gladwell takes us on an intellectual journey through the world of “outliers”–the best and the brightest, the most famous and the most successful. He asks the question: what makes high-achievers different?

All the time we keep hearing success stories. We tend to see these successful guys as “lucky ones” or “smart one” or sometimes even as “self-made millionaire”.

This book will change your perception for success. It unlocks various not so obvious, highly backed with facts factors that actually make success happen.

When you were born to what you eat to what your ancestors used to do? It is pretty amazing how all of these can affect how successful you can become.

I highly recommend this book to everyone. A very good read.

Also as the 7th book of the year I have started reading “How I Braved Anu Aunty and Co-Founded A Million Dollar Company”. It is also a fun book to read but not a serious reading.

Will post review when done.