All posts by csharpadmin

Programmer Productivity

I saw this image on a blog the other day.

programmer productivity in a graph

I hear a lot from other programmers that they have problems with productivity.  I know I used to.  I had to work with the TV or Netflix on the background so I would have something to tune out.  You were only going to get about three consecutive hours out of me before I would run off and hide somewhere for a recharge.  I used to drive my manager crazy!

Joel Spolsky talked about this same problem on his blog once.

Sometimes I just can’t get anything done.

Sure, I come into the office, putter around, check my email every ten seconds, read the web, even do a few brainless tasks like paying the American Express bill. But getting back into the flow of writing code just doesn’t happen.

These bouts of unproductiveness usually last for a day or two. But there have been times in my career as a developer when I went for weeks at a time without being able to get anything done. As they say, I’m not in flow. I’m not in the zone. I’m not anywhere.

I think most of us were excited to find out we weren’t alone. If someone like Joel, that I highly respect and look up to has the same problem, then I don’t fee like there is something wrong with me.

So what do you do about it?

First, I made a list of all of the things I thought made me unproductive:

  • Open floor plan offices / not getting any privacy – if I was constantly overhearing other conversations, arguments, etc…I couldn’t keep focused
  • Pestering co-workers – Why would you come by my desk and ask me “did you get that email I sent 10 minutes ago?”.
  • Poor communication about requirements – self explanatory
  • Poor multitasking / prioritizing skills – if I had THINGS ON FIRE and other tasks to handle, I wasn’t sure about how to get it all done and in what order.
  • Twitter and Facebook notifications on my phone – self explanatory
  • Email notifications on my computer – also self explanatory
  • The Internet in general

So when I would find myself in a period of strong productivity, I would begin to ask myself.  What is going on right now that makes me more productive?  I created a similar list of “pro” environment things:

  • Music is good but I don’t want lyrics, instrumentals / dance music only
  • TV/Netflix is good but only if its some nonsense show that I don’t really care if I watch.  Daytime TV is good for this.
  • A private office.  For the most part I just started working from home.
  • No interruptions.  I had to isolate myself from the Internet.

If you find yourself in a similar situation, I would recommend that you start making lists like the above.  It has completely changed the way I work and my work output. Not all of us are cutout to work in the same office environment and learning these things about yourself will only make you happier as an employee.

Put yourself in control

A lot of us think that we are just lazy or that unproductive behavior is just part of who we are.  You are capable of so much more! Each of us has the power to control what makes us unproductive.  To make myself more productive I had to take control of the areas that I could:

  • Turn off notifications on your phone. Added bonus – more battery for later!
  • Work from home when I really, really need to get something done.  I also found places I can “hide” at work and not be bothered but I am easily accessible for pop-up meetings.
  • Black-out times on your calendar – These are times that you are scheduling yourself to work without interruption and they show as busy to anyone else that may want to schedule you for something.
  • Re-position your work environment – Move your desk so you can’t see people passing by or so you don’t see distractions.
  • Learn to reward yourself – I give myself three hour breaks for Internet, snacks, walks around, etc…

Now I seem to have the opposite problem where I am so productive with all of my tasks that people wonder how I get everything done.  Its really been a complete change.

I would be interested to know what you think makes you unproductive.  How do you combat it?

Math and Programming – Locked in an Eternal Struggle

It constantly surprises me the number of students that want to go into Computer Science that don’t like math.  Haven’t we been told for decades that the two fields are intertwined?

There seems to be two schools of thought on this struggle between math and programming.

Programmers do not need to be good at math

I often hear from programmers in the field that they don’t feel like they need to be good at math to do their job.  They have perfectly good careers and rarely have to use any math.  So why bother?

Today’s programmers are typically more focused on business logic problems and n-tier communication issues than using fancy equations to solve problems. Maybe the most math that you ever have to do is determine if you are going to overload your mobile network connection or that your Java library is going to be too big to load. When was the last time you had to implement a logical math function that wasn’t already given to you in a library?

Fundamentally, I think the flaw in this logic is that “being good at math” is not the same as “being good at math problems”. I’m sure that many a programmer goes about his day without ever giving the college Algebra class that he took almost a decade ago another thought. So why do we need it?

Programmers need math to learn logic

Think back to your last math class.  What did you learn?  It doesn’t really matter what you answer here since the answer, fundamentally is going to be the same. Math teaches us some basic things that make us better programmers.

  • Logical thinking – math teaches us about the application of logic to a problem.  Conjecture, proof and building theories.
  • Linguistical thinking – There has been tons of research that shows learning math is more like learning a language.  We use similar areas of the brain to learn and retain this information.
  • Future automation – Programmers typically have a drive to automate processes and tedious tasks.  Figuring out these automation techniques for tasks almost always involve computational mathematics in your code.

So not only do we need to take all of those math classes to learn the basics of mathematics, but we are also training ourselves on problem solving and how to approach the tasks that we will find in our programming careers.  We are also training our brain to learn the programming languages that we will encounter.  Let’s talk about that for a second…

Math is a language?

Absolutely! Math is more of a language than programming languages simply due to the way that our brains process problems.  When you are handling a math problem, you are dealing with unknowns and ambiguities.  This forces us to have to handle things based on context, just like you would when communicating with someone else.   One of the great things about programming is that you have a compiler that will help you determine how that ambiguity resolves.  You probably also have a better idea of the expected output or the end result in programming than you do when working math problems.

As someone currently working on their doctoral thesis on the subject – this is a subject that is near and dear to my heart. I would argue that in the hierarchy of rigor, mathematics falls between language and programming.  Its a bridge for understanding and applying concepts, even if you never actually feel that you use math in your everyday programming tasks.  This is why the two fields are locked together – no other training will help you learn the kind of abstract thinking that you will apply in programming like mathematics.

What does this mean for upcoming students in the field?

If you’re not good at math I don’t think you’re a hopeless case, but I do think that it has the potential to directly translate to your ability to apply critical thinking and solve problems in your programming courses.  However, there is no indicator that I’ve found in my research that states a person must be good at math to be good at language (hello future research project!). Since the two are similar, there is a good probability that a person that is good with languages could also apply the same concepts to programming and be successful.

Feel free to comment.  My research analysis will be posted on this blog when I am finished with my dissertation, so maybe we’ll have a more definitive answer then!

Don’t Get Type Cast in Your Programming Career

I was recently talking to a student about their career goals and they said “which language should I choose to learn: C# or Java?”.  My response was that they should learn both, since limiting your knowledge in this field can be a dangerous game. You want to be able to branch out and learn new things, even after you are out of school, so you can figure out where you fit.  I hear a lot about “specialization”.  People seem to think that since these specialized devs that only know about a few key systems like Sharepoint make tones of money, that is what they need to do as well.  I would caution you to not think this way as specialization only seems to work for a handful of people.  The more you learn about different systems, environments, and technologies the more it is going to open your eyes to different ways of thinking and working with different types of people.

Specialization also happens in the development world where you get stuck only working on projects that are supported on one platform.  You may think, “hey, I know a lot of different stuff about C#, Winforms, Asp.net, ASMX, Asp.net MVC, etc” but all of these are .NET platform technologies.  Not limiting yourself, should mean using different platforms altogether. i.e Linux, Windows, OSX, iOS, Android, different DBs, different languages. Also, different types of apps and requirements such as  web, desktop, mobile, embedded, enterprise level, high traffic, etc…

I recently saw a conference video from the Goto Conference where one of the presenters, Trisha Gee was giving career advice to programmers.  Here is the video:

Trisha talks about not limiting yourself in your learning and thus limiting your career by only focusing on one kind of technology, platform or area.  She used herself as an example since she switched from web development to server administration to server development. I’ve done the same thing.  I started as a programming student that went into programming, then IT administration (basically a catch-all title in itself), then server administration, then software administration, then programming instruction with freelance development and web development projects on the side.  By learning all of this, I learned I can switch gears and diversify my skills to create an impressive resume.  I also learned a lot of soft-skills.  Those are the people skills that you pick up along the way and having all of this experience helps when you need to put yourself in another person’s situation or understand the impacts of your decisions. It gives you a broader view of the process.

The key to all of this is don’t box yourself in. Don’t be afraid to learn new things and pick up new skills, even 10 years from now when you feel secure in your job. By switching gears now and then you are going to keep yourself from feeling like you are stuck in a rut.  It can be quite scary jumping into a new area or discipline in your field but ultimately it is rewarding as it gives you a very well-rounded resume that will open up a lot of doors.  It also shows employers that you are willing to invest in yourself and aren’t afraid of change.

Programming Challenge: Reverse Input

This week’s programming challenge is about Strings!  String is a great C# class with a lot of built-in functionality for manipulating characters and text.

Write a program that reads a string from standard console input and then prints it in reverse order on the screen.

To spice this up, allow the program to take in a number of strings and reverse the whole thing before printing it.  The console should know that the program is done when it encounters the word END.

Example input:

one

two

three

END

Example output:

three

two

one

See if you can write this program before I post the solution on Friday.

[codesyntax lang=”csharp” title=”Solution” blockstate=”collapsed”]

class Program
    {
        static void Main(string[] args)
        {
            //create a List that allows you to hold the input strings
            List<String> wordList = new List<string>();

            //get the word input from the user until they tell us there are no more words
            string input = "";

            while(true)
            {
                Console.WriteLine("Please enter the word you wish to store or END to quit");

                //get the string from the user
                input = Console.ReadLine();

                //test the input to make sure its not the word END
                if(input == "END")
                {
                    break;
                }
                else
                {
                    //store the input in the list
                    wordList.Add(input);
                }

            }

            //once the user has entered all of the words they want, we will reverse the list and print it
            wordList.Reverse();

            foreach(string word in wordList)
            {
                Console.WriteLine(word);
            }

        }
    }

[/codesyntax]

Programming Challenge – Roll the Dice

Write a program which simulates two dice with values from 1 to 6. The program takes a single argument which is the number of dice. The output should contain the values of the dice and the probability for this combination to occur. The probability is expressed as a decimal value between 0 and 1 with three decimal points.

How do you find the probability of a dice roll? Check out this explanation: http://www.math.hawaii.edu/~ramsey/Probability/TwoDice.html

If you think you have it figured out, post below and email me a link to your source so I can check it out!  I’ll post the solution at the end of the week.

 

 Post updated with solution below
[codesyntax lang=”csharp” lines_start=”1″ title=”Solution” blockstate=”collapsed]

class Program
    {
        static void Main(string[] args)
        {
            //welcome the user and start the program
            Console.WriteLine("Welcome to the dice probability program");
            Console.WriteLine("-------------------------");
            Console.WriteLine("Rolling dice");

            //create a new dice object and roll
            Dice newRun = new Dice();
            newRun.Roll();

            //display the result of the rolls
            Console.WriteLine("Die 1 rolled a {0}", newRun.Die1);
            Console.WriteLine("Die 2 rolled a {0}", newRun.Die2);

            //probability
            //Since each die has six sides and the game is played with two dice, there are 36 (6 x 6) combinations 
            //find the total of the two dice
            int total = newRun.Die1 + newRun.Die2;

            double probability = 0;

            //compare the total to the probability out of 36
            switch (total)
            {
                case 2: probability = 1.0 / 36.0; // 1 possible combination of dice 1/36
                        break;

                case 3: probability = 2.0 / 36.0; // 2 possible combinations of dice 2/36
                        break;

                case 4: probability = 3.0 / 36.0; // 3 possible combination of dice 3/36
                        break;

                case 5: probability = 4.0 / 36.0; //4 possible combination of dice 4/36
                        break;

                case 6: probability = 5.0 / 36.0; //5 possible combination of dice 5/36
                        break;

                case 7: probability = 6.0 / 36.0; //6 possible combination of dice 6/36
                        break;

                case 8: probability = 5.0 / 36.0; //5 possible combination of dice 5/36
                        break;

                case 9: probability = 4.0 / 36.0; //4 possible combination of dice 4/36
                        break;

                case 10: probability = 3.0 / 36.0; // 3 possible combination of dice 3/36
                        break;

                case 11: probability = 2.0 / 36.0; // 2 possible combinations of dice 2/36
                        break;

                case 12: probability = 2.0 / 36.0; // 1 possible combination of dice 1/36
                        break;

            }

            //output result
            Console.WriteLine("The probability of this roll is {0:F3}", probability);
            Console.ReadKey();
        }
    }

class Dice
    {
        private int die1;
        private int die2;

        public int Die1
        {
            get { return die1; }
            set { die1 = value; }
        }
        

        public int Die2
        {
            get { return die2; }
            set { die2 = value; }
        }

        public void Roll()
        {
            //get a random number object we can the use to determine the die face
            Random rand1 = new Random();
            Die1 = rand1.Next(1,6);
            Die2 = rand1.Next(1,6);
        }
    }

[/codesyntax]

Which Version of Visual Studio 2013 Do I Need?

One of the confusing things about getting started with a .NET language is figuring out which version of Visual Studio that you need.  Microsoft typically puts out many different versions of the Visual Studio software with each release and they can differ in the types of programs and projects they can create, features, functionality or limitations.  With the current version of Visual Studio 2013, there are five different versions of the main product and three versions of the Express edition so its no wonder that people just getting started or that are looking to upgrade to 2013 feel confused.  Here are the differences so you can determine which version you need.

Visual Studio Express

Visual Studio Express is the free version of the product that is usually released alongside the full version of the product.  Giving a free edition of Visual Studio allows people who want to learn a .NET language an easy way in. Since the Express version is free, it is often pared down and contains less functionality than the full version. Applications created in the Express version can be later maintained in other versions of Visual Studio if you decide to upgrade.

For 2013, there are three versions of Express: Web, Windows, and Windows Desktop.

 

Visual Studio Express Web

The Web version of Express allows you to create ASP.NET and Azure projects as well as other web-based projects like web services or web APIs.  This version is good if you won’t be creating other types of applications and the install will be slimmer since it only has the minimum necessary for these types of projects.

 

Visual Studio Express for Windows

The Windows version of Express allows you to create Windows Phone or Windows Store applications for Windows 8.1.  If you are thinking about getting into the app space, this is the version for you. It has support for HTML, JavaScript, C++, C# and Visual Basic and a built-in device simulator so you can test your apps on various phone and tablet devices.

 

Visual Studio Express for Windows Desktop

The Windows Desktop version is different from the previous version as it allows you to create full Windows desktop applications using Windows Presentation Foundation (XAML), regular Windows Forms or Console applications. If you are targeting the Windows desktop and wanting to make regular Win32 desktop applications, this is the version for you.

 

Visual Studio 2013

The full versions of Visual Studio are of course more powerful since they come with a full-sized price tag. There are five versions of the full product: Ultimate, Premium, Professional Online, Test Professional, and Professional.    All of the full versions of the program also allow you to connect to code collaboration platforms such as Team Foundation Servers (internal and at Visual Studio Online) and Github.

Here is the difference:

Visual Studio Professional Online

The Professional Online edition gives you all the functionality to create applications for Windows Desktop, Azure, Server and Windows Phone but does not include a lot of the functionality of the regular Professional edition. It is also limited when it comes to the number of users that can be connected to a project via Visual Studio Online.  For Professional Online, there is a maximum of 10 users and projects can only be hosted to Team Foundation Server Online and not to an in-house TFS installation.

 

Visual Studio Professional

The professional edition gives you the ability to create all of the project types that are available in all three versions of the Express edition. Windows desktop, Windows phone, Web, etc…It also gives you the ability to create cloud-based applications with Azure and Office integration add-ons.  There is no maximum for the number of users that can be connected to a project via Visual Studio Online.

 

Visual Studio Test Professional

Test Professional gives you a lot of the functionality of the Professional version along with tools for testing and integrating with workflows and collaboration.  The big difference with Test Professional is the lack of project availability. This edition is really for testing and QA personnel and does not include the ability to create projects.  However, if you are wanting a solution to create lab environments, capture requirements, or create and manage test cases, this is the version for you.

 

Visual Studio Premium

Premium is going to give you everything that is in Professional plus integrated testing tools to plan, develop, test and operate applications.   There are features included that allow you to workflow your code through a peer-review process and helps with multitasking and productivity by allowing you to suspend and resume tasks. Code coverage analysis tools and interface tests are also included.

 

Visual Studio Ultimate

Ultimate gives you everything in Professional and Premium as well as extensive testing tools. There is built-in functionality for capturing and reproducing bugs, diagnostic data, and performing web performance and loading testing. A new design interface allows you to create diagrams that validate code and implement architecture.

 

To help better understand all of the differences, here is a comparison chart:

Categories and capabilities Visual Studio 2013 Ultimate with MSDN Visual Studio 2013 Premium with MSDN Visual Studio 2013 Test Professional with MSDN Visual Studio 2013 Professional with MSDN Visual Studio Online Professional
Work in the same IDE to create solutions for the web, desktop, cloud, server, and phone checkmark checkmark checkmark checkmark
Take your apps to the cloud, Windows and Windows Phone Stores with included services as subscription benefits checkmark checkmark checkmark checkmark
Get access to Microsoft platforms and tools past and present, with new releases added all the time, including Visual Studio checkmark checkmark checkmark checkmark
Get access to Microsoft platforms and tools past and present, with new releases added all the time checkmark checkmark checkmark checkmark
Organize and define your test plans with test case management and exploratory testing checkmark checkmark checkmark
Provision and manage virtual lab environments for testing with consistent configurations checkmark checkmark checkmark
Improve code quality with a peer code review workflow within Visual Studio checkmark checkmark
Improve developer productivity when multitasking with task suspend and resume checkmark checkmark
Automate user interface tests to validate application UI checkmark checkmark
Find and manage duplicate code in your code base to improve your architecture checkmark checkmark
Determine how much code is being tested with code coverage analysis checkmark checkmark
Reliably capture and reproduce bugs found during manual and exploratory testing to eliminate “no repro” bugs checkmark
Collect and analyze runtime diagnostic data from production systems checkmark
Perform web performance and load testing checkmark
Design architectural layer diagrams to then validate that code implements the architecture checkmark
Maximum number of users on a Visual Studio Online account Unlimited Unlimited Unlimited Unlimited 10
Host team projects on-premises or in the cloud checkmark checkmark checkmark checkmark Cloud only

 

 

All of these versions can be downloaded from the Visual Studio Download site: http://www.visualstudio.com/downloads/download-visual-studio-vs

If you want to try these out you can get a 90 day free trial from www.visualstudio.com or if you are a student at a school that participates in the Dreamspark program, you can get a free version of the Professional edition at www.dreamspark.com.

Can You Learn to Program?

I don’t believe that everyone has the aptitude to program.

I know that might seem like a strangely bold statement, especially from someone that makes their living teaching people how to program but hear me out.

I think you can agree with me that not everyone is cut out to do everything.

I want to learn how to paint, draw and play the guitar.  I have spent countless hours learning – I have paid for lessons and I have put in a lot of effort.  But do I know how to do any of those things? No.

Why? Because I don’t have the aptitude.

What is aptitude? Aptitude can be defined as having a natural ability or a “fitness” for a task. Aptitude means that you have a competency for a certain kind of task or work. Some of us have the aptitude to be great basketball players because we were born tall.  Some of us can be great runners and participate in 5Ks every weekend because we have good stamina. Some people have the aptitude for mathematics because they were born with strong analytic skills.

So, no – everyone cannot learn how to program just like I cannot learn how to play the guitar.

So how do you know if you have the aptitude or not?

One way to find out is to take tests in areas such as Numerical Reasoning, Logic or Pattern Recognition.  These are all good skills that translate into being able to learn programming languages and concepts faster. You can find some of these tests here:

http://www.kent.ac.uk/careers/tests/computer-test.htm

http://www.computeraptitude.com/

These tests can help identify whether or not you have some of the necessary skills but they should be considered the end-all voice on whether or not someone is capable of learning how to program.

Some people believe that if you are good at math that you can be a good programmer.  I am almost in this camp but I have to disagree with some of this idea. Most of the programming that you will be doing for a living revolves around business problems. Math isn’t going to help with these but it will help with foundation logic. Since most of the first programming languages were developed by mathematicians, it makes sense that a lot of the same concepts would be applied or borrowed into the concepts used in computer science.  However, being good at math is not a free pass into programming.

Are these tests and scores really going to tell you anything?

In my mind, the only way to find out if you have the aptitude for something is to try it.  Only by trying to learn something, putting in the effort and practicing it are you going to find out if this is something that you like, enjoy, and/or are good at.  Over my years of teaching I have seen all sides of this coin.  Students that want to learn programming so bad but just can’t get it.  I’ve had students that joined the class because someone told them they should and were good at it but hated actually doing it.  I’ve had students think that learning to program was going to be like playing video games and they shy away from it because “its hard” and I’ve had students come in thinking programming was going to be terribly hard and finding it was simple.

What can we learn from this?

Expectations are the common thread between all of these students. Everyone comes into programming expecting something but their expectations do not align with reality they aren’t going to get anywhere. I recommend that you put away what you think programming is going to be like, whether it is easy or hard, whether you are good at it or not and put your butt in the seat.  Do the work. Only then will you know if you can do this.

Sorting Elements in a Object-based Array

Since most C# applications are taking advantage of object-oriented practices, we often end up with arrays of objects instead of simple-types like int.

Let’s imagine, we have a class like this:

[codesyntax lang=”csharp”]

public class Employee
{
	public string FirstName;
	public string LastName;
	public decimal Salary;
	public int EmpType;

}

[/codesyntax]

 

Then we have an application that creates arrays of Employee objects so we can store each instance of the object.  For example:

[codesyntax lang=”csharp”]

Employee[] myList = new Employee[2];

[/codesyntax]

Suppose I want to sort the array by a particular field of Employee?  How could we sort this array of Employee objects by the LastName field?

There are two ways we can accomplish this – delegates and LINQ

Delegates

A delegate is a special type that references a method.  You can define a parameter list and a return type just like you can in regular methods.  Through this delegate process, we can create a method that sorts the object array by comparison.

[codesyntax lang=”csharp”]

delegate(Employee emp1, Employee emp2)
{
	return emp1.LastName.CompareTo(emp2.LastName);
});

[/codesyntax]

The CompareTo method is built-in to the .NET framework and compares two objects of the same type. It will return less than 0 when X < Y, zero when X = Y and greater than 0 when X > Y.

LINQ

LINQ stands for Language-Integrated Query. It is a feature of the .NET framework and allows you to create queries based on simple patterns and built-in methods.   LINQ has a method OrderBy that is designed to compare and sort two elements.

[codesyntax lang=”csharp”]

var sortedArray = myList.OrderBy(emp => emp.LastName).ToList();

[/codesyntax]

Either of these methods will work when you have an array of objects that need to be sorted by one or more of their elements.  Make sure to let me know if you have questions!

Number Validation Program

Its OK, especially when you are just getting started, to practice learning C# on some smaller code projects.  Don’t underestimate how much you can learn about programming in the console before you move on to more complex tasks.

For this program, we are going to validate a number that the user gives us in a console application. Here are the specifications:

Write a program in console that accepts an Integer value from the user

When you have accepted the value, determine if it is less than or equal to 10.  If so, print the statement: “This value is small”.

If its larger than 10, print the statement: “This value is large”.

If the user enters a number greater than 100, print the statement: “This value is too big!” but don’t print either of the previous statements

Hint: Remember to use Convert.ToInt32 when accepting the integer value from the Console.ReadLine() statement so you can store the incoming value into an integer variable.

Try it out on your own and see if you can get it working. If you get stuck, check the answer below.

[codesyntax lang=”csharp” lines_start=”1″ title=”Solution” blockstate=”collapsed”]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NumberValidation
{
    class NumberValidationProgram
    {
        static void Main(string[] args)
        {
            //print a welcome statement
            Console.WriteLine("Welcome to the number validation program");
            Console.WriteLine("Please enter a number");

            //accept the number from the console
            int number = Convert.ToInt32(Console.ReadLine());

            //check the number against the validation rules
            if(number <= 10)
            {
                Console.WriteLine("This value is small");
            }
            else if(number > 10 && number <= 100)
            {
                Console.WriteLine("This value is large");
            }
            else if(number > 100)
            {
                Console.WriteLine("This value is too big!");
            }
        }
    }
}

[/codesyntax]

Understanding Object Oriented Programming

What is Object Oriented Programming?

Quite often I get a question or see a question posted online along the lines of: “What is this thing called OOP?”, “What is so special about it?”, “Why should I use it?” or “How do I use it?”. The person asking this type of question usually has experience of non-OO programming and wants to know the benefits of making the switch. Unfortunately most of the replies I have seen have been long on words but short on substance or example.  The main reason for this is that some of the explanations about OO are rather vague and can be interpreted in several ways, and if something is open to interpretation it is also open to a great deal of misinterpretation.  Hopefully this article will help clear up the confusion and give you a better idea of what Object Oriented Programming is.

What is Object Oriented Programming?

Object Oriented Programming is programming which is oriented around objects, thus taking advantage of Encapsulation, Polymorphism, and Inheritance to increase code reuse and decrease code maintenance.  Here are some examples between object oriented programming and non-object oriented programming.  Don’t let the big words scare you – these are easy concepts to learn.

What is an Object Oriented language?

A computer language is an Object Oriented language if it provides support for the following:

  • Class: A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
  • Object: An instance of a class. A class must be instantiated into an object before it can be used in the software. More than one instance of the same class can be in existence at any one time.
  • Encapsulation: The act of placing data and the operations that perform on that data in the same class. The class then becomes the ‘capsule’ or container for the data and operations.
  • Inheritance: The reuse of base classes (superclasses) to form derived classes (subclasses). Methods and properties defined in the superclass are automatically shared by any subclass.
  • Polymorphism: Same interface, different implementation. The ability to substitute one class for another. This means that different classes may contain the same method names, but the result which is returned by each method will be different as the code behind each method (the implementation) is different in each class.

A class defines (encapsulates) both the properties (data) of an entity and the methods (functions) which may act upon those properties. Neither properties nor methods which can be applied to that entity should exist outside of that class definition.

 

Different Definitions

A method is defined as a self-contained block of code. Each method name must be unique within the application.  This is the name we use when we want to call upon this block of code to perform its job.

Public string DisplayName(string name)

{

                …..

                return name;

}

A little bit of a breakdown:

  • Public is an access modifier, it tells us what parts of the program are going to have access to this method and which one do not.
  • String tells us about the data type of the information the method will return when it is done performing its job. In this case, we can see that the data type of the variable “name” is a string and since that is what we are returning, we have to indicate that here.
  • DisplayName is the name of the method so we know what it is called when we want to use it.
  • The parameter list follows in the parenthesis. Methods do not have to have parameters but they sometimes need outside information brought in so they can perform their job. We can provide any number of parameters needed in a comma separated list.

A class method is defined within the boundaries of a class definition. Each class name “MyClass” must be unique within the application. Each class may contain any number of functions (also known as “methods”), and the function name “DisplayName” must be unique within the class but need not be unique within the application.

Public class MyClass

{

                Public string DisplayName(string name)

                {

                                ….

                                Return name;

                }

}

 

Accessing them is Different

It is important to note that neither a method nor a class can be accessed until an instance of the class object has been created. Calling a method is very straightforward:

String result = DisplayName(“Sara”);

Calling a class method is not so straightforward. First it is necessary to create an instance of the class (an object), then to access the function (method) name through the object. The object name must be unique within the application.

//create an instance of the object

MyClass myObj = new MyClass();

//now I can call a method from inside of MyClass

String result = myObj.DisplayName(“Sara”);

 

State Maintenance can be Tricky

A method by default does not have state: each time that it is called it is treated as a fresh invocation and not a continuation of any previous invocation. An object does have state; each time an object’s method is called it acts upon the object’s state as it was after the previous method call. It is possible for both a regular method and a class method to use local variables, and they both operate in the same way. This means that the local variables do not exist outside the scope of the function or class method, and any values placed in them do not persist between each instance. It is possible for a method to remember values between each time it is called by declaring a variable as static, as in the following example:

Public int Count()

{

                Static int count = 0;

                Count++;

                Return count;

}

 

Each time this method is called it will return a value that is one greater than the previous call. Without the keyword static it would always return the value ’1′. Class variables which need to persist outside of a method are declared at class level, as follows:

Public class Calculator

{

                //define class variables

                Int someValue;

                //setup properties for class variables

                Public int SomeValue

                {

                                Get { return someValue;}

                                Set {somevalue = value;}

                }

                //setup a method that Adds the value

                Public int Add (int number)

{

                                SomeValue += value;

}

//setup a method that Subtracts the value

Public int Subtract (int number)

{

                                SomeValue -= value;

}

}

 

Properties are used to handle the way the data moves in the class when we want to access class-member variables.  Using the Get we can access the value of a variable and through the Set we can change the value of the variable. This helps us control access to the information in the variable and to be able to perform validation and other checks before the value is changed.

 

Conclusion

Many people use the terms “object oriented” or “OO Programming” sometimes out of context.  These terms are slippery and we must be careful that we intend what they truly mean.  There are only three features which really differentiate an Object Oriented language from a non-OO language, and these are Encapsulation, Inheritance and Polymorphism.  If it doesn’t have these three key ideas then it isn’t object-oriented.  OO doesn’t necessarily mean that you will get code that is high reusability and low maintainability that is up to the quality of the code and the experience of the developer, however if you are using object oriented techniques; you are moving in the right direction.