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();
dbManager.getAllEmployees()

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!

CREATIONAL PATTERNS

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.

BEHAVIOURAL PATTERNS

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

STRUCTURAL PATTERNS

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
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK

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

NOTE :
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!!!

Thursday, 12 December 2013

Generating Barcodes In Python

There are almost 2.7 million searches related to the term “barcode” each and every month on Google.
 It’s no wonder that barcoding is such a large topic for small businesses. Can you think of anything in this day and age that doesn’t have a barcode?
Barcodes have revolutionized the way we do business today. They allow you to run your small business more accurately and efficiently, getting you ready for growth. You’ll look more professional too!
Programmers these days are required to know just enough about barcodes in order to implement any serious shop management system or product identification system. However the barcode specification spans many pages. This means, it's impractical for any programmer to fully understand how barcodes work behind the scenes before being able to generate them from their codes.

There are a lot of software libraries out there to help in the generation and scanning of barcodes. For example, the ZXing library is a suite of java libraries for working with barcodes from the Android platform to JSE and JEE (Servlet Containers).
There is also Barcode4J, a freely available software library for generating and scanning barcodes in java.

Scanning of barcodes in a shop management system is actually a quick replacement for the keyboard. That is, instead of searching products by typing lengthy product codes into the software, a barcode scanner simply scans the barcode image and feeds the product code into the software for searching.

Of all the libraries around, I choose ReportLab, an amazingly free python package for generating PDFs. Aside it's extensive support for PDFs, it generates all kinds of barcodes including QRCodes.

The procedure for installing ReportLab is clearly laid out on their site.

Now with ReportLab installed, let's get our fingers dirty with some python codes
In our first example we will generate a simple PDF document showing "Hello World"
Open up your text editor and type in the following codes

from reportlab.pdfgen import canvas

c = canvas.Canvas("hello.pdf")
c.drawString(100,500,"Hello World")
c.save()

After executing this python code, you should see a file, "hello.pdf" in your current working directory. Open it with any PDF reader and say a big thanks to the ReportLab team for such a fantastic offer.

The details of how this piece of code works is spelt out in the ReportLab documentation.

Now let's generate some simple barcode. The details of the different types of barcodes are out of this post's scope but in this example we will be generating a EAN13 barcode, an european standard barcode format for most products in shop. The ReportLab library is capable of generating all other kinds of barcodes. Just read the fu*king manual.


from reportlab.graphics.barcode import eanbc
from reportlab.graphics.shapes import Drawing
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF

#Setting up canvas for pdf
c = canvas.Canvas("barcode.pdf")
code_number = "1234567899087" #This is the number for which the barcode is to be generated

#Generating a EAN13 code
barcode = eanbc.Ean13BarcodeWidget(code_number)

#Drawing generated barcode onto pdf
drawing = Drawing(50,10)
drawing.add(barcode)
renderPDF.draw(drawing,c,100,100)

c.save()



This is all there's to generating and saving a barcode to a PDF. Applying your own logic, you should be able to generate countless unique barcodes, print them out and stick them on your products for identification.

Lemme know of your questions by commenting.

Happy Coding!!!

Tuesday, 5 November 2013

Switching Android Activities : Fade Out - Fade In Animation

In this post, I will show you how to implement a basic slide-out-slide-in transition animation when switching between Activities in an Android application.

Animation in Android can be implemented either in Java code or XML markup. In this post we will use the latter approach. A similar post will be published on implementing animations in Java code.

We are going to make some assumptions. We will assume that we have 2 activity classes, ActivityA and ActivityB. Now when a button is clicked on ActivityA, we want it to slide out and ActivityB will slide in.

To define the animations in xml, create a file call fade_in.xml in the anim directory found in the res folder and paste the following code.

NOTE : The filename could be any valid android resource name

CODE FOR slide_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="500" />
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="100" android:startOffset="200" />

</set>

Create another file called fade_out.xml in the anim directory found in the res folder of your project and paste in the following code. Again, the name of this file could be any valid android resource name.

CODE FOR slide_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="500" />
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="100" android:startOffset="200" />

</set>

EXPLANATION :
<translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="500" />

The above code means the X position of the sliding Activity should change from -100 to 0 in 500 milliseconds.

<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="100" android:startOffset="200" />
The above code changes the transparency of the sliding Activity from 1 to 0.

To show ActivityB following an event in ActivityA and apply the defined animations use the following code

startActivity(new Intent(ActivityA.this,ActivityB.class));
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

If you don't understand anything just write it in a comment and get it answered.