Category Archives: Introduction

Don’t Repeat Yourself

This week lets take a look at a(nother) useful principle, the Don’t Repeat Yourself (or DRY) principle. The goal here is to get an idea of how the principle works and then aim to incorporate it into your day to day development activities. Remember to try to combine it with the other principles we’ve looked at, for example the Single-Responsibility Principle from the SOLID principles.

So where’d this one come from?

Introduced by Andrew Hunt and David Thomas in their 2000 book “The Pragmatic Programmer” they define DRY as

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

What we are basically aiming for is don’t say (following Uncles Bobs tell a story advise) or do the same thing twice. If you have some logic that performs a useful job, or even if its not that useful, don’t repeat that code. Combined with Single-Responsibility you could wrap that it up behind a class or method and have a single definition (“authoritative representation”).

I read a quote once that is quite good, “The only bug free code is no code” another is “Code that doesn’t exist is code you don’t have to debug” (can’t remember the original authors). Essentially what both of these statements are telling us is, write as little code as you can to get the job done. By following DRY we can shrink our code base by reducing repetition and therefore reduce the chances of bugs or introducing bugs through changing the same piece of code found in multiples places.

Another benefit we get from DRY is if you have a block of code duplicated throughout your code base and you need to make a change to that block not only do you have to go and update all blocks but there’s a chance a bug can be introduced through this change (at the end of the day we’re only human). Now if that code block was held in one place, meaning only one update was required we save time and reduce the chance of introducing bugs.

One example is say we needed to modify a piece of data using the following steps:

const int TEMP = 10;
double x = 30;
double y = 5;

x = x * TEMP;
x + y;
x / 10;

Now instead of duplicating this “important” bit of code we can wrap it in a suitably Named class or method and simply call that.

That’s it really, if you find yourself writing the same piece of code more than once consider if it may be worth extracting all instances of that block.

Magic Mirror

Apologies this post has taken longer than I expected to get out. Its a bit different from the others as its about a specific project.

I decided to give making the Magic Mirror a go. It was my first (and I expect not my last) DIY project and I must say I really enjoyed doing it. I’ve been wanting to do it for a while but as with many people the first road block instantly made me move onto the next thing to do. Not very productive right?

So this time round when the urge to make it took me I put myself on the spot, I told my fiance I’d make it for her as a gift for her birthday, though I didn’t tell her exactly what it was only that I was making something myself.

So what is the Magic Mirror? If you haven’t checked out the above link I’d recommend you do they can probably explain it better than me. Essentially it’s a mirror that gives you information, be it the time, weather, news headlines, and a lot more. The image below shows my end product :

Magic Mirror

What I needed to make the Magic Mirror was:

  • A Monitor
  • A Raspberry Pi
  • A Frame
  • A Two-way / See through mirror
  • Wood
  • Tools

The Monitor

The monitor I used was Iiyama ProLite E2207WS, mainly because I’ve had it for years and wasn’t doing anything with it.

Monitor

First thing I needed to do was get the frame off it, which wasn’t as bad as I thought it would be. Was quite worried I’d end up damaging the buttons but it worked out well. You do definitely need to be careful not to damage them as you may not be able to use the monitor if you do.

Monitor – No Frame
Monitor – Buttons

If you don’t have a monitor lying around make sure you get one where the HDMI connector would not be facing the wall. They should be facing towards the floor if the monitor was standing up right. Another useful option for the monitor would be to ensure it has a USB port capable of powering a Raspberry Pi, that way you only need to worry about one cable. Unfortunately for me my monitor did not have a USB port so I have two cables on display.

Raspberry Pi

I think it’s recommended you use the Raspberry Pi 3 to make the Magic Mirror but again I had a Raspberry PI 2 Model B+ lying about the house that I wanted to do something with. So instead of buying a new Raspberry Pi I just used that instead (and now have an excuse to get the Pi 3). There wasn’t really much to this bit to be fair, those behind the Magic Mirror software make it very easy to get things installed and moving, this is what you need to do:

Update OS

Generally its considered best practice to ensure your OS is up to date before you get started.

Install MagicMirror²

Open a bash terminal

Run the following:

bash -c "$(curl -sL https://raw.githubusercontent.com/MichMich/MagicMirror/master/installers/raspberry.sh)"

This will pull down and install everything we need to get the MagicMirror up and running. Once complete you should be presented with the MagicMirror UI.

The next thing you can do is modify the configuration slightly to better suit your needs. For example

  • Update the news feeds to a provider of your choice
  • Update the weather to your location or one you are interested in
  • Update the Calendar to your own
  • You can also add additional modules:
    • For information on this please check out the GitHub page here

Now finally for the Pi we need to make sure the Magic Mirror starts for us on boot. It is recommended to use PM2 for this.

Setting up PM2

First, we need to install it; so run the following from terminal:

sudo npm install -g pm2

Second, we need ensure PM2 starts on boot; run:

pm2 startup

Once that is finished, run the command it shows you.

Next up we need to add a start script for our Magic Mirror, it is recommended to put this script in the Magic Mirror directory (and its just cleaner)

cd ~
vi mm.sh 

If you’re not experienced with ‘vi’ try ‘nano‘ instead. Now we want to add our startup commands

cd ~/MagicMirror
DISPLAY=:0 npm stat

Save and close vi. Ensure script is executable by running:

chmod a+x mm.sh

Now lets start MagicMirror using PM2; run:

pm2 start mm.sh

MagicMirror should now start up. Once it does press the super key + tab to navigate back to your terminal and run the following to ensure PM2 starts your MagicMirror on boot.

pm2 save

That’s it, our software side of things is complete next up lets check out the Mirror itself.

The Mirror

The mirror was one of the things that stopped me going forward in the past. I’d spoken to a local Mirror shop and they made it sound like getting the two way sheet/glass was going to be really difficult. Annoyingly if I’d just taken a look on the web I’d have found it. This time round I took to Amazon a tried to hunt something down, luckily I found a seller called Sign Materials Direct who sold something along the lines that I needed.

Unfortunately they didn’t sell it the size I needed as the sheet needs to match the monitor. Luckily, again, however someone had had a similar issue as me and had asked the question about customisation. Turns out they can cut the material to “any shape or size” you need. So I got in touch with them at the email address in the link (who got back to me very quickly) and within a few days I had my custom cut sheet that fit perfectly.

If you’re in the UK I would highly recommend you give them a try, I was really happy with the price and speed.

Also best to add I’m not affiliated with Sign Materials Direct, just a happy customer.

Custom Cut Acrylic Mirror

The Frame

At first I was thinking I might make the frame myself as I was going to have to make a housing unit to put the monitor in and then attach it to the frame anyway. Then I realised, I am neither a carpenter nor an artist and threw that idea a way.

We have a large Mirror in our living room and thought getting a matching frame would look quite good. So off to the local Mirror shop I went again, that’s where the larger mirror came from, and that was a no go as their supplier doesn’t do custom sizes. But moving on anyway I gave the internet a go and found a company who make custom frames and thought they looked really nice. So I got the frame from there.

Frame

Now I was a bit worried about was may be I’d measured something wrong or had typed something wrong, made a “school boy error” or one of the pieces didn’t fit right etc. But nope it was all good, the frame and Mirror fit perfectly.

Frame and Mirror

The Wood

The next step was to get some decent wood and cut it to house the monitor and Raspberry Pi. I didn’t have a saw so this was a pretty good excuse to get an over the top tool for the job right?

The wood I used was Redwood planed timber, apparently normally used for door frames. But did the job quite nicely in this instance. Unfortunately I didn’t take any pictures for that part which may have been the most interesting, wood cuttings everywhere and a large circular saw.

Anyway I ended up with a bit more than I needed, mainly because I cut one piece slightly too small so had to go buy some more. Though I’m sure I’ll be needing to cut it for a shelf or something… or to just cut it. So got the wood cut to the right size, screwed the pieces together, and painted the whole thing white. Eventually, once dried, got the housing unit attached to the back of the frame with perhaps a few too many screws than was needed but better safe than sorry right?

One thing I would add if you decided to do this yourself, I can’t imagine the unit would get too hot but I drilled two large(ish) holes into the top of the housing unit to allow some kind of air flow just in case. I’m not planning on leaving it powered on all the time but I would say it’s worth putting the holes there.

On the wall

The final job, getting it on the wall. This step was easier to do than I thought it would be as the wall had a large screw in it already for the Magic Mirror to rest on all I needed to add was something to stabilise it. This was done by adding some 90° hooks to the underside of the Housing unit to give the overall structure more support. I may add some more hooks to the top of the housing unit to make sure but it is certainly well secure now.

Finally

Well thanks for sticking all the way through this post. I know it’s not my normal style but I thought I might try adding this as it’s the first project I gave a go and am quite pleased with the results. The fiance really likes it so that’s good.

With all the modules available for the Magic Mirror and no doubt some more really cool ones that will come out the in future I’m going to add to what I’ve got so far. Things like facial recognition, Alexa integration, calendar notifications, and there’s plenty more.

Hopefully you decide to give it a go yourself and if there’s anything I can help with please get in touch.

SOLID Principles

I thought this week we’d check out the SOLID principles I touched on in previous posts (here and here). I’m thinking get a quick overview like we did with Design Patterns and may be we can then take another look at each principal again in more detail in the future.

So what exactly are the SOLID principles? They are really good guidance on how to design and develop highly maintainable, flexible, and easily understood software. Initially coined by Uncle Bob, if you read my previous post you know to check out one of his books, Clean Code, in a paper he wrote in 2000 called Design Principles and Design Patterns with the term SOLID coming later.

SOLID itself is made up of 5 principles, each a letter in the SOLID acronym, so lets get started…

Single Responsibility Principle

The first principle, and the ‘S’ in SOLID, is the Single Responsibility principle. This principle at its core means:

There should never be more than one reason for a class to change

In essence a class should only ever do one thing, it should have one responsibility. This allows us to know exactly what our class is doing and why.

One of the easiest ways to apply this principle is if the description of your class or method has the word ‘and’ in it you may well be doing more than one thing.

By following this principle we can reduce coupling between classes and improve the maintainability of our code.

Open-Closed Principle

Next up is ‘O’, that is the Open-Closed principle. The Open-Closed principle states:

Software Entities (Classes, Modules, Functions, etc) should be open for extension, but closed for modification’

So what does that mean? It means our goal is to ensure we can always extend the behaviour of an entity, lets say we have requirement changes or future developments but at the same time we do not modify the existing behaviour of an entity.

Personally I view this more from the perspective of the interface, we should always strive to maintain compatibility and, ideally, never introduce breaking changes by modifying existing entities but we can add modifications by extending it.

Liskov Substitution Principle

This one initially I found more confusing that the previous two but the more you use and understand these principles the better. Developed by Barbara Liskov in her keynote in 1987 called ‘Data Abstraction”, within the realm of SOLID it is defined as:

Functions that user pointers or references to base classes must be able to use objects of derived classes without knowing it”

This principal states that an object of a base class must be replaceable with an object that is of a child class (Polymorphism?).

As above I like to apply this by thinking interfaces, if I expect an interface within my code base, then any class than implements that interface and therefore fulfills the contract can be used.

Interface Segregation Principle

The ‘I’ in SOLID is for the Interface Segregation Principle, developed by Uncle Bob when he was consulting for Xerox. The principle is defined as:

Clients should not be forced to depend upon interfaces that they do not use.

Similar to the Single-Responsibility Principle mentioned above the goal here is to reduce the amount of “stuff” our code does and so reduce the complexities within the code base.

This one I like to think of as we should aim to define a lot of related interfaces instead of one massive ‘Jack of all Trades’ interface. The aim is to provide clients only with what they need instead of forcing them to use something “bloated”. The nice outcome of having multiple interfaces means a client can implement only those they require and are not forced to provide implementations for functionality they won’t or don’t need to use.

So our goal is to have a number of interfaces that can be used to make up the whole but can also be split and implemented on a smaller scale.

Dependency Inversion Principle

So the last principal, ‘D’; the Dependency Inversion Principal. Again developed by Uncle Bob, in a report he produce in 1996 called ‘The Dependency Inversion Principal’ (certainly worth a read). Interestingly this principal actually comes in two parts, defined as:

‘ A. HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW
LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
B. ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS
SHOULD DEPEND UPON ABSTRACTIONS.’

What this principal is trying to enforce is that changes at the low-level do not cause cascading effects to the high-level. Our high-level modules contain the business logic of our applications, now if these modules depend on our low-level modules changes to the low-level may have direct consequences for our high-level and vice versa. Our goal should be to decouple the high-level modules from the low-level (again vice versa).

Why? Mainly re-usability and less fragility, by decoupling our code we increase the portability of our classes or modules (don’t reinvent the wheel) and we make our code less prone to breaking when changes are made.

Conclusion

Well there we go, this has been a short introduction to the SOLID principals and hopefully has given you some information on what they are and how they may be used day to day. I may produce a post for each principal and provide examples in C#, if the interest is there.

One thing I have found is that the principals play well with each other and so as we try to apply them more and more each day to our development practices they quite easily become habit.

As usual feel free to get in touch either by the comments or the contact us page.

Names

My posts up to now have been some general introduction the Software Development and I wanted to continue that trend (and do so for a while longer). This time I thought we’d take a look at something I think is very important, Names.

As Software developers we name a lot of things; methods, functions, data members, properties, variables, arguments, packages, and of course classes. One thing I have aimed to do since reading ‘Clean Code’ by Robert Martin (also known as Uncle Bob), is to give EVERYTHING I name decent intention-revealing names. That is, I try to name things in such a way that anyone (including myself) who reads this code can have a clue what my intention was when I originally wrote it.

One of the main goals of intention-revealing names is it should result in an almost comment free code base, granted you will have some comments in there (and as I like to try to use the StyleCop style guide for Visual Studio I don’t fully adhere to this rule myself). Lets check out an example to see what I mean.

Lets say you’re reviewing code trying to find a bug (the code is what you wrote 6 months ago) and you come across this.

int T; // time

It is not unreasonable to think, what is time, time since when, why is this time important and why is it named T? In reality if it had just been given a more intention-revealing name there wouldn’t be the need for the reader to go hunting what it is and what it’s for. Instead it could be

int TimeSincePlayerLastMadeMove;

The above code gives far more information that ‘T’, (although if I’m honest I’d say we’d want to go one step further and apply the Single-Responsibility Principle and wrap this up in a class, but I’ll go over that in more details in another post).

We also want to avoid adding unnecessary information that just added to the confusion, so for example if we started off with

List<GamePiece> PieceList; // Players Game Pieces

We’ve included the collection type in the name but what if we change it from a list to something else, say an ICollection? Whilst the name infers its a collection of some sort any future user may well try to make use of it as if it were a list, as mentioned leading to confusion. Instead we could use

List<GamePiece> GamePieces;

An obvious issue Uncle Bob raised was that we should make meaningful distinctions within our code and not just code to make the compiler happy and we should avoid what he calls ‘noise’ words like, a, an, and the, that again may add confusion where there just isn’t any need to have it.

The book explains that we should strive to use pronounceable names, things that when we are in a meeting people know what it is we are talking about. Unfortunately I don’t have a personal example of this (though I would say acronyms are one of my biggest pet peeves in meetings), however he does have one he explains that he had come across ‘genymdhms’ which stood for ‘generation date, year, month, day, hour, minute, and second), not ideal really.

I won’t run through the entire section from the book there’s just a few more points I’d like to mention.

Class and method names, now class names should be a noun such as Customer or Account, they are names of things and so we should be using naming words. Method names should be a verb such as DeleteAccount, GetUserName, or SaveGame, they are things that do something so we should be using doing words. We’re very lucky today that if we name something and decide it’s not the right name we can quite easily refactor our code and have a name change ripple throughout the code base.

A key point that I think Uncle Bob raises that is spot on is the reason people use shorter less meaningful names is to ensure it shortens the code for that line or it means the required coding standard. Two of the coding standards I’ve come across in the past was MISRA and Google C++ Style, and they have a line length limit. I can’t recall the MISRA length I think it was between 80 and 95 lines but the Google Style limit was 80 with additional rules when 120 and 150 was broken (though in all honesty I think 150 is a bit much). The main reason for both of these limits was a throwback to when screen sizes were limited and if code was going to be printed. Now for the printed code issue I have not and I don’t know anyone who has had to print code out (at least in the past few years). For the former as our monitors are continuously progressing this just seems like a poor reason and I can’t see how it will continue as a rule. Though to be fair Google themselves state it is a throwback to the 1960s (link here).

So there we go, one of our many aims of writing code should be to make the things we name far less confusing than they need to be. Granted I am cherry picking things here and I do highly recommend any and every one interested in writing software pick up Uncle Bobs book and give it a read.

Design Patterns

Going to keep this one small and to the point today and we’re going to take a look at Design Patterns.

Essentially design patterns are a reusable solution to solving our software development problems. This is great because it means someone has taken the time to put together problem solving templates that we can apply during our development.

Now there are a lot of design patterns out there and I mean a lot but they all, generally, fall into 3 categories:

  • Creational
    • Concerned with the creation of objects
  • Structural
    • Concerned with the relations between classes and objects.
  • Behavioral
    • Concerned with the interactions between objects

The above 3 categories pretty much sum up all the design patterns we need to worry about about.

So how did we get to the point where we have well-know and well-defined design patterns we can use? It started with the release of a book called Design Patterns: Elements of Reusable Object-Oriented Software in 1995 by a group called the Gang of Four (GoF). The GoF consisted of:

  • Erich Gamma
  • John Vlissides
  • Richard Helm
  • Ralph Johnson

Which even today is considered one of the most reliable resources on software design patterns. From this book we got 23 design patterns split into the above 3 categories.

  • Creational: 5 Patterns
    • Abstract Factory
    • Builder
    • Factory
    • Prototype
    • Singleton
  • Structural: 7 Patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioral: 11 Patterns
    • Chain of responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template
    • Visitor

Well that’s quite a list isn’t it, and it’s only grown since then.

So how do these patterns actually help us with developing software?

I’ll pick that up next with posts dedicated to each category, first up: Creational.

I welcome feedback, especially at this very early stage, so any improvements you think I can make please get in touch either in a comment below or send me a message and I’ll get back to you.

Four Pillars of Object Oriented Programming

Introduction

This week we’re going to look at the Four Pillars of Object Oriented Programming as a nice follow on from the last post, Procedural and Object Oriented Programming, the plan here is we’re going to expand on what was mentioned and get more information on what the Four Pillars actually are, in a simple and to the point way. So first off, lets name them:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

As a side note there is also the term Three Pillars of Object Oriented Programming, this version however does not include Abstraction. So I went for doing a post on the ‘Four Pillars’ as it would literally give the best of both worlds.

Abstraction

The first Pillar we are going to look at is ‘Abstraction’, also called ‘Data Abstraction’, this is the means by which we only show (externally to our class) what is absolutely necessary and we hide all other aspects of the class. This is where the access modifiers I mentioned in Procedural and Object Oriented Programming come in, that is public and private (there is also protected and for C# internal but we’ll just concentrate on public and private). So, in a class those parts (data members and methods) we want other entities to see we make them public and the parts we want to keep hidden we make private.

A good example of this would be the consider a car. When we want a car to turn left we use the steering wheel. How exactly the wheels move in the correct direction we don’t really need to know, just how we move the steering wheel (our public method) ensures all the actions ‘under the hood’ (our private methods) makes the wheels turn in our desired direction.

So Abstraction, also called Data Abstraction, is the process of hiding data and information.

Encapsulation

Encapsulation is the process of containing or ‘encapsulating’ our state and behaviour, that is our data members and methods within a self contained entity, for example a class (check out my Procedural and Object Oriented Programming post for a bit more info). When applying our Access Modifiers (see Abstraction above) we can limit who has access to that state and behaviour. Encapsulation is a very useful mechanism as it allows us to place all the related ‘stuff’ of a class (data members and methods) within one nicely contained and well named package, i.e. class (I’ve made a point of well named because after reading a book by Robert Martin called ‘Clean Code’ it is a must, I recommend you read this but I’ll be giving you some details in the future).

And that’s it encapsulation is that simple, wrapping up state and behaviour within a single class.

Inheritance

Similar to how we consider the term in the real world when applied to parentage. It is the process in which we allow our classes to get data members and methods, state and behaviour, from other classes. Why would we want this? Why not write each class individually? Well the biggest answer is code reuse, the more code we write the more bugs we bring into a system and the more code we have to maintain. If we can write a class then allow other classes to take that functionality and use the content without having to write it that is very helpful. It’s similar to how a child gets some characteristics from their parents. We call the class providing the members and methods the parent or base class and the class inheriting the members and methods the child or sub class.

Different languages have different versions of inheritance, so C++ allows a child class to have multiple parent classes, there are pros and cons to this, one of the most well know cons is the diamond problem (to avoid getting side tracked I’ll do a post on this in the future). Another form of inheritance is single parent inheritance (from classes), in this case we can only ever have one parent class and of course this can go up the chain, so our parent class can have one parent class and so on, this is the case in C#. In C# however we concentrate more on the use of interfaces, which is where we define a contract and leave it up the the inheriting classes to provide the implementation (again this will definitely be a future post, very important).

So the easiest way to know if you need inheritance is think can I apply the ‘is-a’ relationship, i.e. a car is a vehicle, so in this circumstance we may have a vehicle class and a car class where we may, and probably should, have our car inherit the characteristics of vehicle.

Polymorphism

The final pillar we’re going to look at is Polymorphism, ‘poly’ means ‘many’ and ‘morph’ means ‘forms’ so ‘Polymorphism’ means ‘many forms’. It allows use to define, say, a method in our base class and allow our child classes to provide their own implementation of that method. A good example is if we have an Animal base class with a method called ‘MakeSound’, now the result of ‘MakeSound’ would be different for pretty much every animal we created, for example a Dog would bark, a Cat would meow, a Lion would roar, and a (male) Grasshopper makes their noise by rubbing a hind leg on their wings.

It essentially allows for a contract to be agreed, so in terms of our animal example every animal that inherits from the Animal class are essentially saying I will provide you with my own ‘MakeSound’ implementation.

This one tends to be a bit trickier than the other pillars but it is quite that simple, if there is any interest in some more information please free feel to ask.

 

And there we go a quick view on the Four Pillars of  Object Oriented Programming. Hopefully that has given you some insight however if you have any questions please feel free to ask. 

Procedural and Object Oriented Programming

Introduction

Now that we have our Visual Studio Development environment setup and have some background in software (check out my previous posts) let’s start looking at Procedural Programming and Object Oriented Programming (OOP). During this post I want us to take a quick look at the history of the two main methods of software development, that is Procedural and Object Oriented, the differences between the two and then delve deeper into OOP. I started my introduction to programming with procedural before moving into OOP using C/C++ and as I will be focusing on using C# for most of my posts we’ll be taking a far larger look at OOP than procedural. So let’s get started…

Procedural Programming

Procedural is where we have variables, that is a container we use to hold our data, and procedures/functions, this is a defined section of code that performs ideally a single task (I say ideally because this isn’t always the case, I’ll be producing a post on some programming principles where we’ll cover these in more details) based on some information it may require and may or may not give something back, lets see an example:

In the case for the variable, our data the system will hold, which would be considered it’s ‘state’, we’d normally find the data held in variables (check out What is a Program? for more info) such as

int age;
string name;

The example above shows two variables,

  • An int called age
    • An int is a whole number, it cannot have any decimal places.
  • A string called name
    • A string holds characters, that is letters, punctuation, and other symbols

So with age we can store any whole number and if we want to get to that value we use the name ‘age‘ to do so, the same applies to name, we can store someone’s name in the variable and if we want to get the value of name we just use the variable name to get access.

For both of these variables we’ve given them useful names and can assume they are related to a person in some fashion.

Quite straightforward for variables, now let’s take a gander at functions, which would be considered the systems ‘behaviour’:

int add(int x, int y)
{
    return x + y;
}
  • The first word ‘int‘ is the data type that will be returned from this function
    • Returned means at some point, normally the end, the function gives data back using the ‘return’ keyword to identify what holds that data.
  • The second word is the name of the function ‘add‘, callers to this function will use this name to tell the system that is the function they want to use.
  • The opening parenthesis ‘(‘ is used to identify the beginning of the values the function expects to receive, this is called a ‘parameter
  • Now, we need both the ‘int‘ and the ‘x‘ for this bit, the ‘int x‘ section tells you we want an int called ‘x
    • Think variable.
  • The use of ‘,’ is simply to separate parameters so if the function expected 3 parameters it would be:
int add(int x, int y, int z)
{
    return x + y + z;
}
  • The opening curly brace ‘{‘ is used to define the start of our scope, scope is simply the start boundary for our function and the closing curly brace ‘}’ defines the end of our scope.
  • The content of our function, which is very small, is found on line 4
    • All we do here is add x and y together then return that new value as an int, quite simple.

Let’s take a quick look at a very simple program (in C++):

// So this is our function, we expect to be given two values x and y
// and we'll give back a new value which is the result of adding x and y
int add(int x, int y)
{
    return x + y;
}

// As mentioned in a previous post, this 'main' method is quite important 
// and is the starting point for a lot of programming languages, in this case C++
// We'll not be looking at that here though
int main(string[] args)
{
    // Our first variable of type int called starting_balance and it has been assigned a value of 100
    int starting_balance = 100;

    // Our second variable of type int called deposit_amount and it has been assigned a value of 50
    int deposit_amount = 50;

    // Not here is our third variable called end_balance but it is not assigned an amount directly instead we are 
    // calling the add method and passing the starting_balance and deposit_amount variables to the function.
    // Which we expect the add function to return another int to us, and it is that value we are assigning to 
    // end_balance (which is 150)
    int end_balance = add(starting_balance, deposit_amount);

    return 0;
}

The above is not a very useful program mind you but hopefully proves the point.

So that is an exceptionally quick and shallow overview of Procedural Programming but gives us some useful information and I hope shows we can develop anything we want really. My background has been more focused on Object-Oriented so let’s move on to that.

Object-Oriented Programming

Now then let’s check out Object Oriented Programming (OO or OOP)…

In our look at Procedural Programming, the state and behaviour do not really have a strong relationship, in the world of OOP that is not the case. The Object in OO refers to an entity within the OO domain and that object contains both the state and the behaviour, that is the variables and the functions, which in this context are generally called attributes and methods respectively. An object is a self-contained representation of ‘something’, such as a person, shape, car, or anything else, that has both state and behaviour.

The reasoning here is how do we prevent anyone from changing the state within a procedural program? It’s a bit difficult, so by wrapping state and behaviour up in a nice object, which is defined in something called a class, we can control access and manipulation to that state, we call this Encapsulation (and it is one of the ‘Pillars of Object-Oriented Programming’) because we’ve ‘encapsulated’ both state and behaviour within a single container. The next stage is the use of data hiding, another principal in OO, here we restrict how that state is changed and only allow specific ways of changing the state. That would be by the use of those methods mentioned earlier, that way we can ensure only changes we allow can be made to our state. The really nice thing about this is by restricting access to an objects state we prevent any accidental (or intentional) corruption of that state. We can, and should, hide a lot of the internals of an object from the outside world by use of access modifiers, that is we only provide very specific methods to change an objects state and we hide everything else. The easiest way I find people understand this is by thinking of a car, now not everyone fully understands how the internals of a car work, for example how exactly a combustion engine works, and because of the design of a car, you really don’t need to know this. All we, the driver, need to know how to do is to make the vehicle move that is switching the car on, steering it, accelerating, braking, changing gear, adding fuel, etc, you only need to know how to operate it you don’t need to worry about anything else. So as programmers we can do the same, we can provide users of our objects with simple methods and hide anyway all of the complexity.

So there are a few terms in the previous paragraph that need some explaining, (right?):

  • Attribute:
    • An attribute is a variable held within a class, it should not be accessible to the outside world
  • Method:
    • A method is a function held within a class, it can be accessible to the outside world or hidden
  • Class:
    • A class is simply a blueprint for an object, we use classes to define attributes and methods within a container
    • Another good analogy is a blueprint for a house, we use the blueprint to define how to build a house but it is not the house itself
  • Object:
    • Using the above analogy an object IS the house, it is what we have created from the class, the blueprint
  • Access Modifiers:
    • Access Modifiers are keywords we assign to our attributes and methods, this allows us to control access
    • For now, think of there being just two access modifiers:
      • Private: This means only the class has access to the attribute or method
      • Public: This means any entity can access the attribute or method held in a class

I think it will be worth looking at an example (in C#):

// Here we use the keyword class to identify we are creating the blueprint
// We have called the class Person, similar to how we create variables; 
// start with the type, in this case its a class, then give it a name, 'Person'.
public class Person
{
  // So here we are defining 3 attributes, notice the access modifiers.
  // The first is an int called age, we give it an initial value of 0
  private int age = 0;
  // The second is a string called name
  private string name;
  // The third is a string called message
  private string message;

  // Here is a method we have set to public, this means the method can be 
  // access by any holder of a Person object.
  public SetNameAndAge(int newAge, string newName)
  {
    age = newAge;
    name = newName;

    // UpdateMessage isn't available to anything outside of the scope of the class
    UpdateMessage();
  }

  // This is our first private function
  // The type 'void' means we do not return anything from the method
  private void UpdateMessage()
  {
    // So we update the message variable to the following
    // The use of quotes defines a string
    message = "Hello, " + name + ". You are " << age " year(s) old.";
  }
}

This is a very simple class but I hope it helps to show some of the above content in an actual example, check out my previous post as well about What is a Program? to add some additional value.

Why Object Oriented?

Ok so we’ve had a very quick look into OO, but why would we want to use it instead of saying Procedural. I’ve touched in it very slightly above but because of the Four Pillars of Objected Oriented Programming. They are:

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

we’ll be looking at the Four pillars exclusively in another post, so keep an eye out for that.

I hope you’ve found this post a little bit useful and if you have any questions or there’s something I haven’t explained very well please feel free to get in touch.

I welcome feedback, especially at this very early stage, so any improvements you think I can make please get in touch either in a comment below or send me a message and I’ll get back to you.

What is a Program?

What is a Program?

We’re going to look at some rather interesting stuff today. If you’ve read my other posts you’ve probably been thinking “When are we going to start coding dude?” but I wanted to give you at least a small introduction to the larger picture before getting stuck into actually writing any code, don’t worry though we’ll be looking into that shortly

So today I wanted to take the time to look at What a Program is (see What is Computer Software? for more information) and how we can create them. I hope you enjoy this part of your introduction I know I did quite a few years ago.

What is a Program?

Essentially, a program is just a set of instructions given to a computer to solve some problem or to perform a task. So if we wanted to work out someone’s annual business mileage, we would do the following.

  1. Ask the user “How many miles do you drive for work per day?”.
  2. Wait for the user to provide us with the number of miles.
  3. Store that number in memory using something called a “variable”.
  4. Ask the user “How many days in a year do you work?”.
  5. Wait for the user to provide us with their days.
  6. Store that number in memory using a variable.
  7. Create the user’s mileage by multiplying the number of miles by the number of days, also stored in memory using a variable.
  8. Display the annual mileage to the user on the screen

As a whole, the above steps would be called an algorithm (we’ll be looking at Data Structures and Algorithms in the future). For right now an Algorithm is just a collection of clear logical steps used to solve a problem or to perform a task. As you can see we perform the above steps in the order given and we will get the output we expect, while some elements could be rearranged we can’t perform steps 7 and 8 before steps 1-6.

One thing we must be absolutely clear about is that a computer does ONLY what we tell it to do, unlike us (humans) it does not interpret the meaning of things, it does exactly what it is told to do. So how do we use the above steps to tell a computer how exactly to do what we want, there are a few steps involved:

  • The first is we need to use is a programming language to put our intent into a human-readable format using code
  • The next is to convert out intent into a format the computer can interpret
    • This has several steps:
      • In some languages, we turn it into something called object code
      • Then we convert the object code into a machine-readable language, 0s and 1s called binary or machine code.

What is a Programming Language?

A programming language is just a way in which a human can provide their intentions to a computer. We have two categories of languages that we use:

  • Low-level
    • This language category resembles something closer to Machine Language
  • High-level
    • These languages resemble something closer to a human language

Low-Level Languages

We won’t be looking into these languages (for now at least anyway) but as mentioned these languages tend to resemble Machine Language and for a lot of your programming tasks won’t be something you need to have a great understanding of. Having said that it doesn’t hurt to have a quite overview.

Depending on how low into the Low-level category we are, the code itself may run directly on the computer, being executed by the CPU (check out my post on Computer Hardware if you haven’t already), and this would be called Machine Code, there are some further steps such as Microcode, I won’t be going into that but feel free to check out google if you’re interested.

We also have Assembly Language, this is classed as any low-level language that has a strong relationship with a program and the machine code instructions. As mentioned, I don’t intend to look at this in much more detail but we’ll see how things go.

High-Level Languages

Now that we’ve had a, very brief, look at Low-level languages lets check out some more high-level stuff. There are a lot of high-level languages that have been developed over the years and we’ll discuss the differences between the language types later:

Language Description
C A general purpose language. Developed by Dennis Ritchie for Bell Labs between 1969 and 1973. Many languages are related in some way to C.
C++ A general purpose language and based on the C language. Developed by Bjarne Stroustrup in 1979 to add “classes” to C. We’ll check out classes in a later post.
C# A general purpose language and is part of the C family of languages. Developed by Microsoft and used with the .NET platform.
Java A general purpose language developed by Sun Microsystems and now owned by Oracle. This language is not linked to JavaScript
JavaScript A general purpose interpreted language and is one of the core technologies involved in the World Wide Web. Originally designed by Brendan Eich at Netscape. This language is not linked to Java.
Visual Basic An event-driven Windows-based programming language used to create applications quickly. Developed by Microsoft and used in the .NET platform.
ADA A general purpose language used predominately within the defence and aviation sectors. Named after Augusta Ada the Countess of Lovelace who is regarded as the first programmer.  Developed by the US Department of Defense in the 1970s
Ruby A general purpose interpreted language quite popular with programs running on web servers. Developed by Yukihiro “Matz” Matsumoto in the mid-1990s.
Python A general purpose interpreted programming language. Quite popular in commercial and academic domains. Developed by Guido van Rossum in 1990.

High-level languages allow humans to provide instructions to computers in a format that we find easier to associate with a written language, such as English, which is considered the universal language of software development with almost all code being written using English text. I’ll be primarily using C# and C++ through my posts but may occasionally use Python, Java, and JavaScript just to add some variety to life.

Ok, so we’ve seen some information on low-level and high-level programming languages but what exactly is involved in creating a program. Let’s take a look:

Most programming languages have a lot of similarities:

Language Component Description
Key Words Keywords can only be used for specific purposes, they are words defined as part of the language and have a special meaning. They are also called Reserved Words.
Developer Defined Identifiers These are symbolic identifiers defined by the developer of the program. 
Punctuation Punctuation is used to identify the beginning and end of statements or separate items.
Operators Operators are used to perform actions on pieces of data known as Operands
Syntax Syntax defines the rules that must be followed in order to create a program. The rules determine how the above Keywords, operators, punctuation, and developer-defined identifiers can be used. 

Simple Program: Hello World

So now we’ve got a decent overview of programs and what is involved let’s create a very simple, and pretty standard first, C# program and look at the parts.

namespace WhatIsAProgram
{
  class Program
  {
    static void Main(string[] args)
    {      
      // First assign the text we want to display to a variable
      string outputText = "Hello World";

      // Next use the language provided features to send 
      // our text to the console.
      System.Console.WriteLine(outputText);
    }
  }
}
Key Words:

We have a couple of keywords defined within this simple program including:

namespace, class, static, void, string

These words within C# have special meaning and can only use for that purpose.

namespace

Used to organise code and wraps anything within a namespace removing the risk of conflicting names.

class

Used to create a class, I’ll be putting a post out on object-oriented programming (OOP) so will cover this in more detail, but a class is a blueprint, with state and behaviour, for something we want to represent within our code. Such as a car, person, or book, take a car the state could be speed and mileage and behaviour would be Increase Speed and Increase Mileage.

static

This is a little complicated but static means we are referring to the type and not to an object we’ve created. So if we had multiple objects with a static state, each object would reference the same state. Again, once we’ve done some OOP it should be clearer.

void

We can use blocks of code to perform tasks for us in some cases the code may give us something back and in others, it won’t. Use in this context void keyword tells the program nothing is given back.

string

string is a class, notice we are using string in two places, first at line 5 then at line 8. At line 5 we are saying, this block of code will receive multiple separate strings (defined by the use of []) and in line 8 we are saying I want to create an object and it will be of type string.

Don’t worry too much if a lot of the content here is confusing, as we progress and more of the holes are filled in the concepts will begin to fall into place.
So as described the keywords above have a special meaning and we use them to get specific functionality from the C# programming language.

Developer Defined Identifiers:
This one is a little more straight forward, there are 3 (technically 4) developer defined keywords within our small program. Developer defined identifiers relate to the parts of the component the developer has control over to define the names of such as classes, methods, namespaces, and variables. We can name these almost anything we want EXCEPT for the Keywords mentioned above, the main goal, however, will be to ensure you give them meaningful names but this is a whole other topic that we will be returning to in the future.

WhatIsAProgram

This allows us a means of identifying the name given to the wrapper around our code.

Program

The name given to our class, again keep an eye out for the Object Oriented post and we’ll go into much more detail there, but the use of Program here is simply convention.

outputText

This is the name we’ve given to a variable, think of this as a container which can only hold text and we can identify that container by use of its name. We will be looking at this in more detail shortly.

Additional

Main

The text ‘Main’ identifies the name of something called a method, while method names are developer defined this is a unique case, in C# when we convert our code to be closer to low-level ( this is called ‘compiling’) and usable by the computer that process requires ‘Main’ to be available, for executables, and is used as the entry point of our program. That means every single C# program MUST have a Main method in order for the program to be compiled.

Punctuation:

Nice simple one here, punctuation is simply a means for developers to show the end of a code statement or to identify separations within a list. So in our example lines, 8 and 12 show the use of punctuation in the form of a semicolon, representing the end of those code statements. At the moment it may be confusing because as you can see not every line shows a semicolon but remember they are only used to show the end of a code statement.

Operators:

In our example we only have one operator in use:

=

This is called the assignment operator, it takes the value on the right-hand side and stores it in the left-hand side.
There are many other operators available, (Quick Note: We follow the rules of BODMAS (google for a refresher)):

*

This is called the multiplication operator, it multiplies the two values. Normally used in conjunction with the assignment operators. e.g.

int result = 3 * 4

The value of result would be 12.

/

This is called the division operator, it takes the value on the left and divides it by the value on the right. Normally used in conjunction with the assignment operator. e.g.

int result = 8 / 4

The value of result would be 2.

+

This is called the addition operator, it adds the two values. Normally used in conjunction with the assignment operator. e.g.

int result = 5 + 2

The value of result would be 7.

-

This is called the subtraction operator, it takes the value on the right and subtracts it from the value on the left. Normally used in conjunction with the assignment operator. e.g.

int result = 8 - 3

The value of result would be 5.

We’ve got many more but we’ll look at them in good time.

Syntax: 

So as mentioned the syntax is the rules we must follow in order to create a program. As with natural languages we have rules we must follow in order to create a correctly formatted sentence, the same is true for programming languages. Each programming language has its own sets of rules, much of them shared. Especially with those, I’ll be showing, C++ and C#, and as I post more hopefully these rules will become apparent. We could go through them but I think that would get tiresome quite quickly and we can learn by doing really.

So there we have it a somewhat longer overview of What a Program is than I was expecting however I think this gives us some good details to move forward with. Next up lets setup our machines so we can create some programs…

I welcome feedback, especially at this very early stage, so any improvements you think I can make please get in touch either in a comment below or send me a message and I’ll get back to you.

What is Computer Software?

What is Computer Software?

We’ve had a very brief overview of Computer Hardware if you haven’t checked it out feel free to do so. I thought it would give those with a little more curiosity a starting point and is not required to move forward.

Now then, let’s check out a quick overview of Computer Software before getting stuck into checking out our first programming language.

In order to get our Computer Hardware to do anything useful we MUST have software, it is not optional. As soon as we start the computer, the software kicks in and controls the hardware. In general, we can split software into two separate categories:

    • System Software
    • Application software

System Software

The software that controls or provides access to the hardware and general operations of the computer is called the System Software and can be further broken down into 3 categories

  • Operating System

This category provides the most crucial collection of programs found on a computer. The Operating System provides many services, from controlling the operations of the Computer Hardware, spawns other programs, allows data to be saved and read, and manages connected devices. In the (distant) future I want to provide an Introduction to AOSP, this is looking at the Android Operating System and we will get ourselves a copy, build it for a commercial device, then flash our version of Android to that device, I did this in one of my jobs and it is some seriously exciting stuff.

  • Software Development Tools

This category will be very important to us as we progress, Software Development Tools provide us (Developers) with the ways we create, modify, and test our software. There is a lot for us to look into in this category and I’ll also be putting together a post on the types of IDEs (Integrated Development Environments) and text editors we can use and what languages (I personally think) are worth learning. We’ll even be learning some languages together, so I’m looking forward to getting stuck into that.

  • Utility Tools

This collection of programs are used to enhance the operation of a computer by performing very specialised tasks, this includes programs that provide data-backup and scan for viruses. There is currently no intention to delve into this area but we can see how things progress.

Application Software

I’ll keep this one short because we will be looking into it a lot but, essentially this is almost every other program you find on a computer, and importantly the same software I intend on teaching you how to develop for yourself. So this will be anything from the browser you’re using to read this, any word processing application, the previously mentioned IDEs and text editors, to computer games. This is the category of software that the vast majority of computer users spent their time using. So keep an eye out for the next post where we will look further into Programs themselves and how we can go about making our own.

This was quite a short one but it provides the information I intended and gives us some useful information moving forwards, the next stage will be looking at software and programs in more detail. Check it out here

I welcome feedback, especially at this very early stage, so any improvements you think I can make please get in touch either in a comment below or send me a message and I’ll get back to you.

What is Computer Hardware?

What is Computer Hardware?

I’ve decided to start off with a bit of an introduction into computers for complete beginners and so this will be part of that content. So let’s start with Computer Hardware – Side Note: This is likely to be the only post just about hardware, the next will look at software and continue from there.

The Computer Hardware is the name of the physical components of a computer system, these components can be placed into the following categories:

  • Input
  • Processing
    • CPU
    • Memory
      • Main Memory
      • Secondary Storage
  • Output

Input is the data we provide to the computer, this can be through a variety of means such as, using a mouse, keyboard, microphone, game controller, using touch input (smartphones), or other means including pulling data from a database (if you’re unsure what a database is you can think of it as a digital filing cabinet, we’ll look into then in the future).

The Processing is what the computer does with our data, so using the mouse from the input examples the computer would calculate where the mouse pointer should move to, what key had been pressed (if any), what effects the button press has made, or the action the must be performed on the data from the database (e.g. reading a name from the file)

The output is then the results of the performing some action on the data, again continuing with our previous examples, the mouse pointer moves to the correct location on the  screen, the pressed key is displayed (such as in a text editor), the game view changes in some way (perhaps the player jumped), or the contents of the data from the database is  printed.

In order to perform the above, a computer is made up of two very important parts, the Hardware and the Software (we’ll discuss this in another post).

Hardware

A normal computer is itself made up of several components:

  1. Central Processing Unit (CPU)
  2. Main Memory or Random Access Memory (RAM)
  3. Secondary Storage Devices (such as Hard drives)
  4. Motherboard
  5. Input peripherals and devices
  6. Output devices

The CPU

When the computer is performing a task of such as making a calculation, the CPU is actually the part of the computer that is performing this action. Therefore the CPU can be considered, quite crudely, to be the brain of the computer and the most important component.

The job of the CPU can be explained as follows:

  1. Fetch
    1. The CPU retrieves an instruction from RAM which contains the next action to perform for a program.
  2. Decode
    1. The instruction to execute has been stored in the form of a number, in order to perform its action the number must be decoded into an electrical signal
  3. Execute
    1.  The electrical signal is then passed onto the correct component to perform the operation, this could be the Arithmetic Logic Unit (performs the arithmetic computations) or the disk drive (to load some data).

** Fun Fact **: The original predecessors to modern computers where huge devices that weighed tons. They were primarily vacuum tubes and switches made up of electrical and mechanical components. Although they were extremely large by today’s standards they were not very powerful. An example can be found with

Electronic Numerical Integrator And Computer (ENIAC) was created in 1946 by John Eckert and John Mauchly and were capable of performing about 5000 addition calculations a  second vs a modern smartphone can perform billions per seconds.

RAM

While the CPU can be thought of as the ‘brain’ of the computer, the RAM (or Main Memory) is the memory (as the name suggests) of the computer. This is where active work is currently being stored, for example, any executing (running) program will be held in RAM, this includes any data the program is working with. RAM is also very quick, this is a huge benefit and along with many other improvements is very noticeable by how fast modern PCs run.

RAM is a volatile memory type, that means it does not continue to store its data once the computer is turned off. This is unlike Secondary memory or secondary storage, described later.

Interestingly, it is called Random Access Memory because it enables the CPU to quickly access the data stored at any random location, hence the Random Access name.

RAM is divided into small storage locations called bytes, a single byte is large enough to contain a small number or character. Modern RAM “Sticks”, a stick is just one RAM module, work in the billions of bytes. For example, a standard 4GB stick is 4294967296 bytes, huge right? Of course, this is again another example of great improvements in the world.

Each byte can be further divided into small storage items called bits (binary digit), there are 8 bits to a byte. A bit can be thought of as a tiny switch (much like your light switch) and so can be in one of two positions, on and off. In modern computers however they are not actual switches (at least not like your light switch but the understanding is easily transferable). So a bit can be thought of as being on or off or being one of two values a 0 or a 1, which is called binary. Bytes have their own unique address and is identified by that address, in a similar way postal addresses work.

Secondary Storage

Secondary storage is non-volatile memory, this means that the data stored on the disk continues even after the machine has been turned off. Programs that we install on our computers are stored in secondary storage, such as text editors, browsers, streaming services, and the apps we install. It is quite a bit slower than RAM but still very quick in its own right.

There are a few common secondary storage devices, Hard Disk Drives (HDDs), Solid State Drives (SSDs), Compact Disks (CDs), Universal Serial Bus (USB) drive, and many others.

  • HDD:  Works by storing data magnetically onto a disk.
  • SSD: Uses semi-conductor chips, for those of you who are keen on RAM chips the SSD chips are non-volatile and the data stays put without power.
  • CD:  Stores data in microscopic holes called ‘pits’ and ‘lands’, these pits and lands are read using a laser and are turned into an electrical pulse which is recognised as 0s and 1s
  • USB Drive:  Also uses chips to store data. These are small and very cheap.
  • Additional
    • External HDD: The same as HDD except these devices are connected, normally through USB, to the “outside” of the computer and can be moved between different  computers quite easily

Input Devices

In order for a computer to be able to do anything useful we must provide it with input, how this input is provided varies wildly, from using a mouse or keyboard or input from a database or a file on the computer.

Essentially any device that collects information from the ‘outside’ world and provides it to the computer is considered an input device. As mentioned, a mouse or keyboard are perfect examples but also consider the USB drive that provides us with data stored on it. Additionally, temperature reading devices or the components in modern phones such as accelerometers and gyroscopes are input devices.

Output Devices

As the name suggests output is any information provided by the computer to the outside world can be considered output, printed documents, Graphical User Interface (GUI) on a monitor, flashing LED, audio through speakers or headphones, cooling fan, data saved to external memory such as external HDD, USB devices, and CDs.

Conclusion

Hopefully, this hasn’t been too much information for you and you get the general idea of what a computer is and what each part of the computer does. Not all parts mentioned here are needed and there are some parts left off but this gives you a good starting point. I won’t concentrate too much on Hardware specifically but wanted to give an overview before I got into the areas I’m more interested in, which is Software and the next post is coming soon…

I welcome feedback, especially at this very early stage, so any improvements you think I can make please get in touch either in a comment below or send me a message and I’ll get back to you.