Category Archives: Methodologies

Understanding the MVVM Pattern

I mentioned in a previous post that I had become a Xamarin Certified Mobile Professional (check it out for an introduction too) which I really enjoyed getting to and learned a lot of about Xamarin, .Net, and the platforms involved. I’m going to start sharing more of what what I’ve learned starting now.

For this post as the title suggests we are going to look at the MVVM pattern…

MVVM is a software architecture pattern and is a variation of the MVC (Model-View-Controller Pattern). The acronym stands for Model-View-ViewModel, which identifies the key components within an MVVM targeted app but we’ll get to that.

The pattern is concerned with helping us decouple our business and presentation logic from the user interface.

Why would we want to do this?

By providing that separation between the components we can improve our development by allowing different teams (such as the design team and the development team) to work to an agreed contract and develop their own components independent of each other.

As the name suggests the Model-View-ViewModel pattern has 3 core components, Model, View, and ViewModel. As they say a picture (diagram in this case) paints a thousand words so hopefully the diagram below gives you an idea of the relationship

At a high level the interactions are as follows:
  • View: Knows about the ViewModel
  • ViewModel: Knows about the Model but does not know about the View
  • Model: Does not know about the View or ViewModel

As you can see the ViewModel provides a layer of separation between our View and Model components and through the use of Data Binding we can decouple our ViewModels from our Views. By developing our apps in this way we get quite a few benefits:

  • Adaptive: We can take old Models and adapt them for use in our apps through our ViewModels. e.g. models developed for a web app that aren’t suitable for mobile can be adapted via the ViewModel to provide our Views what they need.
  • Testable: Our unit tests can be developed and maintained easier as our C# code is separate from our UI.
  • Decoupled: We reduce the dependencies between the components and so can update them independent of the others, providing of course we continue to adhere to our contracts.

Now that we have an overall idea of MVVM lets take a look at each component.


The first component we’ll look at is the View. It is responsible for what the user  sees, the structure, layout, and appearance of each Page. Within Xamarin we have two files, a .xaml file and a .xaml.cs file, which together define our views (or pages). As the names suggest our .xaml file will hold our Xaml implementation of the UI and the .xaml.cs file will hold our C# code-behind.

So we can develop our Views using either Xaml or C#, with the use of the MVVM pattern in our apps we aim to do everything in Xaml and have the bare-minimum C#, however in some cases we may need to use C#, such as with animations.

One question you may have now is if we aim to put as little code in our View code-behind how do we allow users to do anything, such as fill in a form and submit it?

For this we have Commands, if a control (an visual item) supports the ICommand interface we can register to it to a property on it’s ViewModel (which must implement this interface). So when a controls ICommand action is triggered the associated property on the ViewModel is triggered. Additionally there are features called Behaviours, these can be attached to an object in the view and wait for either a command to be triggered or an event to be raised. Once the behaviour has been triggered it can then either call the ICommand property or a method in the ViewModel.


Our ViewModels provide Properties and Commands for our views to attach to through the use of Data Binding and through this relationship it can flow the UI presentation logic to the View without needing to know about the View. This is done through the use of the INotifyPropertyChanged interface which uses the OnPropertyChanged method to notify the View that a change has occurred, making apps very responsive if implemented correctly. 

Think of this relationship as the View is used to define how the functionality will be displayed and the ViewModel, through the use of properties and commands, defines what will be displayed in the UI.

Looking at the diagram above again you can see that our ViewModel sits between our View and our Model, this is no accident. Through the ViewModel we can co-ordinate our Views based on based on our Models and updated our Models based on our Views through the ViewModel, providing that layer of separation between the two components. In some cases the ViewModel will expose the Model directly to the View but we also have the control to perform data modification in the ViewModel to meet the needs of our expected presentation design. A very simple example could be convertign data from one format to another such as from lbs to kgs. 

As I mentioned above we perform the communication between our Views and ViewModels through DataBinding. Data Binding allows us to hook our UI elements to properites in our ViewModel and then provide either one or two way communication between the two components. 

For the ViewModel to View communication to occurr the relevant property must raise the property changed event, called OnPropertyChanged. In order to do this a ViewModel must implement the INotifyPropertyChanged interface and raise the event when a relevant property is changed. By doing this whenever the property is changed the relevant UI element will automatically be passed the new value to display. Providing up to date information to the user.

If you have a list or other collection it is a bit easier to perform that communication, use the data structure ObservableCollection<T> and much of the work is done as it implements the INotifyCollectionChanged interface. All you need to do is hook it up.


Lastly, we have the final component, the ‘Model’. This is quite straightforward, the Model is any class not directly associated with the visual aspect and can be viewed as representing the domain model.

This generally involves our data model and our business and validation logic. Examples of Model level entities are Plain Old CLR Objects (POCOs) but also include Data Transfer Objects (DTOs), entity, and proxy objects.

We primarily use this component with services and repositories for data access and caching.

So there we have it an intro to MVVM and the core components. Our View handles the formating of what the user sees, our ViewModel what will be seen, and the Model helps to organise and process.

The pattern is very popular within the mobile development domain and I highly recommend you give it a go if you haven’t already to see if you could benefit from it.

Keep and eye out for the next post.

Test Driven Development

For this post, I wanted to take a look at Test-Driven Development (TDD). What is TDD? TDD is a test-first technique in software development, that means we write our tests first then we write our actual production code. The TDD approach relies heavily on the repetition of a very short development cycle while following The Three Laws of TDD.

Always remember the goal of TDD is the make our code cleaner and simpler.

Before we get into the good bits I think it might be worth quickly going over the way software has generally been written and identify some of the flaws. It is more common to see production code written first with the unit tests being more of an afterthought, still it less common today than say 20 years ago. However, we still have the same problems, when our codebase does not contain reliable extensive tests we are hesitant to make any changes. Especially in those instances where we don’t have any real confidence in the code itself, perhaps because we inherited it, because it was rushed. By following a TDD approach we can make changes, for whatever reason, with more confidence.

Enough with looking back, let’s look forward…

We’ll start with the Three Laws of TDD, they are:

  • First Law: You may not write production code until you have written a failing unit test.
  • Second Law: You may not write more of a unit test that is sufficient to fail, and not compiling is failing.
  • Third law: You may not write more production code that is sufficient to pass the currently failing test.

If you follow these rules you get locked into the development cycle mentioned above. Uncle Bob has mentioned in his books and videos that this cycle can be from 30 seconds to a minute and there have been others that have said it could be longer. I find it varies depending on the complexity of a given situation but it is certainly within the definition of short. Essentially it looks like this:

TDD Development Cycle

The above shows a visual representation of the development cycle we get into by following the TDD approach, we:

  1. Write our test
  2. Run our tests
  3. Make code changes
    • Add required production code
    • Refactor code
  4. Run our tests
  5. Repeat

We can see that any failing test means we ‘Make Code Changes’ and any passing test we ‘Write a test’. That’s it, that’s the cycle we get ourselves into and that’s the cycle that gives us that confidence I mentioned before.

By working this way we end up with a massive suite of tests that (providing the tests themselves are of good quality) mean we can refactor, extend, or update our production code we confidence if/when we break something we find out immediately and can fix it.

I’m not going to go into any detail on the tests themselves as I find that is two different topics or at least a topic I want to expand into in the future. So while we can follow TDD it won’t be as effective if our tests are of poor quality.

Finally, from my experience, I have found following a TDD approach to my development activities has given me far more confidence in my code for two reasons. The first is the likelihood my code will work as expected once released. The second is that I can go in and make changes as needed without the concern that I’m touching something fragile and once a change is made the whole system might come crashing down around me. I’d recommend if you don’t use TDD that there are plenty of really good resources out there for you to check out, two I’d recommend are Pluralsight, there are a lot of useful courses available through them and Uncle Bob’s Clean Code book, Chapter 9 is all about unit tests.

Command-Query Separation

I’ve been dropping some short but, hopefully, meaningful posts about subjects within software development like Names and Don’t Repeat Yourself. These appear to be getting some interest so I’m going to look at putting together more short to the point titbits, or tidbits, of recommended software development best practices.

So this week’s titbit is the aim of incorporating the Command-Query Separation principle into our code.

The main goal of Command-Query is that we should aim to write our code in such a way that methods either do something or give us something but that they do NOT do both.

  • Commands: Do something; change the state of the system.
  • Queries: Give us something; give us back a result but do not change the state of the system.

This concept was coined by Bertrand Meyer the author of Object-Oriented Software Construction in the late 1980s and as mentioned above is quite straightforward to understand but not as easy to implement all the time.

Martin Fowler wrote an article in 2005 that provides a good example of where this is the case. If you are using a 3rd party data structure which does not follow this rule and you perform a query on that data structure the state of the system may be changed as a result, thereby breaking the principle. He also continues with this train of thought, we should aim to follow these best practices where we can and when we can but that is not always the case.

My view here is we can either review our implementation, and look to improve it if it’s a break we are causing, or we can accept that these things happen but try to work around the issue so we ensure our code is as clean and expressive as we can make it.

A quote from one of my university lecturers was “Write your code like the person taking it on after you are an axe-wielding murder who knows where you live.”, a bit dramatic but the point is there; we should aim to make our code clean and clear and this kind of decoupling is certainly something we should all be considering.

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.


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


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.


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 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.


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.


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


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

  // 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.