Design Pattern: Singleton

“Beauty!”, when I see some really amazing code that is my first reaction, but what makes a piece of code beautiful? Is it neatly named variables? Is it the uniform indentation?

Well the answer is yes but there is something a little more than these factors and that is an elegant  solution to the problem. When I say elegant solution what is that I am talking about ? What makes a solution elegant? It is the way you approach a problem.

Design Patterns in the programming world adds to the beauty of the solution, it sometimes feels that it is the missing piece of the puzzle. And the solution so magically fits to solve the problem. The various patterns that I came across are Singleton, Mixin, Pub-Sub etc. The way I approached it and studied them is a little different, design patterns are actually tailored way to react to a given situation.

Let me elaborate on that now suppose there is an emergency and somebody got hurt, what is the first thought that comes to your mind ? It is to handle it using First Aid, this is actually a catered thought which has been imbibed in us from ages and people have design First Aid boxes in such a way that it has all the first come fixes for all the emergencies.

For me I see Design Pattern in the same manner it has gone through the test of time and proved to be the best way to solve a specific type of problem.  It is like a ready made template but you should be aware enough to know the problem and to know the pattern that solves that problem. 

I have read about a lot of design patterns but to be very frank I have seldom seen one being applied in the code-base that I have came across, this could be because I have not appreciated it much and also because I was not able to observe the pattern. It was very recently when I was working with Gautham Sir I began to appreciate the beauty of it. We were writing a utility in jnaapti using EcmaScript 6. He made me feel to appreciate the beauty of it and taught me how to implement it as well.

Let us break it down more and see the type of problems in which Singleton design pattern can be used.

What is Singleton design pattern?

A Singleton design pattern puts a restriction of returning the same object irrespective of how many times the class is being instantiated. This makes sure that whatever is the state of object that state is preserved. Don’t be overwhelmed if you are not able to understand it now it will make more sense once you see the code.

The benefit you get is having a kind of a global store where you can put in data and retrieve it when you desire to.

Lets us make it more clear imagine there is a class Library now through out the life cycle of the software what we want is there should be only one Library object and when ever I get this object I should be able to add and delete books from the library hence modifying the library now when I do this the library object anywhere being use should get this information.

Lets chalk out some code and try to understand it, I have 3 files Library.js, Customer.js and LibraryPlayGround.js.  The content of those file are very straight forward.


Now we need customers or readers for simplifying things i have only included on one method that is return books.


Once all this is done we need a playground where we can see things happening and experiment with it.


Now if you see the code farhaan object has tried to access the same Library object that is being exported. No matter what it well return the same instance which has been instantiated in the beginning of the lifecycle of the software. This is how I tried implementing Singleton .

I have used ECMAScript here to demonstrate that concept and to implement it, I am a learner so there could have been certain things I wouldn’t have made clear, you can leave a comment regarding the same, if you have something to add I would love to know.

Till then Happy Hacking

Functional Programming 101

“Amazing!”  that was my initial reaction when I heard and read about functional programming , I am very new to the whole concept so I might go a little off while writing about it so I am open to criticism .  This is basically my understanding about functional programming and why I got hooked to it .

Functional Programming is a concept just like Object Oriented Programming , a lot of people confuse these concept and start relating to a particular language , thing that needs to be clear is languages are tools to implement concepts. There is imperative programming where you tell the machine what to do ? For example

  1. Assign x to y
  2. Open a file
  3. Read a file

While when we specifically talk about FP it is a way to tell how to do things ? The nearest example that I can come up with is SQL query  where you say something like

SELECT  * FROM Something where bang=something and bing=something

Here we didn’t tell what to do but we told how to do it. This is what I got as a gist of functional programming where we divide our task into various functional parts and then we tell how things have to be implemented on the data.

Some of the core concepts that I came across was pure functions and functions treated as first class citizen or first class object . What each term means  lets narrow it down .

Pure functions  is a function whose return value is determined by the input given, the best example of pure functions are Math functions for example Math.sqrt(x) will return the same value for same value of x. Keeping in mind that x will never be altered. Lets go on a tangent and see that how this immutability of x is a good thing, this actually prevents data from getting corrupt.  Okay! That is alot to take in one go, lets understand this with a simple borrowed example from the talk I attended.

We will take example of a simple Library System  now for every library system there should be a book store, the book store here is an immutable data structure now what will happen if I want to add a new book to it ? Since it is immutable I can’t modify it , correct ? So a simple solution to this problem is every time I add or remove a book I will actually deliver a new book store and this new book store will replace the old one. That way I can preserve the old data because hey we are creating a whole new store. This is probably the gist or pros of functional programming.

book_store = ["Da Vinci's Code", "Angles and Demons", "The Lost Symbol"]
def add_book( book_store, book):
    new_book_store = []
    map(lambda old_book: new_book_store.append(old_book), book_store)
    return new_book_store

print add_book(book_store, "Inferno") # ["Da Vinci's Code", "Angles and Demons", "The Lost Symbol", "Inferno"]

print book_store # ["Da Vinci's Code", "Angles and Demons", "The Lost Symbol"]

In the above code you can actually see that a new book store is returned on addition of a new book. This is what a pure function looks like.

Function as first class citizens , I can relate a lot to this because of python where we say that everything is a first class objects. So, basically when we say functions are first class citizen we are implying that functions can be assigned to a variable, passed as a parameter and returned from a function. This is way more powerful then it sounds this bring a lot modular behavior to the software you are writing, it makes the project more organized and less tightly coupled. Which is a good thing in case you want to make quick changes or even feature related big changes.

def find_odd(num):
    return num if(num%2 != 0) else None

def find_even(num):
    return num if(num%2 == 0) else None

def filter_function(number_list, function_filter):
    return [num for num in number_list if(function_filter(num) != None)]

number_list = [1,2,3,4,5,6,7,8,9]
print filter_function(number_list, find_odd) # [1,2,5,7,9]
print filter_function(number_list, find_even) # [2,4,6,8]

In the above code you can see that function is passed as an argument to another function.

I have not yet explored into lambda calculus which I am thinking of getting into . There is a lot more power and beauty in functional programming.  I want to keep this post a quick read so I might cover some code example later, but I really want to demonstrate this code.

def fact(n, acc=1):
    return acc if ( n==1 ) else fact(n-1, n*acc)

where acc=1  this is pure textbook and really beautiful code which calculates factorial of n ,  when it comes to FP it is said To iterate is Human, to recurse is Divine. I will leave you to think more about it, will try to keep writing about things I learn.

Happy Hacking!

Crypto 101

I was not keen on cryptography before this incident, so I was working on this PR for pagure where I had to write a feature which give  the ability to local user to change the password. You can see the PR here. There are two ways to login to pagure FAS account if you want to use pagure online else if you are hosting it you can use local authentication. I learned a lot from this feature  for starting “how not to write authentication system” that is because the first PR I sent was all about the wrong practices thanks a lot to Pingou and Peter to correct and guide me on how to do it.

Peter pointed me out to this video which cleared a lot of my questions. So some of the basic rules for writing an auth. system is :

  1. Never ever store password
  2. Always adopt the latest encryption technique
  3. Use constant time function to compare password

The technique we used is called salting, this is a very beautiful technique. Before going into salting we try to look into what is hashing because hashing generates a junk string using an algorithm, salting is just a different layer over it which makes this hashing more random. Hashing is a way in which password is converted into a string which cannot be inverted. Practically once you convert a string into hash there is no way you can retrieve it but the drawback is comes when two same string produce same hash string. Now if that is possible then it can be brute forced or rainbow tables can be used to get the password.

Here salting comes into the picture because with salting the entropy of the strings generated is exponentially increased and hence your site a little more secure because even you are storing password in your database even you can’t decipher the password all you see is a junk string. That makes your site secure and impenetrable.

Python comes handy with it, bcrypt is a library which give us a simple interface to use the functionality without getting into much detail.

Now here comes a tricky part we do not compare passwords directly we use something called a constant time function to compare passwords. The sole reason being the normal compare functions are written in such a way that the compare two strings as fast as possible which reduces their efficiency. When we are dealing with passwords accuracy is the most important factor not efficiency hence a constant time comparison function is used.

The PR evolved very organically and finally after discussing about various aspect we landed up writing test cases which exposed one of the vulnerability in the code. We fixed the error and then we went on to complete the PR, Pingou wrote most of the test cases and then after a lot of hard work and working for a long time the PR was finally complete. I even got my name in some of the files.

git commit -m”Best Practices”

git commit -m”Best Practices”

All of us who use some kind of revision control system have this problem especially the one who are new to the whole git commit thing . Well the question I use to have what do I write what I just did and how can it be helpful to others.

I got all those question answered when I was working on moving my patch from master branch to feature branch. Pingou asked me to squash commits and make the commit message more reasonable.

Not so good way of writing a commit

Some of the references I used was Peter Hunter’s Blog and Chris Beam’s Blog. And I landed up with these seven rules .

The seven rules of a great git commit message

  1. Separate subject from body with a blank line
  2. Limit the subject line to 50 characters
  3. Capitalize the subject line
  4. Do not end the subject line with a period
  5. Use the imperative mood in the subject line
  6. Wrap the body at 72 characters
  7. Use the body to explain what and why vs. how


But for all the single commits which is doing a minor change you can still use git commit -m “your message”. ( Try to keep message in imperative mood)

A better way of writing commits

For bigger changes you need an editor so you might want to use a switch -a. For more details on how you can do that in pro git. Finally I am changing my habits of those shabby commit messages. So, think twice before you commit. 😉



On 4th of this month we the Jnaapti team planned a small workshop to get 9th and 10th standard kids to get them started with programming . We visited Florence Public School and it was really a pleasant  experience to see such fresh minds exercising their mind.

I was really amazed to watch them apfps_kickstartersproach the problems we gave them, we have a rigid mind and we are really bad at thinking out of the box and that is because we have been taught rather conditioned to go in one direction.

But these kids they never knew this problem so they have a very different approach to these problem and I learnt about 7 new ways to approach the famous N-Queens problem.

Then came my favorite part “LABY”laby its a game which teaches programming in a fun way, so the whole idea is to make an ant to reach the door. There are various obstacles that needs to be handled and you know what you are going to use for that ?  CODE what else but its super fun to do that and we could see that in those kids. I learnt a lot that day like how will you explain conditionals , I am telling you it is not as easy as it looks.

Thanks to Gautham Sir, Shreelaksmi ma’m and Abraar for getting me this opportunity to do something this amazing , hope we will do more of such programs.