Saturday, June 18, 2016

Object Oriented Programming (OOP) (Part 0)

I will continue using C# .NET when explaining what Object Oriented Programming (OOP) is. Let us continue from where we left off in my previous post.

I want to explain OOP by diving straight into writing code and let the explanation come fluently. Let us begin by creating a new project within our solution.

Step 0 - Right click your solution -> Add -> New Project...






















Step 1 - Select Installed -> Visual C# -> Class Library
Step 2 - Name your project CardGameLibrary and click OK



Now we have two projects in our solution. We could have all classes within the same project and even in the same file if we really wanted to, but there are several very good reasons for the different layers of abstraction. Separation of Concern (SoC) is one of them. Which simply put is: different kind of code should be divided into their own kind of solution, project, namespace, class, method etc. But this does not mean you should create a new project all the time. You will learn when to do what with experience. It is all about being readable and maintainable. Moving on...

In the new CardGameLibrary project you should see a autogenerated class called Class1 (.cs is just the C# file extension). Rule #0, only one class per file. Period. Delete this file (select and hit delete on your keyboard). Add a new folder to the project called 'Model' (Right click project -> Add -> New folder). Add a new class called Card to that folder (Right click folder -> Add -> Class...).

You should see something like:




So, now lets start talking about Object Oriented Programming (OOP). There are many things to this, but as mentioned in my previous post:

"To explain the class declaration... In the real world, you'll often find many individual objects all of the same kind. A bicycle company creates thousands of bikes each identical to each other, but still unique. Each bicycle was built from the same blueprint and therefore contains the same components. In object-oriented terms, we say that a bicycle is an instance object (or instance for short) of the class Bicycle. A class is the blueprint from which individual objects are created."

While the blueprint of each bicycle might be the same, that does not mean that the data of each object stays the same. You could for instance create two instances of the Bicycle class, one blue and one yellow, but they fundamentally work the same way.

You can model a program you can do it in an infinite number of ways, but we want something that is easy to understand and when creating a program that is going to simulate the real world, like a card game, why not start with a class called Card? Each and every class should have a single responsibility, it might be difficult to define 'single', but that's something you will become better at with experience. But "handle everything" is not a good single responsibility. So the purpose of this class is simply to represent a card used in a deck of card. A class can have different properties and methods which either take actions on them self or other objects. Lets just dive right into how you would approach this in C# .NET.

Lets start with two properties, color of the card and number.


At the beginning of each property you see "public", which is the visibility level, meaning it can be seen from outside the class. Another class can read and write (get and set) to that property. However the setter (set;) is private which means you can only read this property from the outside, but within the class you can set the property. Which brings us to the constructor, which is a method that is used to create an instance of a class. You as a developer has to make sure that the constructor creates an object that makes sense, it has to be an object that it has the required input arguments (input variables). Lets start with an example that is very basic and improve upon it.

In this first constructor we have two input arguments 'string color' and 'int number', which we assign to their respective property. While this works if the constructor is used in the right way, it also opens up the possibility for errors. But it is bad practice to leave anything for chance. When a program is small and you are the only one working on a project you will probably be able handle it, but with just a few more lines of code you will ensure that a class always works as intended. When somebody else consume your class or reads your code it should always be clear what you were intending to accomplish. The first problem with this code is the input arguments, they are not sufficiently well defined. They can be set of values far greater than those who actually make sense. In a regular card game there are only four colors - 'hearts', 'spades', 'diamonds' and 'clubs', but the argument 'color' is of type string which can be just about any kind of text. So if somebody uses the constructor in the wrong way, like using strings that does not make any sense in a game of cards; you could end up with weird bugs where players are dealt cards of the color 'orange' or the "color" 'fried chicken', since any string (text) is possible. You can even use a special value called null, which means nothing. It is a special object without any content and without methods. You should try and avoid using it, because it causes problems. If you create an object without instantiating it, then it has the value null. If you try to call a method on a null object you get something called a 'NullPointerException', which is a special Exception class that can cause your program to stop working (unless handled; more about that in another). The other argument 'number' is of type int, which is a primitive datatype that cannot be null and is an 32-bit integer within the range -2,147,483,648 to 2,147,483,647, but the only integers that really makes any sense is 1 to 14. Not only can an int be way to many wrong integers, but it does not really make sense to use integers for the number. Especially not for aces that can both mean 1 and 14.

So how do we solve this? There are many ways, but I am going to solve this using something called 'enum'. I cannot really explain it much better than Microsoft, so here is a link where you can read about it. It is common practise to put enums within the same class or at least in the same file, but we will instead put each enum in a separate file, because of separation of concern.

Lets start by creating a enum for the colors called "CardColorEnum"

Step 0 - Right click the Model folder -> Add -> New Item...









Step 1 - Visual C# Items -> Code -> Code File -> Name it CardColor.cs -> Click Add




Step 2 - Write the following code in that file


Now we have the enum we need with all the colors of a regular card game. Lets use it as an input parameter for our card class.
Simply change the color argument in the card constructor from string to CardColor and the same for the Color property.










We are about to do the same with number. But first, you will learn that while coding you will do mistakes and things that does not make sense and one of the most important things when writing code is that it is easy to read and understand. Because usually you will be sitting reading code, either your own or others. If I am repeating this a lot it is because it is really that important. Naming something correctly tells you or the next one reading it really what its purpose is. Therefore we will change the name from number to value, because Knight, Queen, King and Ace are not really numbers, they are just representations of some kind of value, which differ in different games (well same for 2, 3... 10 really).

So here is our new CardValue enum.


















Lets use our new enum and change our Card class.













We have now learned how to create a simple basic class that makes sense and is difficult to misuse.

What's next?

In the next post I will be continue where I left off and start building the foundation for a card game.

/*
  Live and let live.
*/

Monday, March 28, 2016

What is Software?

Purpose of this blog

The purpose of this blog is to teach you as much as possible about software development without knowing anything from the beginning and end up being on your way to know as much as me. I find the way I were taught in school was not very efficient and there were a lot of things that you should know before going out into the work place, some of which are not taught in school. I hope to address these issues with this blog. But, this will absolutely not be a substitute for any university courses or programmes. My main focus will be on basic real world knowledge of software development.

What is Software?

In its most basic form, software is a collection of instructions that tells the CPU (Central Processing Unit) what to do. Each instruction is represented by certain length of bits. A bit is a value that can only be 0 or 1. The number of bits required for each instruction depends on the kind of CPU you are using; a typical desktop CPU can run 32 bit and 64 bit instructions. More simply put, every instruction is a numerical value that each correspond to a certain logical operation which the CPU can run; like adding two numbers together or compare one number to another. The main purpose of software is to automate logical operations that we otherwise would have to do manually. It's used everywhere - door openers, phones, cars, air planes... the list is long.

What does it mean to write code?

Back in the day people used to write code in a language called assembler, which is a direct translation of machine code (as in instructions) into more human readable names. When you have enough of instructions, you have a program. Even though a few people still use assembler, it's not common.

What languages do people use today?

There is a lot of different languages, such as:


  • Java
  • C#
  • JavaScript
  • Python
  • C++
  • SQL
  • etc...

    All of these have different uses, benefits and shortcomings. The truth is that if you want to become a valuable developer you need to learn several languages and be able to learn new ones as demand requires it. Luckily most languages are very similar in basic syntax. Though, you do not need to worry about that just now. The reason we have any other language than assembler is to make it more efficient to write programs. Simplifying things is very important in every profession. It's what allows us to make profits and that's what makes it possible to enjoy all the good things from life. Without profits we'd still be living in caves!

    What tools do I need to start coding?

    Typically you write your code in an IDE (Integrated Development Environment), which basically is a program that helps you with a lot of things involved in developing software. The most important part is the compiler which basically translates your high level language (such as C#, Java...) into machine code that you then can execute (run). It also helps you to arrange the different files that makes up your project. The IDE will also help you in real time with syntax errors, sometimes you forget minor details required for your code to compile. These error messages can be cryptic to understand for a beginner, but you will learn to understand them with experience.

    What is the next blog post going to be about?



    /*
        Strength comes from within.
    */

    Your First Program

    In this tutorial you will be using the programming language C# (pronounced C sharp), the .NET (pronounced dot net) framework and an IDE called Visual Studio Community 2015 which is free. Simply google for it, download and install it. I have chosen the dark color theme because it is easier for the eyes and I have changed a few other colors.

    Once installed and launched we will begin by creating a new solution, which is merely a container for one or more projects.

    Step 0 - Select File -> New -> Project...



    Step 1 - Select Templates -> Visual C# -> Windows -> 'Console Application' and name the solution 'HelloWorldApplication'.




    As you can see below on the left side you should now have a solution called 'HelloWorldApplication' which contains a project also called 'HelloWorldApplication'. A solution and project is simply two different levels of abstractions. On the right side you can see a auto generated snippet of code which I will explain step by step.



    At the top (row 1 to 5) you can see a few statements starting with 'using', these indicate that this file has access to certain functionality. A statement is the same as an action that the compilation will translate into machine code.

    Then at row 7 you can see 'namespace HelloWorldApplication' which is a logical container for the 'class Program' declared at row 9 to 14. In C# curly brackets (or braces) '{}' are to indicate the limitation of a certain container. The character '{' is referred to as the opening bracket and '}' the closing bracket; there is must always be the same number of opening and closing brackets or the program will not compile. The reason you have namespaces is so that if someone creates a class of the same name there will not be a conflict between them.

    To explain the class declaration... In the real world, you'll often find many individual objects all of the same kind. A bicycle company creates thousands of bikes each identical to each other, but still unique. Each bicycle was built from the same blueprint and therefore contains the same components. In object-oriented terms, we say that a bicycle is an instance object (or instance for short) of the class Bicycle. A class is the blueprint from which individual objects are created.

    In our case, it is a very simple class called Program which contains a simple method called 'Main'. This method is also static which means that it can be called for without creating an object of the class it belongs to. The 'void' term is an indication of the return type, which means that when the method has finished executing its statements it is will not return any value. The '(string[] args)' part indicates the input parameter to this method; the parameter is called 'args' and 'string[]' is the type this parameter has. Each program must have a method of this kind 'static void Main(string[] args)', this is where the program starts to execute. A 'string' is just plain text and the '[]' square brackets indicate that it is an array of strings, which makes string[] a 'list' of 'texts'. This args variable could for example be used to initiate an application with different settings.

    By tradition we will add one simple line of code like below, which makes this a "Hello World" application.



    The semicolon at the end is required because it marks the end of that statement. You could put several statements at the same row if you really wanted to as long as you end each one with a semicolon, but it would make it more difficult to read. As we will see in future blog posts there are multiple ways of writing the same code.

    If this is your first time programming I would imagine you might feel a bit overwhelmed with all the details, do not worry about not understanding everything completely, it will become clear as you continue. Also, there is no shame in trying out the same things multiple times.

    When you run the program using this button , you will probably see a fast flash of a console application running and then disappearing. This is because the program starts running, prints "Hello World!" in the console (cmd.exe) and finishes, which means the console application closes. It is all it does and nothing more, there is nothing that would keep the program running.

    To actually see the text in the console, one way is to use a 'break point' which is important feature of the 'debugger'. You can see a break point to the left below. You add one simply by left clicking in that area.



    Now, simply run the program again. The program should pause running at the break point.



    You should have a console application running on your task bar like so:


    You can now 'Continue' or 'Stop' the application. 
    'Continue' makes the program continue running as if you never paused it with the break point while 'Stop' makes it quit execution immediately.

    Congratulations! You have just created your first program!

    What is the next blog post going to be about?

    Object Oriented Programming (OOP)

    /*
      Good ideas don't require force.
    */