Practical Reference Type (POCO) Example

So the other day, I was asked by a colleague that is learning to program what a practical use case would be for using custom objects (also known as Plain Old CLR Object). They also asked why you would want to use a reference object as a parameter in a method that assigns a value to the objects property instead of just assigning yourself. These are good questions for someone that is just learning as the difference between value types and reference types and why you even want or need reference types can be daunting and down right confusing. Especially when you don’t have a sizable project to look at or work with. I was disappointed to see that although this a very basic thing to learn about object orientation, the results out there were very confusing and useless for a new programmer. So today, we are going back to the basics and learn why we use POCO’s.

What is a POCO

A POCO or Plain Old CLR Object is a common term throughout object oriented programming that allows you to create your own “storage” of data in a way that means something to you as the programmer. A POCO is always a noun and describes some sort of “thing” usually representing some physical object. An example would be a toaster, car, food, computer etc. Today, we will use a Car object as our POCO.

A POCO also has properties (and sometimes methods called instance methods, but we won’t go over these today). Properties are verbs that describe the object. In our example of a car, you might have the manufacture, model and miles per gallon to describe and differentiate one car from another. In the end, we would like to go on a vacation, so we would like to know which car is the cheapest to go the miles based on miles per gallon. All cars will go the same distance and have the same gas prices.

public class CarModel
{
    public string Manufacture { get; set; }

    public string Model { get; set; }

    public double TotalCost { get; set; }

    public int MilesTraveled { get; set; }

    public double MilesPerGallon { get; set; }

    public double PricePerGallon { get; set; }

}
 

I assume that you have a basic understanding of the syntax for C#, so I won’t go into that kind of detail. Basically, we have a Car object and that object has 6 properties that will describe each object.

 

Why use these objects?

The reason for these objects is really the foundation of object orientation which is segregating things into smaller logical components and ‘separation of concerns’. When I say that last part, for now it basically means to separate business logic , UI design and business rules into their own “black box” so to speak. For example, as you will see, when the code is done, you can come back to this program in 6 months and know what it does in roughly 5 minutes.

On to the Code

So lets start coding. The first thing we are going to do is instantiate or create 3 CarModel objects. These cars will all have different models, Manufacturer, Miles per gallon and miles traveled to. To make this more practical, we will create them in an order that would make the total costs not be in numerical order. Then we are going to use the Bubble Sort algorithm to reorder the total costs so we know which car to take on our trip. If want to understand the algorithm better, the link above is a pretty good article. Now, Bubble sort is by no means the quickest, but it is one of the simplest that most people learn in any programming course in college, so I figure most can relate and see what it happening without much detail.

static void Main(string[] args)
        {

            CarModel[] carArray = new CarModel[3];

            CarModel newCar = new CarModel();
            newCar.Manufacture = "Hyundia";
            newCar.Model = "Elantra";
            newCar.MilesPerGallon = 34;
            newCar.MilesTraveled = 200;
            newCar.PricePerGallon = 3.50;
            CalculatePrice(newCar);
            carArray[2] = newCar;

            CarModel newCar2 = new CarModel();
            newCar2.Manufacture = "Toyota";
            newCar2.Model = "Camery";
            newCar2.MilesPerGallon = 32;
            newCar2.MilesTraveled = 200;
            newCar2.PricePerGallon = 3.50;
            CalculatePrice(newCar2);
            carArray[0] = newCar2;

            CarModel newCar3 = new CarModel();
            newCar3.Manufacture = "Ford";
            newCar3.Model = "Tundra";
            newCar3.MilesPerGallon = 15;
            newCar3.MilesTraveled = 200;
            newCar3.PricePerGallon = 3.50;
            CalculatePrice(newCar3);
            carArray[1] = newCar3;

The code above first assigns some memory to an array that will be fixed (Immutable) at 3 cars. In most program scenarios, you will be getting the car information from the user in some fashion, but I am creating each car statically for simplicity. So each car is created, the values are assigned and added to the array for later processing ( There is this CalculatePrice method thingy that we will discuss later). As you can already see, there is certain kind of English when reading this code. You can already see without much syntactical knowledge that a bunch of cars are created and then added to an array ( or list) of cars in memory.

Next is the Bubble Sort algorithim. With this algorithm, there is an inner and outer for loop. The first loop is used to make sure we go through all the items in the array without any out of bounds errors. The second array is the meat and potatoes of this algorithm. This method takes the Total Cost of the current car and the next car and if the current car is larger than the next car (or in the algorithm speak, to the right of the current item), it then swaps the first item and the next item so that the lower number gets pushed down the array index. Enough talk, here is the code.

for (int i = 1; i < carArray.Length; i++)
{
    for (int counter = 0; counter < carArray.Length - 1; counter++)
    {
        if (carArray[counter].TotalCost > carArray[counter + 1].TotalCost)
        {
            CarModel tempCar = carArray[counter];
            carArray[counter] = carArray[counter + 1];
            carArray[counter + 1] = tempCar;
        }
    }
}

The final part of this program needs to write out to the console what the cheapest car and price will be since this is what our program is supposed to figure out.

Console.WriteLine("Cheapest Car: " + carArray.First().Manufacture + " " + carArray.First().Model + "\n" + carArray.First().TotalCost.ToString("c") + " Total Cost");
Console.ReadLine();

So what about this CalculatePrice method

This method is what this blog post is really all about. Why use objects? Well, part of it was shown above. The ability to store data in a structured, human readable way that can be read in 6 months and still understood. So The CalculatePrice method does exactly what it says it does. Calculates the price Smile. In this case “price” is the total cost of the trip. So yes, as I am writing this we might have wanted to call this method CalculateTripCost. Here is the code.

public static void CalculatePrice(CarModel car)
{

    var gallonsNeeded = car.MilesTraveled / car.MilesPerGallon;
    car.TotalCost = gallonsNeeded * car.PricePerGallon;
}

You will notice that the method passes in a CarModel and returns nothing (void). This works because of reference types (POCO is an example). Reference types are exactly as they sound. References to a place in memory (like a pointer) that can still be updated. A value type/primitive (int,double,string etc..) sends a copy of the value and only changes for the scope of the method. In this case, if you wanted the changed value, you need to return it to the caller of the method. I will go over value types in a separate blog.

So since the CarModel is being passed as a reference type, when the TotalCost is updated, the callers version of the CarModel is what is actually updated and requires no CarModel be returned. At the end of this article, I will give you the full code and encourage you to test and place break points in places you do not understand to see how the compiler handles the code.

POCOs are great when you have a lot of parameters to pass into a method as well. If you have more than 3-5 paramaters going into a method, it might be a good idea to step back and think: Hey, do these parameters describe a common tangible object?

Lets take CalculatePrice method for example. If you didn’t have the CaModel object to pass, this is similar to what the method could look like if you needed to pass all the car properties.

public static void CalculatePrice(string manufacture, string model, double pricePerGallon,double totalCosts.... )
{

// Some changing of several properties
}

As you can see, this gets unwieldy quickly, very hard to read / see what is going on. This is where POCO’s start to really shine because you declare them once and the rest is history. The DRY method is your friend in object orientation. It stands for Don’t Repeat Yourself. So don’t do it… I’ll be watching you Smile.

As promised here is the full code from this blog:

namespace Tut_Reference_Object_Example
{
    class Program
    {
        static void Main(string[] args)
        {

            CarModel[] carArray = new CarModel[3];

            CarModel newCar = new CarModel();
            newCar.Manufacture = "Hyundia";
            newCar.Model = "Elantra";
            newCar.MilesPerGallon = 34;
            newCar.MilesTraveled = 200;
            newCar.PricePerGallon = 3.50;
            CalculatePrice(newCar);
            carArray[2] = newCar;

            CarModel newCar2 = new CarModel();
            newCar2.Manufacture = "Toyota";
            newCar2.Model = "Camery";
            newCar2.MilesPerGallon = 32;
            newCar2.MilesTraveled = 200;
            newCar2.PricePerGallon = 3.50;
            CalculatePrice(newCar2);
            carArray[0] = newCar2;

            CarModel newCar3 = new CarModel();
            newCar3.Manufacture = "Ford";
            newCar3.Model = "Tundra";
            newCar3.MilesPerGallon = 15;
            newCar3.MilesTraveled = 200;
            newCar3.PricePerGallon = 3.50;
            CalculatePrice(newCar3);
            carArray[1] = newCar3;

            for (int i = 1; i < carArray.Length; i++)
            {
                for (int counter = 0; counter < carArray.Length - 1; counter++)
                {
                    if (carArray[counter].TotalCost > carArray[counter + 1].TotalCost)
                    {
                        CarModel tempCar = carArray[counter];
                        carArray[counter] = carArray[counter + 1];
                        carArray[counter + 1] = tempCar;
                    }
                }
            }
            Console.WriteLine("Cheapest Car: " + carArray.First().Manufacture + " " + carArray.First().Model + "\n" + carArray.First().TotalCost.ToString("c") + " Total Cost");
            Console.ReadLine();
        }


        public static void CalculatePrice(CarModel car)
        {

            var gallonsNeeded = car.MilesTraveled / car.MilesPerGallon;
            car.TotalCost = gallonsNeeded * car.PricePerGallon;
        }
    }

public class CarModel
    {
        public string Manufacture { get; set; }

        public string Model { get; set; }

        public double TotalCost { get; set; }

        public int MilesTraveled { get; set; }

        public double MilesPerGallon { get; set; }

        public double PricePerGallon { get; set; }

    }
}  

This was done in a Console application, so that would probably be a good template to place this into. Just change the namespace and off you Go.

 

Happy Coding Smile

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in .NET, .NET 4.5, Best Practices, C#, Classes, Coding standards, Programming Paradims and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s