Mario’s Blog

Here are some thoughts of mine.


Notifications without the Network

A Push Notification is a message (read data), that’s sent from a remote server to a connected device

Most of you who have had to deal with Push Notifications (GCM, etc.) would have come across how reliable they are. I stress on them not being reliable, primarily because of the way we (read India, other developing nations) use our data. A whopping 50%+ of our Internet Janta, do not have their data on through the day. Without data, there’s no way to reach a device, and hence notifications never reach a huge chunk of our customer base.

Don’t we all have that friend recommending to us to turn off data, when we don’t need it, and use it only when we need to!

How do we effectively reach a message out to our users, when their data is turned off most of the time?

Enter Scheduled Notifications. What if we can schedule a notification on a user’s device, provided we know of an event much in advance. By doing so, at the designated time, we can pop the notification to our user, delivering to them whatever message we intended to. Every Android device ships with an AlarmManager, that well, schedules tasks to be run at a specified time. We took the capability of push — which is to send data to a device, and the capability of the AlarmManager to schedule a task at a specified interval. We send data over the wire, a few hours, or even days in advance, listen on this data and then set alarms to fire off notifications on the device. This way, we are able to reach out to our users at the designated time. The only caveat is that we need to know of an event much in advance. We can only hope and pray that battery woes and data woes slowly cease to exist, to solve this problem for good.

While we were building this, we had to also take care of de-duplication, to ensure that the same message when sent as an instant push and a scheduled notification do not pop up together as separate notifications on a users’ tray. So we went ahead and built a system on the device to keep track of previous notifications, and we effectively de-duped notifications.

Now, since we have a system to effectively handle notifications on the device, we took it a step further and added rules to configure how many notifications a user could receive on the device. We could add these rules by classifying notifications by type, etc. You might wonder, why would we add all that logic on a device, when we should effectively be doing this on our servers. Well, we’ve learned the hard way, that we cannot always be too sure of these systems working flawlessly, we never know when they can go berserk due to an unforeseen error. So, we’ve built our apps to be extra careful in such situations.

GCM, (now FCM) supports Notification messages and Data messages. This flexibility to handle the notification, comes only when you send a notification as a data message. Just ensure that you do not spend too much time in the background. Get your work done and exit as soon as you can. The advent of Jio has led telcos to heavily reduce the cost of data. We can only hope that user’s stop being over-protective of their data usage.


My First Day at Compassites

As most of you who would have looked me up would know, I was working at Infosys and have been doing so ever since I left college. I decided it is time to change a few things in my life, and one of those was to get a new job. A friend of mine told me about Compassites, a growing IT startup with a great vision and great leaders. I thought it was the right place for me to work in. I didn’t apply to too many places. I wasn’t interested in working in any of the IT biggies anymore. So Compassites, fit right into the place I had in mind. I was referred to the company by a kind friend, got called for the interview and I cleared it :) Infosys has a notice period of 3 months, I got my offer letter on March 7th, so I could only leave Infy by the 1st week of June. After a looong wait, the day finally arrived when I bid Infy good bye. It was a fruitful 3 years, I learnt a lot and have a lot of memories that I will cherish for life. June 10th was the day I was to step into an entirely new life.

Unlike any of my pervious work days, I got to go to office from home. Mom was busy packing, dad, my sister and myself set off to our respective offices. Being the first day I didn’t want to be late. So I left home by around 8:10. I got a bus 15 mins later. The bus journey was long, really long. By the way, I chose to travel by bus as the bike would be a really bad decision considering Bangalore’s traffic. The office is located at JP Nagar, that is a whole 50 odd mins from my place in moderate traffic! I plan on spending my time in the bus, by either reading a book, watching some videos or as a last resort sleep!

Anyways, in my offer letter, it was mentioned that I had to be in office by 9 am. But, my HR had mentioned 10am to me. So I decided to be there by 9:30. Upon entering the office, I found an old colleague of mine, who I came to know also works here only when I saw the “Join Us” page at www.compassitesinc.com, her pic was there. I walked into the office and met the HR, who told me to wait a little, while she got my documents ready.

I’m going to take a little time to explain to you how my first day at Infosys was, just to paint a better picture of exactly how I was feeling here today. At Infy, I was part of a batch of 700 odd trainees. We were all taken inside the famed “multiplex” at the Mysore campus. We had a host of folks addressing us, right from the HR to the security, We were screened videos of talks by Narayana Murthy, Kris Gopalakrishnan, the then CEO, etc. Well, I hardly knew the people sitting beside me, forget getting to know any of the 700 odd people from my batch!

Now back to the present, I was taken into a conference room as I was the only person to join on that day. There was a nice huge LCD TV onto which the presentation was displayed. I was walked through the history, value system, culture, etc of Compassites. I was shown a few videos of the CEO, talking about the company, its values, etc. I was then given a set of forms, which I had to review and sign. All this might sound like any other induction, the next part was what amazed me. I was taken around to every single employee and introduced to them personally. Now, this was something I least expected!!!! It was such a nice gesture. Never in my entire career, have I been introduced to everyone, even from my own floor! Everyone was very pleasant to talk to.

I was then introduced to Rahul (whom I guess I’d have called my team lead), who got me started with work. I kept meeting more and more people throughout the day, everyone were really nice. I really felt like moving from an large ocean, to a small lake. A really nice clean lake at that. I knew everyone who resided in it! :)

The people here are really smart, and I’m really looking forward to working with each and everyone of them in the months to come by.


The Singleton in Objective C

In my previous post I had mentioned a code example on how to write a Singleton in Objective C. I had a friend ask me, what would happen when I call an alloc init over my Singleton?

This got me thniking, so I did my fair share of research on the topic, and came up with a few conclusions. There is no way to restrict the calling of the init method(like in Java). But, we still want to maintain only one instance. Of course, the easiest solution would be, just to remember that we are using a Singleton :-) But, often enough this is not the case, and when working in large teams, theres always a chance of making a mistake. So here are two methods by which we can ensure the creation of one and only one instance of the class

  • Restrict creation of another object of the same class
  • Raise an exception when an unnecessary retain or release call is encountered

Restricting the creation of another object My code would have to be modified by adding another method…

Singleton.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#import "Singleton.h"

@implementation Singleton

static id _sharedInstnace;

+(void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_sharedInstnace==nil)
        {
            _sharedInstnace = [[self alloc]init];
        }
    });
}

+(id)allocWithZone:(NSZone *)zone
{
    if(_sharedInstnace==nil)
    {
        _sharedInstnace = [super allocWithZone:zone];
    }
    return _sharedInstnace;
}

+(id)sharedInstance
{
    return _sharedInstnace;
}

@end

The allocWithZone: method is what allocates memory to the object. Hence overriding this to point it back to the same object will prevent other instances of the object from being created. This of course, ensures that, when a developer calls alloc init on the class, the same instance is returned. This makes the developer oblivious to the fact that he/she is using a Singleton. If we want to be mindful of our actions, Id suggest the next option.

Raising an exception when an unnecessary retain is called

Singleton.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#import "Singleton.h"

@implementation Singleton

static id _sharedInstnace;

+(void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_sharedInstnace==nil)
        {
            _sharedInstnace = [[self alloc]init];
        }
    });
}

+(id)allocWithZone:(NSZone *)zone
{
    if(_sharedInstnace!=nil)
    {
        [NSException raise:@"Explicit Object Creation not allowed" format:@"%@ is a Singleton",[self class]];
    }
    _sharedInstnace = [super allocWithZone:zone];
    return _sharedInstnace;
}

+(id)sharedInstance
{
    return _sharedInstnace;
}

@end

This way you would have an exception raised every time you try to instantiate a Singleton

Notice, that in both these snippets, I have left the Object creation to a new method

1
+(void)initialize.

From the Developer Library…

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

So by calling this method to create our Singleton’s instance, we make sure we call it only when the Class is first called.

And dispatch_once ensures that any code within this block is executed only once


Design Patterns - Singleton

Here’s my second post on Design Patterns. So, this post is going to throw some light on the Singleton Patterns.

In software engineering, the **Singleton Pattern** is a design pattern that restricts the instantiation of a class to one object

So one might wonder why would you need to implement a Singleton? There are many scenarios where we’d rather have just one instance of a particular class. For eg.

  • The class which instantiates the DB connection
  • It can be used as a replacement to a Global Variable

Here are some of the advantages of using a Singleton

  • Only one instance of the class will exist
  • This saves up on memory
  • Allows one to share data amongst classes without actually passing around objects

Here are a few examples where you must have used a Singleton

linenos:false
1
Runtime.getRuntime().exec(new String[] {"echo", "Hello, world!"});
linenos:false
1
[UIApplication sharedApplication].delegate;

Here’s an implementation of the Singleton Pattern in Java

Singleton.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Singleton
{
  private static Singleton instance;
  private Singleton()
  {
  }
  public static synchronized Singleton getInstance()
  {
      if(instance==null)
      {
          instance=new Singleton();
      }
      return instance;
  }
}

And here’a an implementation in Objective C

Singleton.h
1
2
3
4
5
6
7
#import <Foundation/Foundation.h>

@interface Singleton : NSObject

+(id)sharedInstance;

@end
Singleton.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#import "Singleton.h"

static id _sharedInstance;

@implementation Singleton

+(void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_sharedInstnace==nil)
        {
            _sharedInstnace = [[self alloc]init];
        }
    });
}

+(id)sharedInstance
{
    return _sharedInstnace;
}

@end

So thats how you make use of Singletons. This is one Design Pattern you will use on a regular basis. Will update this article with more samples and issues related to thread safe creation of singletons.

EDIT : Added a slightly better way to manage Singletons in Objective C. A more detailed explanation and variations to this can be found in the next post.


Design Patterns

Most of you in the Software Development Industry must have at some time or the other heard the term Design Patterns . Well, I heard this a while back from a few friends. Design Patterns was originally conceived by Gamma, ErichRichard HelmRalph Johnson), and John Vlissides  in their book Design Patterns: Elements of Reusable Object-Oriented Software).

To be brief, Design Patterns are a collection of approaches to Designing software applications that enable reuse and extensibility. It’s a more Object Oriented way of writing code, that is structured, well written, well understood and most importantly highly extendable and reusable.

Now, many of you might wonder, why must your code be extendable? We work in an industry thats driven by Clients’requirements. And mind you, these requirements hardly freeze that easily. Well you might say, if you were to follow the waterfall methodology of Software Design, where does change in Software requirements occur. Truth is, in all practicality, the waterfall model cannot be followed all the time, and even if it were to be followed, an iteration over the code to add a new feature, must be made with minimal change to the existing code base.

Most articles I’ve found these days about good programming spring from the Agile, TDD and XP Community. They’ve inspired me to write better code, and well, I must say I’ve grown to like their style of development too.

Here are some of the ideals I try to follow, they’re not in any order, just random stuff I do while writing code.

  • Do not use else
    • I try real hard to avoid the else statement. When I first heard this from Object Calisthenics, I found it weird  but slowly grew to realize that I realize that I didnt need it. A simple return or continue could easily replace an else.
  • Only one level of Indentation
  • Good method names
  • Let a method perform one task and only one task
  • Break down taks into Classes, give each class a Single Responsibility
  • Use helper methods to perform tasks such as formatting text, etc.

When I started writing code, I use to have this notion that my code must not be understood by others, that made my code complex and better!

Now, Ive grown to realize that, the easier my code is to be understood, the better it is.

Coming back to my initial topic of discussion, I find that Design Patterns help me write better code. We might have some point of time used many of these patterns, but without giving them a proper name.

Well, the Gang of Four, have taken the trouble to pen these down and have given a name for each of them. Now, the Gang of Four are not the only ones who documented them, they are the most acknowledged and one of the first to do so. SInce I acknowledge them, I will be using them as a reference and I shall also add a few more that I find or come across.

Creational Design Patterns

  • Abstract Factory
  • Builder
  • Factory Method
  • Object Pool
  • Prototype
  • Singleton

Structural Patterns

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

Behavioral Patterns

  • Chain of Responsibility
  • Command Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

Now why am I telling you all of this. Well, I intend on going through all these 22 patterns via code examples over a span of (hopefully) 22days :-)

So, I’m going to document my understanding via Code Examples, etc. Each Pattern will have its own post.

Code examples will be posted to github and can be browsed through via my github handle -> Github

So ciao for now, see you in the next post.

PS : I’m not going in any order


Bad Roads and the Contractors who built them

Back here in India, we are prone to finding bad roads, with potholes. Usually, once the road has been newly laid, its all neat and really great to drive on. A few rains, a few months later, there are pot holes everywhere! The only plausible explanation is the quality of tar and other material used to lay the road. And the people to blame are the Contractors. Most Contractors in a bid to make money use poor quality material to get the road laid.

Once the bad road has been laid, and after a good load of people have suffered using them, they start off with patch work, this is usually taken up by a different contractor (The old contractor cant be trusted anymore). Now, patch work is never good, there are odd lumps on the road, and the drive, though not as bad as the previous one with the potholes, is still not great.

We wait a little while longer, there are more potholes, and this time even the patch work has started to wear off. Now people have to lay a fresh road. And once again the vicious cycle continues.

When I was riding by today on a bad road, it chanced by my mind. Isn’t that exactly what we see here, in the software industry. We usually get projects wherein we find that the code has been really badly written, and we are given the task of fixing it. Or in some cases, bad code which we have written, ends up in another person’s kitty to clean up.

Why do we write bad code? Aren’t we also like these bad road contractors? Getting some one to clean up our mess, or get it in a state bad enough that it has to be re written from scratch?

People think its a headache to use the write design pattern, that breaking down our objects in to smaller, more usable objects is just some big daunting task. Or for that matter, using the right variable name, or closing that curly brace properly is just too much to do. I keep telling people that code should look beautiful.

Code, to us programmers is like how a painting is to an artist. Unless it looks beautiful and magnificent, it’s just not complete. We’re not experts or gurus to just weave out great code, but even a small effort such as using the right variable names, using the right code wrapping style, breaking down your objects into more smaller, manageable objects is surely going to go a great deal in making your code better, more maintainable and more extensible.

Writing code that works is not the right approach. But writing good code, that works, efficiently and allows for extension in the future is the right approach.

I was introduced to Design Patterns by two friends, Senthil and Kumaran. Ever since, I find myself trying to write better code. I know I still have a long way to go. I want to be a great Road Contractor. And I know that spending that extra time to get my code look beautiful, is going to get me there.

Other Resources that I’ve found of really great use


Sherlock Holmes, A Game of Shadows - Movie Review

I just watched Sherlock Holmes, a game of Shadows. It was running in the multiplex at my office campus. Before I go on to tell you how the movie was, I’m going to tell you what led me to go watch the movie.
First up, I’m a big Sherlock Holmes fan. I just love the way his mind works. Would’ve been great to know a real person like him.
I was sitting at home, half sleepy and half wondering what to do next that will not bore me. I had already watched The Hound of Baskervilles (Sherlock Holmes TV Series, BBC) earlier today. I actually fancy a more modern day Sherlock rather than a Sherlock from the late 18th Century. But, nonetheless I realized that the DVD was not due until April, so I mustn’t curse myself in the future for not watching it, so I went ahead and made a decision to just go out there and watch it.

I usually have a habit of tweeting and posting on my fb wall, about any movie I was about to watch. Hoping for a last minute save from some good soul. I’m not a movie buff. I find it difficult to sit for about 3hrs and see what the Director has to show me. But, nonetheless, once I’m hooked onto it. I will watch it till the end.

So, I got balcony seat, a nice place to watch the movie from. The show was at 8:30pm, and I was there about 15mins earlier. At about 8:20, they started screening a few Trailers.

  1. GhostRider - Spirit of Vengeance
  2. The Dark Knight rises
  3. Journey 2: The Mysterious Island

The movie started off next, amidst a lot of whistling, which is something I still don’t understand or find the need for. Like its prequel, this edition too was based in the late 1800’s. If I’m not mistaken, 1891. The entire color tone and every thing else was set to mimic England from the 1800’s. A really nice job I must say. The visuals were slick and really a sight to the eye.

The plot opens up with James Watson typing down the entire tale, and is mostly narrated by him. There are a lot of bombings around England and people assume its the work of other nation’s planning on waging war against England. But, Sherlock Holmes knows better. he suspects the hand of his arch-nemesis Professor James Moriarty.

The tale is wound around a gypsy girl they meet, who’s brother Rene, works for Moriarty. I’m not going to throw too much light on the story. I’d rather you watch it than me spoil it for you. I’m not a good story teller! Well, I’m here to only give my critical opinion. It wasn’t as nail biting as its prequel. But, its worth the watch all the same,. imdb has rated it a 7.9/10, which is pretty high.

But, I guess the reason I wasn’t all that pleased with it was perhaps because I’ve been off late been fascinated with the UK TV Series. Its situated in modern times and has a lot more suspense to it.

My rating would be about 6/10. Neither was it bad, neither did it impress me much. It did make me laugh and did want me to watch it. I must attribute a lot of that to Robert Downy Jr., who is a fine actor and seems to carry his touch from Iron Man. He has really portrayed his role well. They introduced Mycroft Holmes, Sherlock’s brother for the first time. Watson’s role played by Jude Law has been enacted well too. Rachel McAdams, portrays her role really well too. It was sad to see Irene Adler killed off though. She was like the perfect match for Holmes. Mary Watson played by Kelly Reilly, shared more screen space compared to the previous Sherlock Holmes.

The climax was a bit predictable, they couldn’t kill off Mr. Holmes. So that clearly means we can expect more Holmes, hopefully from Robert Downy Jr. again.


A Naive Programmer’s guide to Git

Git is a version control system. More specifically it’s a distributed version control system.

For those of you who don’t know hat versioning is. Here’s a small anecdote to get you up to speed.

I was working in a project where I was the developer and I had a fellow team mate testing my code. I used to complete my code and inform him of the updates and ask him to proceed with the testing. This was what he used to do. Download the latest version of the code into a folder with the current date as its name. Test the code and then let me know of any bugs.

This was his folder structure Proj | 1st Jan | 2nd Jan |_ 3rd Jan and so on.

He was manually keeping a log of updated code at every stage. Don’t you think this was kind of redundant ant time consuming? This is where version control kicks in. Imagine a scenario where in, I can code, update my changes and add it as a commit to my remote repository. Inform the tester about the updates, he/she does a checkout of the latest version of the code. Adds review comments to the commit. I read those comments, make the changes and then commit my changes. Makes more sense doesn’t it? Well Git is one such tool, which I’ve grown to love. I must thank my friend Senthil for introducing me to Git.

If your on Windows, you need to download and install git. (Link) Mac comes with git preinstalled :-) Edit : I’m so used to having Xcode installed on any Mac that I thought Git actually came pre installed with Mac. Correction, it doesn’t, and must be installed from here (Command Line Tools) or via HomeBrew as suggested by my friend Akash. Linux, download and install (Link)

If your adding git support to an existing project

  1. Navigate to your source directory.
  2. Type
1
git init
  1. It initializes an empty repository
  2. Next, type
1
git add .
  1. This adds all the current files to git
  2. Next, type
1
git commit –a –m "Initial Commit" # Or whatever message you find suitable

If your starting a new project

  1. Create a new directory
  2. And follow steps from 2 to 9 from above
  3. The only differences will be, as and when you add new files, they aren’t tracked by git by default.
  4. You need to add them by typing in
1
git add .

Next, I’ll talk about adding remote support. Remote support works best in a Unix environment

  1. Create a new folder in your remote machine as .git. The.git is not mandatory.
  2. Then key in
1
git init –-bare
  1. This initializes a bare repository
  2. Head over to your machine and navigate to the project folder
  3. Key in
1
git remote add origin <username>@<host>:<path>
  1. This adds a remote using ssh to your git repository
  2. Once done. Key in
1
git push origin master
  1. You’ll be asked for credentials, supply the same. You can skip this by using ssh keys.
  2. As and when you make changes to one of your Local copies, commit and then push to the remote.

That’s it. Git is cool to use, and its even cooler to share your code to others via sites like github, gitorious, etc.


The Indian IT Industry

I don’t know how many nerves I’m going to tickle with this blog post. But, heck who cares it’s a free world. I got a right to voice my opinion.

Here’s the Life of a typical Indian Software Engineer.

  • Take up an ECE/CSE/IT degree. (nowadays even a Bio Tech Engineer is welcome :-))
  • Get placed via Campus in Company I, T, C, A or W (I’m not taking names here :-))
  • Undergo Training (Engineering students don’t learn more than C and Java, CSE/IT included)
  • Once they’re done with their training, send them into a Project which they have no familiarity with, wait, I‘m not complaining here, how’s a Software Engineer one, if he’s not Technology agnostic?
  • He/she works on .net, J2EE, Mainframes, ya that’s all that exists for them.
  • Has no clue how the code works as he/she’s supposed to modify code written by someone else, who, well has no clue, just like the one trying to do so
  • Wait till they get sick of the Job, switch…. And this cycle continues. From what I can see from this pattern, I find that no one, likes what they are doing. Of course, they aren’t going to like it, as they didn’t go there out of choice, but only because that’s the job that paid more

How many software Engineer’s do you guys know, who you could call upon to fix your computer? They themselves need one. Creating software is a Job, not a Passion. Out of 100 people I can find only a handful, who actually know what they are doing, and enjoy it. Almost everyone does what they are doing as its their source of income, and nothing more.

I had complaints about the Education System here, and hoped to find the Corporate Sector free of such quirks. But, no, it might be better than the Education System. But, its got its own set of problems.

Programming is something that you got to be passionate about. When your bored and have nothing more to do, and you end up opening some old code of yours, find it to be junk and then sit back, wonder how bad your code was, spend time in refactoring it to perform better. You got passion. You find a skilled artist who’s in love with his job, constantly looking at bettering himself. Programming is an art.

Software is something that helps you make your day to day tasks easier to perform. Every piece of software written which has truly survived, was written with a purpose to better the standard of living for a human. And was not intended at being a money making tool. The money will come. But the idea is what matters.

You don’t need 100 people to do 10 people’s job. You don’t make 100 disoriented people work on something to make a mess and then get 10 good people to just clean up the mess. It would be better to motivate all the 100 instead. Make programmers out of them, not Coders.

Programming is a passion. Don’t make it a JOB.

I hate to see people who just hate their Job. Lets try to drive in some passion. Not everyone needs to born with a passion. If you don’t have it, try nurturing it. Help your fellow people. People say that your born with a talent and that is what you eventually pursue as your career. People talk about having interest in a particular field. If you ask me, God made Humans and gave them a forest to eat from. His only career would’ve been farming! Everything else is man made. It’s the path we have taken in our lives, the thoughts put into us by people that drives an interest in our career. We can all excel in whatever we are doing, if we just begin to like what we do. Make your job your passion!