Tuesday, 5 August 2014

Learn A Pattern A Week With Pie - Builder Pattern

Welcome back to our series on design patterns.

This week our focus will be on the Builder pattern, a creational pattern which provides ways to construct a complex object one step at a time.

So let's say you've a class called Student with a constructor which accepts 3 parameters; firstname, lastname and department. Obviously, creating an object of our hypothetical Student class is a no brainer. Just pull out your editor and fondle some few keys to get it done as shown below:

Student s = new Student("Edward","Pie","Computer Science");

The above snippet is easy enough to be memorised by a day old chick, isn't it?

What if you'd a constructor which accepts 10,15,20, or more parameters? Would you still go by the strategy above? Yes or No? Be honest!

Wait babe, don't flush in 10,15,20 or more arguments into your constructor. That's gluttony and you know that's unprofessional. And now you're wondering, "what else can I do?" Uuhhhhm! Ok lemme create a parameterless constructor and throw in a bunch of setter methods to set properties on the object.
Really? Mr. holy sinner, there's a better way (ask your parents).

Aaaah! I caught you there, now you're scratching your head and you're saying "what the heck am I to do?" Tadaaaaah! The Builder Pattern says, "hey! I am every heck you've to do"

The Builder Pattern

This is a pattern for constructing complex objects in a step-by-step approach using simple objects. In this pattern, a Builder class which is independent of other objects builds the final object in succession of steps.
This pattern falls under the creational pattern in the GoF's grouping of design patterns.

Ti's Time For Hands-On

Let's have a practice lab session and try out one of the simple ways of implementing the builder pattern.
We'll continue working with our hypothetical Student class, this time it accepts 6 parameters instead of 3. Six parameters aren't too much to be supplied as arguments to a constructor but we're sticking to 6 parameters just so it'll be easier to understand. You'll be able implement a Builder for a much complex object after understanding this.

The 6 parameters for our hypothetical Student class are firstname,lastname,department,cwa,level, and hallOfResidence.

See a simple implementation of the above scenario below:

I admit you've to add extra code to implement the builder pattern for such a simple scenario but the focus is on being able to construct complex objects in a step-by-step approach. With the builder pattern, you're able to chain a series of setter methods calls with each call taking the object under construction a step further.

Consider a typical real world situation where you take your car to the car repairs shop, the fixing of your car's problems may start with the welder welding broken pieces together, the auto-electrician fixing electrical problems, the mechanic fixing your engine and finally the sprayer giving your car a new look. You'll agree with me that the movement of your car from one expert to the other takes it closer to your final goal, fixing your car. This is how the builder pattern works. It helps you to construct complex objects in a step-by-step manner.

There are other ways of implementing a builder but for the sake of understanding I chose a very simple approach.

Your comments, suggestions, questions and criticisms are welcomed here or on Facebook.

Thanks for learning with me. See you in the next post!

Remember to have fun!!!

Sunday, 3 August 2014

My Highly Opinionated Thoughts On Learning Programming

This is gonna be a rather long and highly opinionated post on mastering programming so I advice you grab a cup of coffee and sip slowly as you read with an open mind. Like I said, the points aren't laboratory certified ways of mastering programming 1, because I'm not a master programmer yet (at least per the people I keep as mentors) and 2, because what worked for me may not work for you. Pass what you read here through your own filters, assimilate what resonates with your style and shove the remaining shit out of your brain.

Choosing A Programming Language

I'll urge you to love to be a polyglot (be able to program in multiple programming languages). Choose at least 1 mainstream programming language eg. Java or C# .NET or PHP and some other non-mainstream programming language eg Python, Ruby, R etc. Your location determines what's mainstream and non-mainstream. In Ghana, Java & C# are mainstream. Also, master different languages for the different paradigms especially OOP and functional programming. If the only tool you've is a hammer, every problem appears to you as a nail. It easier to find a not-so-well-paying job with your skills in the mainstream. Conversely, it's difficult to find a job with your skills in the non-mainstream but remember to say thanks to Pie when you hit that high paying job which needs your skills badly.

Master Syntax & Semantics

The best way to learn any programming language is to master the syntax and semantics of the language. Don't sit all night cramming crap you don't understand into your head. Until you learn to understand, you can't really build good stuff with your language of choice. Don't rush it. You aren't in any race. Slow it down, learn it well, understand it and use it well. Learn to share your knowledge freely once acquired. Don't fool yourself by thinking it's an advantage if only you can do it. You know why? Simply, you don't know shit. People know more than you do yet they are humble and love to share. The more you teach, the more you understand.

Learn & Apply Design Patterns

You don't know of design patterns? Meeehn, you're so not current. A simple Google search will land you on some awesome sites where you can learn and apply design patterns. It will help you avoid writing spaghetti codes and also shun voodoo programming. Don't spend hours wondering how to write some piece of code. Some older dude faced similar issues, fixed and documented the procedure just to make life easier for your lazy ass. Sorry, you ain't lazy, you wouldn't have read this far. lol!

Read & Write Lots of Codes

Until you read code written by others you may think you're the best programmer ever created. Code writing is easy, code reading isn't. Every developer thinks the other guy who wrote the code he's been called to maintain is an idiot. Why? Simply because you've bad code reading habit or maybe the guy was indeed an idiot, a typical text book example of an idiot. The pun and jokes not withstanding, take these points serious. You learnt how to write code, you've to learn how to read code as well. Join some open source projects, get insulted and intimidated by the experienced dudes. They won't forgive you for posting stupid code, you'll get hurt but you'll dare not repeat yourself.

Invest In Your Skillset & Toolset

Make learning a life-long process. Buy books if you've the means, watch video tutorials. Never enter tomorrow being the same person you are today. Wake up every morning knowing you're a better person. Buy good computers. Use your snail-paced PC for a doormat. Save and buy some fast computer, at least fast enough to launch your IDE before you blink 10 times. Know what you don't know and never be satisfied with what you know. If you don't know, and you don't know that you don't know then you're a fool.

Have A Mentor, Be A Mentor, Change Mentors & Don't Be Changed As A Mentor

Have A Mentor
Whether you like it or not, you aren't the best programmer. Every other programmer, even the greenhorns know something about programming that you don't know. That you've programmed for 20 years doesn't make you the best programmer around. Stop crowning yourself in your utopian world. Shove your pride up your ass, step down, get someone who's better than you, humble yourself and learn from this guy.  Choose a mentor and learn from him.
Be A Mentor
The best way to learn is to teach. You'll hardly forget what you've taught over and over. Don't be stingy with your knowledge. The truth is, you don't know jack. Others know more than you do yet they freely share. If someone sat on this knowledge you wouldn't get to know of it. Count the number of books around you, the number of videos freely available, the write-ups, the blog post etc. How greedy and stingy can you be. Can you lock up the whole internet into your pocket? You see, there's no sense in holding onto some knowledge as though it's your personal property. Share! Share!! Share!!!
Change Mentors
Once you're able to communicate with your mentors at par, you are colleagues. At this point, a wiser thing to do is to choose you mentor's mentor as your new mentor or choose someone better than your mentor as a mentor. Whether you like it or yes, there's always someone up the the ladder. Hating is diabolic and unhealthy. Humility and curiosity is key to the acquisition of knowledge. Acknowledge the fact that your aren't the best and you won't be the best but you can be among the best. Change your mentors frequently. It's a measure of how fast you're growing.
Don't Be Changed As A Mentor
If your mentee  chooses another mentor it means he's got to your level and you aren't growing. Keep growing your knowledge. Learn as though you're gonna live forever on earth. Find great joy in increasing your technical know-how on a day-to-day basis.

Don't Be Complacent

In the land of blind men, the one-eyed man is the King. In Ghana, anything above a freaking HelloWorld is worthy of an award. That there are few techies around doesn't mean everything should be over hyped. A full grown hairy man creates a damn app which notifies you when you get a letter at the post office and it get featured in our contentless media. You build static websites and get carried on shoulders by incompetent people holding highly influential positions. Hey, village programmer, Ghana or African isn't the only place on earth. There are better programmers elsewhere who are worth looking up to. Truly, there are equally good local programmers who are worth mimicking. Have big dreams. It's not about an app which tells you how much damn calories you've burnt. Who cares if your burnt the hell out of yourself. It's only about solving the very simple problems in society. Guys, stop acting as though you're at silicon valley. Silicon valley ain't no joke. Here's silicon savannah, embrace it. Know where you are, know where you wanna go to and you'll know how to get there. Kill your pride because your pathetic degree isn't even a match for someone's primary education. You were taught Computer Science by some lecturers who haven't even written code to parse a file. Your final year project was a useless blah blah blah management system which is sitting in dust by now.
I'm telling you the hard truth you've never heard and you're probably thinking "who the hell does this Pie dude think he is". Sorry man, I'm an honest and proud African who wants Africans to be known for the good things we do and not the copy-cat wanna-bees we've been for decades.

Have big dreams, dream about working for intelligent tech companies across the world. Work with some of the smartest people around. Learn from them! It's not only about some half-assed software. It's not about engaging in mental masturbations. Thinking you're the best. Stop painting Africa black with your mediocre bullshit inventions.

I don't think of my self as the best programmer, I only aim to be among the best in the world and that's what I'm constantly working on becoming.

Get real!!!

Tuesday, 17 June 2014

Learn A Pattern A Week With Pie - Singleton

Our focus this week shall be on a very simple yet useful design pattern, the Singleton Design Pattern.

So What's The Singleton Design Pattern?

Like a lonely guy, a singleton class has one and only one object instantiated application-wide. The Singleton pattern is categorised as a creational pattern because it provides a very good way of instantiating objects.

This pattern usually involves a single class which takes absolute responsibility of creating it's own object while ensuring no one else does and also ensuring that only one object gets created. A singleton class also provides access to it's only object directly without the need to instantiate an object of the class.

Classes whose purpose is to provide application-wide services are good candidates of the singleton design pattern. To this effect, the singleton pattern is used for components like Loggers, Drivers, Thread Pools, Caches etc.

What Does It Take For A Class To Be A Singleton?

Note that, the whole essence of the singleton design pattern is to ensure that only a single instance of a class exists application-wide and this single object should only be created by the class itself. This means the following conditions should be met:

1. A Private Constructor : The singleton class should have a private constructor to ensure that no object of the class can be created outside of the class itself. Without a public constructor no other code can create an instance of a class. Making the class' constructor private prevents other classes from creating objects of this class. In this case, only the class under discussion can create an object of it's own self.

2. A Private Static Instance : There also need to be a private static instance of the same class that is the only instance of the class. Since an object of the class can never be created outside of the class, we'll need to explicitly instantiate an object of the class under discussion. This single instance should be made static and preferably final as well just so we wouldn't have to instantiate an object of the class (which can't be done anyways) before accessing it.

3. A Public Static Method : This static public method (usually named 'getInstance()') is the global access point for the outer world to get a reference to the single instance of the class under discussion.

I think we've had enough theory to get you confused now! Let's do a hands-on exercise to clear the confusion.

In our hands-on exercise, we'll create a hypothetical database connector class which should help us to execute queries any where within our application. NOTE : We won't actually do any database programming here, we'll only simulate the operations.

In this exercise, we've created a pseudo database connection manager with a public API which is supposed to return a list of all the employees in our database. Assuming this data is so central to our application that we'll want to be able to access it anywhere in our codebase without having to explicitly instantiate objects of our DatabaseManager class, we've made our DatabaseManager class a singleton class.

This means anytime we want to access the list of employees in our database, all we've to do is to call DatabaseManager.getInstance().getAllEmployees();

DatabaseManager.getInstance() will return the only instance of our DatabaseManager class which we'll want to exist application-wide. We then invoke .getAllEmployees() on the instance returned.

Traditionally, we would have written the following lines of codes anytime we wanted to access our employees records.

DatabaseManager dbManager = new DatabaseManager();

The above code does not only demand that we type too much characters, it also wastes system resources because anytime a new DatabaseManager object is created, the database connection driver will have to establish a connection to the underlying DBMS and also perform some house-keeping chores.

Implementing this class as a singleton will ensure that our database connection driver performs it's bootstrapping chores only once. It also ensures that only a single instance of this class exist which helps us to keep a global representation of our class.

Note that we've used a database manager in this example but you can always use the singleton design pattern whenever you want to create a class to provide application wide services.

This is the simplest way to implement a singleton class. We'll take a look at other variants later.

Meanwhile, leave your questions and suggestions using the comments box below and let's learn together.

Let's write clean codes one character at a time!!!

Monday, 16 June 2014

Learn A Pattern A Week With Pie - Overview

As promised, we're gonna learn a new design pattern each week to make us better programmers, programmers who write clean and maintainable code. If any code was ever written by a good programmer, that code would probably not need to be commented.

To make the learning easier and full of fun, am gonna make my post very simple, byte-sized chunks which can easily be learnt, understood and memorised in the shortest possible time.

Today, I'll give you an overview of the various groups of design patterns out there and also learn about the GOF.

So What Is The GOF Thingy?

GOF (Gang Of Four) refers to a group of 4 authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides who in 1994 published a book titled "Design Patterns - Elements Of Reusable Software" which initiated the concept of design patterns in Software Development.

I just felt I should make mention of these reverend authors and pioneers of such an important subject in Software Development since no self-respecting book or text on this subject matter would be complete without making reference to the Gang Of Four.

Types Of Design Patterns

Per the book Design Patterns - Elements Of Reusable Software written by the GOF, there are 23 design patterns classified into 3 major categories: Creational, Behavioural & Structural Design Patterns.

In my subsequent posts we'll study each of these 23 design patterns identified and outlined by the GOF in their book.

Meanwhile, let's take a look at the criteria for grouping these 23 design patterns into any of the 3 categories.

NOTE : Java will be used for the code samples in all my post. It shouldn't be difficult converting those sample codes into other OOP languages!


Instead of using the "new" keyword in Java to instantiate new objects of classes, the creational design patterns provides ways of creating objects whiles hiding the logic for creating the objects. This gives more flexibility in deciding which object needs to be created for a given use case unlike using the "new" keyword.


These patterns are concerned with how objects within our programs communicate across their interfaces.


These patterns concern classes and objects compositions. In these patterns, inheritance is used to compose interfaces and define ways to compose objects  to obtain new functionalities.

Don't worry if all these seem too abstract and incomprehensible. Just hold on for a ride and things will be better once we start studying all the 23 patterns one-after-the-other.

May today kick yesterday's ass!

Friday, 13 June 2014

Learn A Pattern A Week With Pie - Introduction

What Are Design Patterns?

Design patterns are a documented set of best practices used by experienced object oriented programmers. These are solutions to general problems that these experienced programmers once faced during software development. Through numerous trials and errors, these solutions were finally obtained, standardised and documented over quite a substantial period of time.

Why Should I Care About Design Patterns?

Design patterns have evolved over a period of time and they provide splendid solutions to certain problems faced during software development.

The un-experienced or green-horn programmer will learn software design in an easy and faster way. Learning design patterns will help you avoid common mistakes which experienced programmers made in the past. This way, you'll be saved an invaluable quantity of time which you can use to do something else.

Design patterns also set a common platform for programmers. It provides a standard set of terminologies which are specific to particular scenarios. For example, a singleton design pattern signifies use of a single object application-wide so all programmers familiar with this terminology will make use of a single object and can tell each other that program is following the singleton pattern.

Design patterns also set a yard stick with which we measure clean codes. Learning design patterns will help any programmer to avoid writing hard-to-maintain-code. Design patterns will help you develop software packages which are closed to modification but open for extensibility.

In my own opinion, one good way of becoming a good programmer is to follow the following route:
1.    Choose one main-stream and one non-main-stream language. Eg Java or C#.Net & Python or Go
2.    Master the Syntax & Semantic of the languages you've chosen
3.    Master the Object Oriented Concepts & Constructs. Eg Polymorphism, Encapsulation etc
4.    Master Design Patterns and know how to apply them in your languages of choice.
5.    Write & Read a lot of code
6.    Never enter tomorrow being the same person you are today. Learning is a life-long process.

If you enjoyed this post, join me as we learn a new design pattern every week.

Enjoy your weekend!

Wednesday, 29 January 2014

According JavaScript The Respect It Deserves

One common misconception and practice among developers is the assumption that we can hop into the world of JavaScript and start writing useful code simply because we already know how to program in C,C++,Java or C#.

We learn how to declare variables using the var keyword, how to get handles to DOM elements with
document.getElementById("id") or getElementsByClassName("className") how to dynamically manipulate the styles attached to DOM elements and finally register event callbacks to be invoked for specific browser events.

The recent outburst of awesome JS libraries such as Angular JS, Backbone JS, Knockout JS, JQuery, D3 ect proves the power of the world's most used language, JavaScript. JavaScript is the engine that powers the web of today. It's the reason for the responsive web apps we enjoy today.

The power of JavaScript goes beyond mere DOM manipulations. It is a very powerful language when given the necessary respect. Though it was released prematurely by NetScape during the browser war era, JavaScript shipped with some really good stuffs. Despite the nasty side of JavaScript, it does more than simply manipulating DOM elements and handling of callbacks. The good sides of JavaScript is the reason why it was the best fit for developing Node JS, a server side JavaScript engine for implementing highly responsive, non-blocking and near realtime web apps.

JavaScript is an Object Oriented Programming language with constructs similar to classes, constructors and inheritance as we know from other mainstream OOP languages like C++, Java , C# etc.

For most of us, our learning of JS never comes to this street of OOP. JS is really cool when used from the good side.

To further build your understanding in JS, I recommend these books which I recently bought from leanpub

1. JavaScript, The Good Parts
2. Principles Of OOP in JavaScript

And finally to learn more client-side JS you can try

3. The Definitive Guide To JavaScript.

Isn't it time to say hi to JS?

May this year kick last year's ass!

Tuesday, 28 January 2014

Groking The Android Emulator

The Android SDK offers a bunch of mouth-watering tools to developers to increase their productivity. Most of these tools are second-to-non when compared to the tools provided by other rival mobile platforms such as Apples iOS (XCode).

One of the most outstanding tools in the Android SDK is the Android Virtual Device, A.K.A Emulator. In this post, am gonna show you how to have fun with the Android Emulator. I assume you already have your SDK setup and some ADVs created.

Now run an instance of the emulators shown in your AVD Manager.
Each instance of the emulator is bound to a port number which is shown on the title bar of the emulator window. My emulator's port number as at the time of this post shows 5554. (Yours may be different anyway)

Now, let's connect to the running emulator via telnet.
Open your terminal or command prompt and execute the following command

telnet localhost 5554 (Replace 5554 with the port number shown on your emulator)

If everything goes as planned you should see an output similar to

Trying ::1...
telnet: connect to address ::1: Connection refused
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands

If you've got this output in your terminal just jump and shout hurraaaay! (watch out for the ceiling fan)

Now all is set to grok the emulator

1. Let's change the network status from 3G to Edge and back
network speed edge
Observe your emulator's signal indicator changing to show edge
Now type
network speed 3g
Observe your emulator's signal indicator changing to show 3G

(Wait! Wait!!, don't jump yet)

2.Let's simulate an incoming sms
sms send 0200662782 "Howdy?, Mr Spanky emulator" (Change the phone number)
Observe your emulator's notification bar as your girlfriend drops in a new romantic message
Mind you, this isn't a replacement for WhatsApp, Lol!

3.Let's simulate a low-battery environment
power capacity 4
Observe your battery indicator drop to 4%
Don't keep doing this cos you don't know when ECG will get you a real low-battery situation.

There are tonnes of command you should know of. Apply whatever you've learnt here to simulate such situation when needed to test your apps in the emulator.
Want to be a groking monster? Point your browser here.

May 2014 kick 2013's flat ass!!!