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!

E-Summit ’17 IIT Bombay — Experience

E-Summit is the flagship entrepreneurship event organized by IITB. The two-day annual summit promises to be an amazing meeting ground for industry experts, business leaders, investors and entrepreneurs and of course, students, many of whom are aspiring entrepreneurs.

I attended this event in its 2017 edition and had mixed feelings on how the whole thing turned out holistically. There were some good parts and some not so good parts, but as a whole the event was worth attending.

There were many small talks spread on a 2 day course. Obviously, you can not attend all the talks, you have to select few of them according to the schedule and feasibility.

I personally realized that choose a topic that you are not familiar with as talks are pretty basic and don’t go to great depths.

Following are the talks and keynotes that I attended.

Day 1 :

  1. Keynote by Raj Jaswa :

First event of day 1 was keynote by Raj Jaswa. Most prominent thing he said in a nutshell was areas in which one should look for business opportunities.

Some being,

  1. Cloning and localisation
  2. Long tail business
  3. Adapt an existing business model to a new sector.

2. Digital Marketing :

This talk was presented by founder of E2M, a digital media company. I found this talk too basic aa I had already taken a course online on digital marketing.

Some topics discussed were,

  1. SEO
  2. PPC
  3. Social Media
  4. Emergence of mobile platforms

3. Brembo Company Presentation :

Brembo is a breaking technology company and a dominant force in the market. A manager from Italy presented the company’s operations in India.

He quoted a quote from the founder of Brembo that I found very captivating,

“Anyone can do simple things, but only few can handle difficult ones. We have to do difficult ones”.

4. Chat with Rahul Yadav :

Next session I attended was a Q&A session with Rahul Yadav, the founder of Housing.com.

It was nice to see him talking about his mistakes and telling people not to repeat them.

5. Wealth creating through financial planning :

This was conducted by Reliance Mutual Funds. In a nutshell it was all about SIP.

6. Keynote by Rajat Sharma :

The day ended by keynote by Rajat Sharma. He discussed his journey and his humility and wisdom was notable and inspiring.

7. Stand up comedy by Vipul Goyal and Sapan Verma

Nice performances by both of them always.

Day 2 :

Day 2 of the event was more power packed. I found the speakers and the talk topics, both to of higher level.

  1. Building a brand that indians love :

This was presented by an ISB professor. Basic point conveyed in the talk was that business customers have two currencies that they spend : time and money.

Thus, trigger point of all the businesses must be how customers are spending these two.

2. Protecting your brand : Trademarks, Copyrights and Patents :

I had no prior knowledge of patents and thus decided to attend this talk.

It nicely packed info on what, when and where to file the patent.

3. Startup Scaling : Overcoming key operational challenges :

Pressing issue of this talk was the resource visibility issues that startups face.

The speaker was from a company called OutThink LLC. They advocated that such challenges can be overcame by businesses collaborating and providing services to each other instead of doing things completely by themselves in isolation.

Here is where OutThink helps its customers by what they call at SRM : Strategic Resource Mapping.

4. Most Common Startup Budget Mistakes:

This talk was presented by a startup investor and mentor from Ireland.

The talk revolved around funding sources, funding advice and bootstrapping.

5. Final Keynote : By Bibop Gresta : COO Hyperlopp TT

The most exciting event of the summit was final keynote by COO of Hyperloop. He presented us with the overview of Hyperloop and how it is planning to carry its operations in India.

It was notable how fit and fun he was at the age of 40. Something that we can all learn from.

Conclusion :

To conclude, the summit was a thumbs up. It was not entirely the standard that I was expecting it to be, but still was Ok.

It was great if you have networking as the primary goal in your mind, not so good if you wanted hand on knowledge on topics.

Finally, it was nice to see other aspiring and existing entrepreneur facing the problems that you are also facing. Makes you feel that you are not alone and if that can pull it off, you can too.

5 notes on MVP architecture pattern for Android

                                                           Image credits Macoscope

MVP (Model View and Presenter) is an architectural pattern inspired by the popular MVC pattern.

MVP addresses two main points :

  1. Make views as dumb as possible. The dumber the better.
  2. Make each layer loosely coupled and easily testable in isolation.

I am using MVP in one of my production project and have used in some dem0 apps. Here are my 5 notes on using MVP for android.

  1. Package Structure :

Android project contains lots of code and files even for application of medium complexity. Even when not following MVP I have found that arranging the project files in such a way that files that are accessed together are put in same package is more efficient and intuitive than any other approach.

What I prefer doing is create separate package for separate verticals of the app and put all related files like activities, fragments, views, presenters, adapters etc in that package.

ex. packages like add task, view task, list task for a To-Do app.

2. Libraries that are useful for MVP :

In MVP you want your model and presenter to be independent of the life cycle of view. For this, you can use dependency injector library like Dagger2.

Other than that, using RxJava and reactive programming principles for creating presenter is also becoming increasingly popular.

Libraries you can use for this purpose are : RxAndroid and EventBus.

3. Managing Remote and local data sources in the Model :

Android apps have to fetch data from the server. At the same time fetched data must be cached to make the app usable offline and increase the speed.

What I prefer doing is to create three model classes :

1. Remote Data Source

2. Local Data Source

3. Data Repository

All presenters talk to Data Repository class. Data repository model contains references to Local and Remote data repository and calls data from either according to situation.

As the name suggests Local Data Source deals with cached data and disk storage whereas Remote Data Source deals with API calls and responses.

4. User Experience is the top priority :

One thing that we all have to keep in mind that the real test of application is, if it is able to provide user a nice experience.

At the end of the day, user only notices the user experience of the application and not the architecture used. So if you have to make some design sacrifices to make the UX better, do it.

The real test of the machine is the satisfaction it provides to the mind. There is no other bigger test.

5. Testing Advantages :

Main motive behind MVP pattern was to make the testing of layers easy.

Basic idea is to keep the presenter and model android free, so that they can be tested without Android instrumentation by the JVM itself.

Views can then be tested by Android Instrumentation tests.

Mockito and Espresso can come handy for testing purposes.

Conclusion :

MVP, in my opinion is so far the best way to architect your android application project. It simplifies many issues like testing and making views lighter. Combine it it RxJava and dependency injection and you’ve got a nice recipe for android projects.

I am learning more about RxJava and testing frameworks will share my views on that soon.

Thanks.

UBCx: Marketing1x Introduction to Marketing : Course Experience

Marketing is no longer about the stuff that you make, but about the stories that you tell.

In today’s world everyone in some way or another is trying to market themselves to the world. This becomes even more prominent if you are trying to attract customers to earn your living.

Preping to become an entrepreneur, I decided to take this course to get the proper understanding of how the mind of a marketer works.

This course included loads of case studies in the form of stories that covered many famous marketing campaigns world wide, from Viagra vs Cialis to Hershey’s vs Mars. Each story will teach you important aspects and tactics of marketing. It will equip you will all the marketing jargon that you will no longer hesitate to invite your marketing friends for a cup of coffee or beer.

The course was 6 modules long. I did it in 15 days as I was running short on time.

Module 1 : Changing nature of marketing, Competition

It covered various tools and frameworks like 3C’s , SWOT and PEST to understand the changing marketing scenario around your business.

Module 2 : Market Research, Segmentation and Targeting

Market research to get actionable insights will make sure that you don’t end up making a product that nobody wants. The case very common with startups.

Study of demographics and psycho-graphics to determine the target customers is another vital component.

Module 3 : Positioning and Value Propositions and Product

Positioning your product in the market by the use of VPs , PoPs, PoDs will determine your product gets sales or not.

Product is not just product, it is a much broader and deeper experience that customer is having with your brand.

Module 4 : Branding and Pricing

Brand identity is what company thinks of its brand, brand image is what use feels about your brand. The more they are similar, more well your product will do.  

Pricing should also be done using skimming and penetration approaches.

Module 5 : Distribution, Integrated marketing communication 

Channel economics, indirect or direct and how product distribution schemes can affect it.

What are IMCs? Basically these are used to reinforce your brand images in customers mind.  Be it PRs, SEO, websites, traditional ads etc.

Module 6 : Social Media, Measurement and Conclusion 

How social media is changing the marketing scenario when combined with digital marketing. (Mobile marketing is what my new start up is based upon).

They can be used to facilitate customer communication.

Metrics of any marketing campaign is revenue, cost of customer acquisition and customer lifetime value.

Conclusion : 

Being a beginners course in the field of marketing, this course served its purpose. My new startup is in the field of mobile marketing where we help small businesses get mobile and expand their customer base.

This course really helped me in shaping what exactly I have to do to shape the company.