Monday, October 7, 2013

Implementing a simple factory

Ok so let's talk design patterns for a minute. To be specific the infamous factory. There is no doubt that the factory is quite handy, but what is it used for? Well, there arises a point when you are building an application and realize that you have a lot of similarly classified objects that need to be instantiated at some point in your code, but you don't know which one should be instantiated until the user or some other function implements it. Well a factory can allow you to instantiate those objects without worrying a whole lot about their actual implementation. Which is cool because then your objects become compliant with open-closed principle. But how exactly does this magical pattern work? Let's assume you have you have a system designed for selling different vehicles. Your company currently has objects set up for the busses, sedan and motorcycles it sells.


    public class Bus{
      public Bus(){
        //instantiation code here
      }

      //..
    }

    public class Sedan{
      public Sedan(){
        //instantiation code here
      }

      //..
    }

    public class Motorcycle{
      public Motorcycle(){
        //instantiation code here
      }

      //..
    }


This is great except then you realize that you are calling these individually throughout the business logic, meaning that each object is coupled to it's instantiating class pretty solidly. Sadly this makes your code fairly brittle and you end eventually updating code in dozens of locations when your requirements change. We've all been there and it isn't fun. What you want instead is to be able to replace all those areas with a more simple, more flexible solution that will allow you to get the object you want without necessarily having to be overly concerned about the implementation. So in swoops an interface to allow you to create a level of abstraction between you and the objects.



   public interface Vehicle{
     public String getVehicle();
   }


This means that each of your objects now look like the following.


    public class Bus extends Vehicle{
      public Bus(){
        //instantiation code here
      }

      public String getVehicle(){
        return "If you don't know what a bus is, look it up";
      }
      //..
    }

    public class Sedan extends Vehicle{
      public Sedan(){
        //instantiation code here
      }

      public String getVehicle(){
        return "A sedan is a car with 4 doors...sometimes";
      }
      //..
    }

    public class Motorcycle extends Vehicle{
      public Motorcycle(){
        //instantiation code here
      }

      public String getVehicle(){
        return "A motorcycle has 2 wheels.";
      }
      //..
    }


As you can see all you are doing is returning a String representation of the class name. Now that you are to this point you see that implementing these is just as easy as creating a factory using an class that will allow you to choose between them. So you code it up and get something like the following.



  public class VehicleFactory{
    public Vehicle createVehicle(String type){
      Vehicle vehicle = null;
      if( type.equals("bus"))
        vehicle = new Bus();
      else if( type.equals("sedan"))
        vehicle = new Sedan();
      else if( type.equals("motorcycle"))
        vehicle = new Motorcycle();

      return vehicle;
    }
  }


Now that we have everything in place let's make sure everything works.



public class FactoryMain {

public static void main(String[] argv){
Vehicle vehicle = VehicleFactory.createVehicle("bus");
System.out.println(vehicle.getVehicle());

Vehicle vehicle2 = VehicleFactory.createVehicle("sedan");
System.out.println(vehicle2.getVehicle());

Vehicle vehicle3 = VehicleFactory.createVehicle("motorcycle");
System.out.println(vehicle3.getVehicle());
}
}


There you go, now you have a factory implementation for your vehicles and all is right in the world.

Wednesday, September 26, 2012

Lists: A brief explanation

So recently I've been asked to try to explain a series of topics needed to have a decent understanding of programming and its constructs. I don't exactly consider myself an expert in all that is programming and this will likely challenge me as well. So where do we start? I thought I'd jump right in and go with Lists, hence the title, surprising right?

So what are lists? I'm sure that you have used lists for a number of things in your everyday life, such as grocery lists, or task lists, or Christmas lists. So to sum it up lists as you know are just a collection of items that can be either ordered or not. At this point if you have a basic understaning of programming you are likely thinking. Well that sounds like an array. And you would be correct. A list and an array are one in the same thing when we talk about programming. Now there are other types of lists that aren't arrays. This brings up so to our actual topic of today.

In the "lists" world we have a few different types of lists that exists. Today I am going to focus on linked lists. In the world of linked lists there are 3 types, single link, double link and circular. Circular isn't exactly a list type as much as a variation on single and double link lists. All this means is that the last element (tail node) is connected to the first element(head node) in such a way that when you attempt to access an element beyond the end of the list that you start back at the beginning. If the list is a circular double link list, then you are also permitted to access the end of the list by attempting to access an element before the start of the list. So lets see what this means exactly.

Single Linked Lists
A single link linked list is a list in which you can iterate from beginning to end and only in that direction. Each node is connected to the next node through a pointer. Lets take a look at an example. Lets say that we have a 3 element(A,B,and C) single linked list that is ordered. You end up with the following list.

A -> B -> C

You can see here that you start at node A and end with node C. This is very important, since unlike arrays, a linked list cannot begin iterating from arbitrary points within the list. They must start with the head or tail node. Unfortunately unless you are looking for value in the tail node in a single linked list, starting there is a bit pointless since you can't iterate backwards through the list. Now I'm sure you are thinking, 'what about circular linked lists? Certainly those would make the end node a reasonable place to start?'. While, you can start with the tail node in a circular single linked list, if you aren't looking for the end node it makes more sense to start with the head node and save yourself an iteration.

Now what if we want the ability to move backwards through the list? Yup, you guessed it, double linked lists. Now this is gonna be hard to understand so bear with me, we need to make sure that the nodes connect to the node before them. This would be represented with a similar graph to the previous example except it now goes in 2 directions.

A <-> B <-> C

That's insane right? Also notice here that we can start at the head or tail nodes and iterate over the list. We can still only start at the head or tail nodes, but now the list can be iterated over in 2 directions.

So now we understand the basic concept of the linked list. But how in the world do we translate that into code? Well first of all, the best way I know of to translate this is by using and Object Oriented approach. I'm sure its possible to accomplish using a non object oriented approach but I'm not sure it would look nearly as nice. For this example I will go with how to implement this in Java. If that's not your flavor worry not, for I will be adding implementations of this in other languages later on. Now for the linked list that in this example we are going to have it hold integer values to keep it simple. There are better ways to do this but those topics are beyond the scope of this post.

Java


class Node{
private Node prev;
private Node next;
private int val;

public Node(Node prev, Node next, int value){
this.prev = prev;
this.next = next;
this.val = value;
}

public void setValue(int value){
this.val = value;
}

public int getValue(){
return this.val;
}

public void setNext(Node node){
this.next = node;
}

public Node getNext(){
return this.next;
}

public void setPrev(Node node){
this.prev = node;
}

public Node getPrev(Node node){
return this.prev;
}

public void remove(){
this.prev.setNext(this.next);
this.next.setPrev(this.prev);
}

public void addAfter(Node node){
this.prev = node;
this.next = node.getNext();
this.prev.setNext(this);
}
}

Perl Sessions...filling in the gaps

I recently had to utilize the perl CGI::Session module and found the documentation a little odd and somewhat vague in certain areas. So for my sanity and hopefully anyone else that runs across this, I'm going to take a moment to explain how to use this module so that you too can get up and running quick.

Sessions...How do they work?

Sessions are fairly basic, the goal is to store some information on the client that will allow us to work around the Internet being stateless. Now there are only a couple ways to do this. The first way is the most common method of storing the user's session id in a cookie. But what if the user doesn't accept cookies? Well that would make the first method a bit hard now wouldn't it? Luckily we can always fall back on storing the user's session id in a hidden variable within the page. The Session module handles sessions in this way as well by defaulting to using cookies. Now I'm sure you are thinking, well great so you have an id for the user's session. But how do we use it? At this point you need to track the user on the server. To do this you can either:
  • save the session data to a file
    or
  • store the session data in a database table with the session id as the primary key.
Getting started:

Before we can use the Sessions module we need to make sure we have included both the CGI and the CGI::Session module. We also need an instance of the CGI object. The code to this is as follows:

use CGI qw/:standard/; # for parsing form data
use CGI::Session qw/-ip-match/;
my $cgi = new CGI();

Now that we have added the modules we can start a session. First, we usually want to make sure that the user doesn't already have a session open. To do this we use the following.

my $session_id = $cgi->cookie('session_name') || $cgi->param('session_name') || undef;

You see in the first thing we check is if there is a cookie in place with the name assigned to identify it with $cgi->cookie('session_name'). If there isn't one then we may want to check to make sure that there wasn't a hidden variable passed to the server with the session_id. Now that we know that we have the session_id set we can create a new session.

my $session = new CGI::Session("driver:File", $session_id, {Directory=>'/tmp'});

Here we are passing a few parameters to the Session() function.
  1. Driver : This parameter is used to define how the data will be stored. In this instance the data will be stored in a file.
  2. Session ID : The users session id. If the user already has a session open then this will use that users session. If it doesn't however, then the module will start a new session.
  3. Directory : This is used to specify what directory the module should save sessions to.
There is a lot more to the module than what I have explained here. You can get the full CPAN documentation here .

Wednesday, August 17, 2011

How stacks work, and how to implement

What is a stack?

A stack is a data structure in which elements can only be added and removed from one end. A good way to think about a stack is like a stack of plates. You can push(add) plates to the top of the stack or pop(remove) them from the top of the stack. The only way to get to a plate in the middle of the stack is to first remove the plates that are on top of it. Afterwards the other plates can be added back onto the stack.

1 ->

5 -> 1

9-> 1 5


1 5 9

You can see from the diagram above that as elements are pushed onto the stack they are appended to the end of the structure. Now if we were to pop the top value from the stack you would remove the top value. The result would be the following:


1 5

But what if I don't want to remove the element you ask? Well in that case you would just want to 'peek' at or read the value of the top element. This structure is usually provided in a library or as part of the language. In perl arrays already have these functions. But for the sake of the structure, the following code is a simple implementation of how this would be implemented in Perl.

$top = 0;

sub push{
my ($arr,$element) = @_;
$arr[top] = $element;
$top++;
}

sub pop {
my $arr = shift;
$elem = $arr[top];
$arr[top] = 0;
$top = $top -1;
return $elem;
}

sub peek {
my $arr = shift;
return $arr[top];
}

@arr = ();

push(\@arr,1);
push(\@arr,5);
push(\@arr,9);
print "@arr";
my $topElem = pop(\@arr);
print "@arr";
$topElem = peek(\@arr);

Tuesday, June 28, 2011

Why Object Oriented Programming: Part 1

The most simple definition of OOP I can come up with is that it is a programming style that allows us as programmers to encapsulate both our logic and data in an object, thus making it more abstract. By doing so, data becomes easier to work with while also managing system complexity as your code base grows. This is a large topic, and I am not sure that my description here serves OOP justice in just how useful it is. Over the next few posts I intend to explain how this abstraction helps and hopefully you'll find it useful.

What is Object Oriented Programming(OOP)?

Well if you have programmed in languages like Java, Ruby, C++ you are likely already familiar with OOP. This style of programming uses objects that have attributes and methods for defining the functions that can be performed on that object. Pretty simple right? Ok, so lets define some of these terms.

An object as I'm sure you have guessed is a programmatic representation of a real world object. For example, lets say that you want to create a program to simulate a car. Well the car is the object. But knowing that the car is the object is just the beginning. How is a car defined? Well we can assume that a car has a speed, a rate of acceleration, wheels, and it carries passengers. These 'definitions' of what a car is are called the object's attributes. So lets see what this looks like in code.

PHP
Java

class Car {
   private $speed;
   private $acceleration;
   private $wheels;
   private $numOfPassengers;
}






Here you see that we created the Car object with the keyword class. Why? The simplest way to put this is that a class is template for defining an object. In the object body we have our attributes defined as private. If you aren't familiar with this type of scoping, suffice it to say that this keyword allows us to ensure that these attritubes are only capable of being edited by the objects functions. I will be explaining how to properly use scoping keywords in a later post.

So now we have our object defined, but it really doesn't do much. At the moment this code is useless, what we really need now is a way to instantiate a new object. To do this we will need to utilize a special type of method called a constructor, which will initialize the object attributes.



PHP
Java

class Car {
  private $speed;
  private $acceleration;
  private $wheels;
  private $numOfPassengers;

  public __construct($spd=0;$acc=0;$wheels=4;$numPassengers = 1){
    $this->speed = $spd;
    $this->acceleratio = $acc;
    $this->wheels = $wheels;
    $this->numOfPassengers = $numPassengers;
  }
}



You see in the code snippets above that the 2 languages provide a slightly different way of declaring constructors but they both accomplish the same task of initializing the object. You may be wondering what is with the this keyword. What this does is tell the system that the following variable belongs to this object. Why do this? Well you may notice that some of the parameters that the constructor takes are the same as the object's attributes. Using this to specify the variable being set makes sure that the right variable is being used. By default if 2 variables have the same name the one pertaining to the current scope is used. Lets see a quick example:


this.wheels = wheels; //sets the wheels attribute to the value passed to the constructor
wheels = wheels;      //would set the value passed to itself accomplishing nothing.


So now we have his object but it doens't do anything. In an object's most basic form it should have accessors and mutators for each of its attributes. What are these strange method types I speak of? Well they do exactly what they sound like. An accessor accesses the data held in an attribute and returns it. Whereas a mutator takes a parameter and sets the value of an attribute to the value of the parameter. It should be noted that a mutator method by definition changes the state of an object and can therefore take any number of parameters and alter any number of object attributes. I usually recommend that a method not alter any more than is absolutely necessary. So lets take a second to add these methods to the object.

PHP
Java


class Car {
  private $speed;
  private $acceleration;
  private $wheels;
  private $numOfPassengers;

  function __construct($spd=0;$acc=0;$wheels=4;$numPassengers = 1){
    $this->speed = $vel;
    $this->acceleration = $acc;
    $this->wheels = $wheels;
    $this->numOfPassengers = $numPassengers;
  }

  function getSpeed(){
    return $this->speed;
  }

  function setSpeed($spd=0){
    $this->speed = $spd;
  }

  function getAcceleration(){
    return $this->acceleration;
  }

  function setAccelration($accel=0){
    $this->acceleration = $accel;
  }

  function getNumOfWheels(){
    return $this->wheels;
  }

  function setNumOfWheels($wheels=4){
    $this->wheels = $wheels;
  }

  function getNumOfPassengers(){
    return $this->numOfPassengers;
  }

  function setNumOfPassengers($passengers=1){
    $this->numOfPassengers = $passengers;
  }
}


And there you have it! We have created an object that is ready to be used, now all thats left is to actually instantiate one and play around. To instantiate a new object you do the following.

PHP

$car = new Car(20,0,4,5);
$car->getSpeed(); //returns 20;


JAVA

Car car = new Car(10,5,6,5);
car.getAcceleration(); //returns 5;



Now that you know the basics on objects, go out there and create a few of your own!