Unit Testing – thoughts, reflections, randomness …

I don’t know why, but I’ve been fascinated with unit testing for years. Yes, you don’t have to point out how nerdy that is, I know, trust me.

I remember thinking that it’s a great idea to be able to check that my code works, all the time and I don’t have to manually do anything … manually …. gosh I really dislike this word. Well, not the word per se, but the activity of spending my precious time, repeatedly doing the same uncreative work.

Am I faster than a computer? No

Am I more accurate? No

Do I have nothing better to do? I do actually

So then, why should I do these activities?

Of course, there is more to it than this, it’s not pure laziness that drives this, it’s more to do with the desire to build quality code, have less bugs and be able to refactor without the fear that everything ends up in the black hole of never again working code. This name itself is scary …. BNAWC, something to do with claws …. yuck.

So, let’s see, what exactly are unit tests? How do we define them and what are their characteristics? I find this is a great place to start as it makes us question, no not life you nerd, but what we are actually doing as part of the coding activity.

A unit test is a piece of code which exercises a small part of our application’s code.

This is a very generic definition and doesn’t help anyone, so let’s move on to characteristics …

unit tests

  1. do not touch anything outside of the small piece of code they are testing
  2. can be run quickly, repeatedly, without setup and without any specific order
  3. are very simple and do not require complex setup, including much mocking
  4. do not have deep knowledge of the code they test.

Let’s look at all of these, one by one.

  1. Unit tests do not touch anything outside of the small piece of code they are testing.

Unit tests do not touch the file system, a database, an API or anything else like this.


All these things require a number of things and take some time. You will need a connection string, an API key, the API might even be down, there might be an issue with your database or the API is not even yours but it is a third party one. Does this mean that if this API is down, you cannot complete your tests?

If you have one test and it takes 2 seconds to run, that doesn’t sound so bad. What happens when you have a thousand though?

Are you happy to wait 600 seconds? That’s 10 minutes by the way.

This doesn’t sound so bad until you realize that the whole point of unit tests is that you run them all the time and you even hook them up to your CI/CD pipeline. Now one run takes an extra 10 minutes or more, which is really bad for everyone. You want quick feedback so people don’t even think about this extra test run.

2. can be run quickly, repeatedly, without setup and without any specific order

We’ve already seen why they need to run quickly and without setup.

What about running repeatedly?

This means they don’t affect the state of the system, by calling the code under test, you’re not setting global things, or anything else like that which influences other parts of the code and thus other tests. This means keep your code in check, so that no surprises happen when any piece of code is run.

You don’t want to hunt through your entire codebase trying to find out why the system is in a particular state. This leads into the next one:

3. unit tests are very simple and do not require complex setup, including much mocking

I have seen huge tests doing complex setup over hundreds of lines of code, I’ve seen mocking taken to extreme. Note I did not say don’t do mocking, I said don’t do much mocking, huge distinction.

SOLID encourages you to think about decoupling things, it encourages you to code against abstractions, not hard coded dependencies.

This is good advice, but you can also fall into the trap of doing too much decoupling.

Then, you write a test and you discover that you have to mock dependency A, then dependency B,which now needs dependency C and you keep going down the rabbit hole until you end up with a highly complex setup.

Once you’re done with the test, it looks like a three-headed hydra, big, ugly and scary. All these things make your tests very expensive to maintain, this is why I always advocate for simplicity. If your test looks too ugly, then look at the code because it is not as testable as you thought it was.

4. unit tests do not have deep knowledge of the code they test.

If your code knows too much about the code what happens is that when the code changes ( through refactoring for example ) then your tests will have to change too.

If the behaviour of the code does not change, neither should the tests

This is what makes unit testing worthwhile and cheap to maintain. This is what makes refactoring possible and safe, you have the harness to make sure you don’t break anything so go ahead and refactor to your heart’s content. If the tests are still green then everything is good.

It doesn’t matter how the code changes, your tests, once written have no reason to change, unless the behaviour of the code needs to change. In this case you change the tests, you now have failing tests, you fix the code until tests are green and move on.

If the tests have deep knowledge of the code, then you will have a maintenance nightmare on your hands, the tests will be too expensive to fix every time there is a change, will end up being commented out and the whole thing has been a giant waste of time. This is where it all goes.

What can we do to prevent this from happening?

My advice would be to aim for a functional coding style as much as possible. If a method that you want to test has a number of dependencies passed as parameters for example, then change it and pass data instead.

You can prepare the data first, then pass it to a method, this makes testing very easy because now you don’t have to worry about mocking anything, you just pass the data in whatever format you need.

This is the functional way. Everything a method needs is inside the method, no dependencies at all.

Random thoughts and questions

Is everything suitable for unit testing? I am going to say no.

What is suitable for unit testing? Everything which has a very well defined behaviour, things like an algorithm, formulas, code which changes something in a well defined way. Essentially anything which has business value and can be well defined, without any doubts.

What is not suitable for unit testing? Things which only make sense to developers, a DI setup, things which check how many times a method is called, stuff like that.

Imagine this scenario:

You go and talk to a business analyst ….

hey man, here is this test where I am checking that I am calling a method called RabbitIsJumpingUpAndDownOnOneFoot exactly twice and no less, no more. What do you think about the business value of this method?

If he looks at you like you are a martian with a green head then the answer is no, you should not have that thing. I cannot call it a unit test because it is not.

I have seen some pretty weird things categorized as unit tests, some examples:

When I call this controller I get this specific view back.

What exactly are you testing? That the MVC framework works? Leave that to the framework, that’s not a unit test you should be having.

When my application starts up I verify that all dependencies are injected correctly, with a unit test

nope. you want to check everything is hooked up correctly? Write a few integration tests which rely on the dependencies being correctly injected, then you know everything is set up correctly.

I am testing that this method is called once

what’s the value of this? what happens when the code changes and that method is not called anymore? how do you even know what that method does?

I am testing this code which depends on random values created by this random generator, so I am running this test one thousand times to see what happens when specific values are generated.

Why ? Take the randomness out of your method, generate the thing outside of it, pass the generated thing as a parameter, now you can test your method with specific values, without having to run it like crazy, hoping it will eventually hit the values you want.

I can probably continue like this for quite a while, but hopefully the idea is clear by now. A bit of thought when writing code makes our life a lot easier when it comes to maintaining or changing the code.

The biggest fallacy I’ve ever heard is that unit testing adds whatever percentage ( typically 30 % ) to the delivery time. Let me stop you right there and tell you that is completely wrong.

Why? Writing testable code is no different than writing non-testable code. It’s the same thing as far as delivery is concerned. Adding proper unit tests is very quick, no problem there.

We, as developers debug our code a lot. If we don’t have unit tests then we have to either write some separate console application or keep going through the UI to test and see what happens.

Going through the UI is very time consuming and let’s face it, no one ever manually tests every possible scenario in every little corner of their application. You’d be ecstatic if even the happy path is tested at all.

Automated unit tests ensure that they run quickly and they all run. You basically save time, because you can cut down a lot on your manual testing time ( for all developers and testers in the team ), while making sure you test a lot more than via the manual way. So, no, adding unit tests does not add anything to your delivery, it just makes you deliver better quality, a lot quicker IF you have decent unit tests. Big IF there …

Posted in Personal Views | Leave a comment

Having a Craftsman Mindset in Software Development


New article published in Dot Net Curry Magazine: https://dncmagazine.blob.core.windows.net/edition35/DNCMag-Issue35.pdf

Thank you,  Suprotim Agarwal, for your patience, this one took quite a bit of work!

Posted in Personal Views | Leave a comment

BDD, an in-depth look

This article was published in the DNC Magazine, issue 30, May-June 2017

The terms of the publication do not allow me to post on my own blog, so please read the magazine if you are interested. I have saved a local copy of the magazine here, should you need it : DNCMag-Issue30

As usual, any comments are welcome.



Posted in Code | Leave a comment

Can anyone become a professional software developer?

This subject fascinates me. Lately I’ve seen lots of ads for courses or people who claim they can teach you how to become a software developer / designer / front end developer, you name it. The conclusion seems to be that anyone can do it.

This is born from the huge demand for developers of all kinds, demand which increases every year. New companies are born all the time, new products built so yes the demand gets higher and higher.

There is also the realization that the engineers produced by universities are not taught what they need and can’t write any kind of useful code. They go on to companies who then have to train them like you would train someone who has never seen a programming language in their life. Maybe this is 100% true, maybe not, there are always people who are better and some who waste their time going through a few years of advanced learning. This is not the point I want to discuss.

What I want to discuss is if anyone can become a developer. Can we take someone off the streets ( not literally although it has been done that way as well!) and teach them how to code? Is this the answer to the huge demand of developers everyone faces?

Let’s delve into this a little. What does one need to become a developer? Well first you need to learn a programming language.  You can’t write anything unless you know a language, right?

Can anyone learn a programming language? I believe the answer to this question is yes. Anyone can learn the basic blocks, how to write a for loop, an if statement, how to add numbers etc. One could go on and write simple programs which do a few things, like implement an algorithm of some kind. Of course knowing a programming language properly means a lot more then a few basic things.

You could get dragged into learning how to manage memory properly which pushes you into learning how computers actually work. Maybe you get to the point where you understand what a high level programming language is and maybe you understand what binary is and how come that a computer can understand what you ask it to do and actually does it. Maybe you understand these things and maybe not. The point is, do you want to understand these things?

Maybe you write an algorithm and are suddenly interested to see if you can make it faster and more efficient. Do you have the inquisitive mind which simply needs to understand how something works, or are content to see that it works and you don’t really care how.

I believe that in order to be a successful software developer of some kind, you need to have the aptitude for it. Creating something in this world is about creating an abstract model, imagine it all work and then implement it. That’s why a lot of very experienced developers will tell you that before you write any code, first go ahead and draw it on paper or on a board, imagine it like that first and once you figure out everything, only then sit down and actually write any code.

If you come from a maths background, whether you know it or not, that’s a very good sign that you can be a developer. Why do I say this? Because maths is all about the thinking process, it’s about abstract thinking, it’s about modelling and going from one known thing to another. If you have all these things then that’s a good indication you can be a developer, although it is not 100% guaranteed. I have seen very smart people with amazing background fail miserably in this field, because of their attitude and because of their inability to learn once they had it in their minds they knew everything better than anyone else. This happens because development is an ongoing process, once you get into it, you keep learning and learning and learning.

Learning never stops.

That’s what makes it harder than other disciplines. Sometimes it leads to burnout because you wake up one day and realize there’s no way you can keep up and there’s no way to know everything. Maybe you wake up one day and realize that you just can’t be bothered anymore.

So far I’ve talked about development as in back end development, I bet i am going to be told that front end is different, you can be a designer or front end dev  without all this, right?  I have seen the ads, learn a little bit of HTML and you’ll be guaranteed a job. I beg you, don’t fall for those. Web design is hard as well, you not only need to learn several things (  big surprise there ) but now you have to deal with other things, like browser differences. How come this box looks one way in Chrome and completely different in IE, or it works in Firefox but doesn’t work in Opera. You need to know JavaScript and that is a challenge because of the nature of the language. It also pushes you into back end development where everything I said before applies because guess what … JavaScript is just another programming language. Yes it runs in the browser but it is still a language.

At this point you might wonder, hang on a minute, are you trying to push me away from trying to become a developer? The answer is not exactly no, I want you to know what you’re getting into. Yes the salaries in IT are great, but if you don’t enjoy the field, you’ll never be more than an average level developer and won’t get any joy out of it. I want you to understand what these things mean and make you sit down and think if this is for you. If it is, great then go ahead and try.

Take the Yams challenge first though. Yams is a game with 5 dice, with poker like combinations. You can search more info about it and learn every little detail. I encourage you to write a program which implements this game in whatever language you want. Keep the interface simple.

If you can build a working version of this and enjoy yourself in the process then by all means you will love being a developer. You are in a great position because there is a lot of information out there, for free, about anything. You still need to figure out what you need though and how to do it.

Have I done it myself? Yes, I have. I did it before starting on my current path. I was actually working as a care coordinator at the time. I remember using Visual Basic 6 and winforms and I wrote the game for my wife. I absolutely loved it and it pushed me towards software development. I can only wish it does the same for you. Take the challenge and find out.

If you need some ideas, you can always use something like Visual Studio Community edition, or you can use JavaScript or anything else you want.

It’s up to you but the point is the tools won’t cost you anything.

Oh and let me know how it goes, if you do take the challenge.

Good luck!

Posted in Personal Views | Leave a comment

Helping graduates become the developers we need

What I would like to address today is the disconnect between the academia world and the professional world. We know a disconnect exists, we can hear countless employers complaining how graduates lack basic skills, how their attitude sucks etc.

What we don’t hear is how we are supposed to solve this problem. You know what they say, first admit there is a problem, then try to address it, right? This is exactly the purpose of this article.

Employers have an expectation that someone who graduated or is close to graduation needs to have a certain set of skills for them to become useful. They must know how to code, know multiple technologies, have the right attitude, be willing to do whatever. Is that a fair expectation? Maybe, maybe not.

What are students taught in universities? Granted, it’s been more than 20 years since I’ve been in one, but I remember being bored out of my mind. This is because I was being taught things I was not interested in. Later on, I took some courses with Open University, because for some reason I wanted a degree in UK. It was just as boring as I remembered it, actually even more boring. I wanted to learn stuff related to programming and I just gave up when I saw that one of my courses that I had to take was about design and I had to design a chair. That was something I was not interested in and I didn’t want to waste my time working on something that didn’t have any value for me.

This is one of the first topics, are we teaching the students what they need to know? I won’t pretend to be able to answer this question, perhaps others who studied recently can answer that a lot better than I can.

Employers expect someone to have a basic level of literacy, be able to read, write, know some maths and have a good worth ethic, meaning coming to work on time etc. They want to see an interest in programming and what they’ve been doing and working on to prove this interest actually exists. Just a look at grades on various subjects is not going to tell them much.

Someone who comes with great grades should be able to prove their value quickly otherwise what is the point, correct?

For a software developer to be successful there are a number of things they need to know. Imagine a web developer: they need to know some back-end language. Many universities happily teach Java and they have been doing it for a long time. If the job is that of a web developer, knowing Java is not going to help you that much.

You need to know front end stuff, you need JavaScript, you need HTML, CSS.

Then, how about Ajax and then what about relational or no-sql databases?

How about another scripting language?

How about the latest and greatest Open Source stack?

Hang on a minute, but what about mobile, responsive websites, how about hybrid and native?

I can keep going like this for a while, trust me, the list of skills can be endless. So, is that a fair expectation for a graduate to know all that? No, of course not, even if they dedicate their entire university career to these skills, it will still not help much, because, of course, by the time they finish their studies, the development stack has changed. Right? Well, that is true up to a point. There are a number of things and technologies that have been around for a while and they are still in use and in demand.

I will make a few statements here, which are my opinion and need to be taken perhaps lightly. I think that yes, software students need to learn more than what they are being taught right now, assuming they are not already! They need to have an understanding of a back-end language, such as Java or Dot Net. I would argue in favor of Dot Net and I will get back to this later.

Then they need at least  a basic understanding of JavaScript and perhaps an understanding of one MVVM framework. Which one is a bit unimportant. The point is that once you understand the concept, it becomes a lot easier to learn whatever the flavor of the month is and this is exactly the point. MVVM is everywhere these days and the concept takes a total shift from traditional methods. i know first hand how difficult it can be, I remember what it took for me to wrap my head around how it works.

Next, an understanding of relational databases is extremely important, they’re not going away any time soon.

Once they know these things here comes the most important thing and this is exactly what I believe is missing : an understanding of how these things work together. You do not learn one thing in a big vacuum. Everything one learns needs to help create a bigger picture. Developing a professional application these days is not done with the use of any one technology. There are multiple technologies and they all need to play together nicely.

For example, you learn about relational databases and you learn about dot net. How do they work together is extremely important, how do I build an application which uses both, how do I build a data layer in that language and how do I make it work nicely with a relational database?

Yes, we hear every day how universities should teach concepts, not specific frameworks. Well that is not only incomplete ( you can’t teach a concept without writing some code in some language )  but also totally not useful. You go to work and they won’t ask you to show on a black board how a specific algorithm works, you’re going to be asked to build something. That particular something might use the algorithms you learnt, but that algorithm is only a small part of something much bigger.

Big disclaimer, this article has been in my drafts folder for two years. Yup, completely forgot about it, just uncovered it today, so hmm maybe the time has come to finish it.

Have any of my views changed? Maybe yes, maybe not, I am not 100% sure their is a need for a back end language anymore, but I would argue that learning one may not be a bad idea anyway.

Back to the drawing board, what do we need the software students to have?

I would say that having some Maths background is a huge help. I cannot stress enough how important this is. I am not talking here about learning algorithms by heart. If you do a lot of Maths, what you end up with is a very useful way of thinking, you develop abstract skills you can apply in many fields, software development included.

It is very important to be able to visualise a problem and build a mental approach on how you would solve it. This is all software development is, solving one issue after another, after all.

So what I would say to a student is to write code, as much as you can, build something that helps you and keep building things. Keep learning, read books, follow developers, see what they do, what they build and what interests them. Start looking for jobs before you finish your degree and have something to show already. All these things will help.

Also, realise you are just starting on a very long journey, pace yourself and be prepared to keep learning for as long as you are a developer. Trust me, this will never change.

Thank you and good luck!


Posted in Personal Views | Leave a comment

Building better ( hopefully! ) RESTful APIs

The idea for this article came while I was at work.

I was talking to an Api provider and he had some very strong ideas on how things should be done. I have built a few APIs myself and suffice to say that we did not think along the same lines.  Of course, I wish you good luck if you try to find two developers who agree on pretty much anything, but this really isn’t the point!

So let’s see what the discussion was about. I am a consumer of that API. It is a restful json api.

There were situations when I would fire GET calls with an id to load the details of some entity. The API would return data if there was any, but sometimes that id would not actually be associated with any data. So the solution was to respond with a 404. Of course such a response is valid but in my opinion it should be used in a different manner. We’ll get to that later though. So anything that would return a null object or an empty list would basically return a 404 status instead and myself, the consumer of the API, I am expected to code around this methodology.

Let’s analyse the implications of this. Any dot net client, such as HttpWebRequest or WebClient will throw an exception when encountering a 404 code. If you have to use a front end javascript client, you would have to trap the response with an error method. 404 is considered a big failure which normally means that there is no listener at that particular URI. Your whole request is incorrect and is dealt with as an exception. This of course complicates things a little bit for the consumers.

This is basically why I have an issue with such a method. I am a lazy person ( lazy in a good way ! )  and I like easy and simple things. This isn’t simple anymore because now we have a totally valid request, it just so happens there is no object on the Api side which corresponds to the id that was sent through. So I would lazily return a code 200 with either a null object or a an empty list, if the result is requires that.

This approach of course simplifies things on the client side, everything works, nothing throws an exception and I can nicely inform the client that there is no data for their request.

There is no harm done basically.  I was told in no uncertain terms, not only by the API provider, but by one of my own colleagues that this is the correct, standardized approach.

So let’s see, is this actually the right way to do it from a standards point of view?

From a logical point of view, I think my approach makes a lot more sense. It doesn’t mean that I am right, of course. So, let’s look at the standards.

I found a set of standards at jsonapi.org

If you have a look they say this :

A server MUST respond to a successful request to fetch an individual resource or resource collection with a 200 OK response.

A server MUST respond to a successful request to fetch a resource collection with an array of resource objects or an empty array ([]) as the response document’s primary data.

A bit lower we can see this :

A server MUST respond to a successful request to fetch an individual resource with a resource object ornull provided as the response document’s primary data.

null is only an appropriate response when the requested URL is one that might correspond to a single resource, but doesn’t currently.

There is more of course and if you keep reading you see that if you happen to request some linked data which should belong to a resource that doesn’t exist in that case it is fine to return a 404 and I completely agree with that.

What I’ve read so far seems to confirm that I was thinking the right way even before reading this spec. Does it make sense to me? Definitely. Does it make sense to anyone else? Well, that is for you, dear reader to let me know, if the subject kept you reading this far!

Let’s not stop here though, let’s look at the w3 spec

According to this spec 404 is defined as follows :

The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

I was totally on the right side here.

It simply does not feel right to return a 404 in such situations when nothing has gone wrong. Yes there could be business rules which state that no such call should ever be made, but there are plenty of valid situations when this can happen. Every time we allow a user to type something to find a booking for example and then use that to try and match it in our back-end. So, there are valid reasons for this to happen. Does it mean the API should blow up with a 404 response? In my opinion, no it shouldn’t.

Now that we’ve cleared this, let’s move on a little. I was reading the w3 spec and I suddenly realized i was doing something wrong myself.

201 Created –

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.

A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.

So when you create data, using a POST, you should return 201, not 200 like I was doing before. I was not following the spec myself!

I am wondering how many API developers actually do this. Please let me know in the comments if you are or not!

So armed with this knowledge, let’s have a look at a little bit of code and try  to build a better API. I am going to use VS 2015 and  Dot Net 4.5.2.  Don’t worry, the code is available on github for your perusing pleasure.

Let’s see what we’ve done in the code.

First, I created a standard Web App, then added MVC and WebApi to it. So far so good. I only want the Json formatter, so I went ahead and wrote a little bit of code in App_Start\WebApiConfig.cs to make sure this happens:


Next I created my WebApi controller and added enough code for the three scenarios I want to present:


As you can see, I have two Get methods, one which blows up with 404 and one which return a 200 Http code together with a null object.

Finally I have a Post which takes an object, simulates a creation method and adds an ID, then returns the whole thing.

Next, I added a little Angular app to show how you can use this API.

The structure of the app looks like this:


Let’s look at these JavaScript files in detail. First the app.js:


As you can see, nothing fancy, we simply create a basic angular app and nothing else.

Next, the dataFactory,js:


It’s just a standard data factory so we can abstract away all the calls to the API.

Finally, the appController,js:


This is where we call all the methods of the API. Look at these calls and their results one by one next.



as you can see, it worked nicely, I am getting a 200 HTTP code and my data object is null as expected. Very easy to check.



Now i have to have an error function, check the status and if status is 404 I can now conclude there was not data. Doesn’t look as nice as the other option, does it?

Finally the createEntity call:


Looks as expected, I am getting my ID back and the status is 201 Created. I like it, so I am going to keep doing this, unless proven wrong, of course.

I am hoping you found this article interesting and I would be very keen to hear your thoughts on the matter.

Posted in Code | Tagged , , , | Leave a comment

Bing, where is my Date Time filter?

There is no secret that I am a big Microsoft fan. I love what they do, the products they offer.

I love Windows 8.1, Windows 10, Office 365, OneDrive, my Lumia 930 phone, my Xbox etc . Yes, I am a Microsoft geek, in case you’re still wondering.

I want to use Microsoft’s products for everything. For example, Bing. Yes, I am not a fan of Google. They went from being a progressive company that pushed the limits of everything they touched, to becoming the old closed Microsoft. I don’t like Chrome and I don’t like  their search engine. I want to use Bing.

So what does any normal user do? He goes to bing.com, types a query and hits Enter. Oh look 2 million results. Ok let’s apply a filter, I only want to see the results from the past week, not those from 2013. Oh wait … where is the filter ???


Turns out, wait for it, there is no Date Time filter for us, mere mortals who happen to live outside US. Yes, you heard it right, you actually get extra filters if you are inside US.  I love you Microsoft but this time … it’s one of those face palm non-Kodak moments.

I am wracking my brains trying to understand why a search engine which wants to compete with the rest of them cannot offer such a basic feature. Nope, no luck so far, I can’t even begin to imagine an answer.

I first moaned about it a few months ago. I got a reply from Bing directing me to a feature request somewhere. Of course I would refuse such a thing, because this is something that should already be there. Several months and a new OS later, Bing still doesn’t have that option. Is it because of me not adding the user voice required? As much as I’d like to think I can make such a tremendous impact, I kind of doubt it!

Is it a big thing? Hell yeah … it’s a search engine … it’s like saying … we sell ice cream with tens of flavours all over the world but if you happen to live outside US we will only sell you the vanilla flavour… this is where I draw the line, DO NOT MESS WITH MY ICE CREAM!

Anyway, how did I get to ice cream from Bing? Mystery about as big as the lack of Date Time filters outside US!

Yes Microsoft, people use Bing outside US. or at least they are trying to, but you’re making it virtually impossible.

The big question remains. When are we going to get those filters and who do we have to kill ( or get in touch with …. long live the more peaceful solutions! ) to make it happen?

Posted in Personal Views | Tagged | Leave a comment

Xamarin – Rest Services PCL

Xamarin – Rest Services from a PCL

I see this on a daily basis especially on the Xamarin forums.

How do I use this service from

  • an iOS app?
  • an Android app?
  • a Windows app?

How do I write a PCL which I can then reuse on all platforms?

While I did present a solution to this issue in a previous article, that services part was only minor as the article was mainly about something else.

So here it is, an article dedicated to using Rest Services from a PCL.

Let’s start by creating the solution and the PCL project


next add a PCL which will target all the platforms you care about. I made mine cover them all, just in case.


Add the Microsoft HTTP Client Libraries Nuget package, this is the one which works from a PCL and for every platform we care about.


At this point we can start creating the service wrapper.

I am going to keep this very simple. We will demonstrate three calls :

a simple get with parameter, a json post with a model and a form post with the same model. This should cover the real life scenarios you need to implement a real app.

Finally, create an Android app and use the service wrapper to fire all the calls implemented.

Let’s have a look at the service wrapper interface:


As I said, it is very simple and only contains the three calls we want to show.

Now let’s have a look at its implementation:


While this implementation is very simple it does allow us to demonstrate the important scenarios we are likely to encounter in a real app. The get method is the simplest one, it passes some data in the Url and returns the response.

The next two calls build up their own content object. Both StringContent and FormUrlEncodedContent are built on top the abstract class HttpContent.

Please note how we’re telling the first call to set the Content-Type of the request to json.

The FormUrlEncodedContent class is a specialized implementation of HttpContent and sets its own Content-Type so you don’t have to worry about that one.

Now that we have the wrapper in place, it is time to use it from an app. So create a Android app, it will give you the default one where you click a button and it tells you how many times you clicked it. I simply modified this basic app a little bit and I am setting the button text to the response coming from the service.

Look inside the MainActivity.cs file:


As you can see I am calling each wrapper method in an async manner ( please note how I set the whole OnCreate method to be async so I can actually await every call. )

Every time I get a response I simply set the button text to that response. All you have to do is run the app and just watch the button text change. You don’t need to click at all.

This is the initial state of the app when no calls have run:


Wait a little bit and you should see the result of the first Get call:


Wait a bit more and here’s the json post call result:


Finally, after another very short delay we can see the result of the form post call:


These screen shots are from the android simulator. I happen to have an old Nexus 7 tablet, so I hooked it up to my computer and deployed the app to it, using Visual Studio. Here is the app running successfully on my Nexus 7 :


At this point I started to feel really bold, so I thought to myself …. hmm why not add a Windows phone app and run the same code there?

This would prove my point about the code truly being cross platform, plus there is one tiny little advantage in the form of me owning a Lumia 930 phone as well.

With this new purpose in mind, I added a Windows Phone 8.1 project, chucked a TextBlock on the first page ( MainPage.xaml ), copied over the code from the Android project, replaced the button text changes with the TextBlock changes, added in the references to the PCL libraries used by Android, ran the little beast and here’s the selfie to prove it :


Happy days, so now I have my beautiful PCL libraries running from both my Android Nexus 7 and Windows Lumia 930. I almost wish I had a real IPhone to add the iOS project as well, but unfortunately I don’t so I will leave this part up to someone who owns such a device.

Hopefully this will help you get over the initial hurdle of not knowing which client to use in order to work with a Rest api, or knowing which client to use but not how to actually use it.

Everything is built as a PCL, targeting Xamarin iOS, Android and Windows phone and it works the same way from every platform.

I have included the rest service as well. Currently it is deployed in my own Azure hosting environment, but this one it is not guaranteed to stay up forever. You have the service code so if mine happens to be down simply deploy it somewhere of your own choosing and update the ServiceWrapper class with the new service URL.

The full source code is available on GitHub

As usual, if you have any questions / comments then please let me know.

This article has been posted on LinkedIn as well

Posted in Code | Tagged , , , , , | 3 Comments

Questions to ask when looking for a job

This was article was posted on LinkedIn as well at this address

Yup, you read it right.

Let’s say you are looking for a job and have an interview. How would you expect it to work? You would sit down and wait for them to ask questions to which you reply trying to impress? Does it sound familiar?

If you interview like this, you’ve wasted a huge opportunity. These days people don’t stay in a job too long unless it’s good for them. What does it mean? You’ve got to learn, you’ve got to develop your skills and you’ve got to advance on your chosen career path. If these things don’t happen, why would anyone stay in a job?

So, can you assess that these important things are actually going to happen? Up to a point, of course. You can’t be 100% sure, but you can ask the right questions to find out if things work like that in the place that interviews you.

So, first things first, they don’t interview you, you interview them. That’s how it should work. You need to find out about certain things which are important to you. Don’t wait for them to ask you if you have any questions, that may never happen. No, turn the table around as quickly as you can and fire the questions. Try to get as much detail as you can as well.

Before the interview think what is important to you. Write those things down on paper, don’t write questions, write targets. Write what you want to find out. Then your questions will have a purpose and help you get the answers you need.

Obviously these things vary per person. If it was me interviewing, I’d like to find out if I am expected to do overtime without extra pay or without time off in lieu. So I would ask my questions like this :

How many hours a week do your developers work? Do they need to do overtime on a regular basis? Do you offer something in return for the overtime worked?

I’ve had various answers to these questions : our developers work extra time every day. It is expected and it’s part of the job. That’s a big no no for me so at this point I already know there’s no point to continue the interview. Nothing else matters if this basic thing is expected.

Another question that many forget to ask is actually very simple : what are the working hours? I’ve had surprises when I didn’t ask the question and I found out they were longer than expected. Longer hours means you need to ask for a higher salary compared to what you had in mind already. In UK, a normal schedule would be 9 – 17:30 with 1 hour lunch. That’s 7.5 hours / day so 37.5 hours per week. Any more than that and you need to ask for more, any less and it’s a benefit.

Ask how the company is structured so you get an idea of what you can realistically achieve.

Ask about your future colleagues, how long they’ve been there, if you are replacing someone who left and if yes, why did they leave?

Ask if they are flexible. No flexibility is also a big no no. Things happen and any decent employer will understand that. If they don’t, move on, it’s not worth spending your time there.

Ask about training, personal development. You need to know if you can expand your skills while working there. If there’s no chance of that, then why are you still sitting down in that interview?

I am a software developer so a number of other things matter to me. What do they build, how, what technologies do they use, are they open to the idea of researching new things to find out how they fit the company or products.

So basically drill down into whatever is important to you and do not take no for an answer. If they don’t like the fact that you ask questions or seem to think you care too much about yourself then do yourself a favor and move on. You do not want to work in a place where questioning things has a negative effect on you.

Of course there is another aspect to it. It matters a lot where you are in your career. If you  are a seasoned professional then these sort of questions will work. If you are just starting out and trying to build a career then someone needs to give you a chance. To that end you need to have the right attitude and the right attitude is to be open to the idea of learning and developing your skills. If this means unpaid overtime then so be it, as long as it helps you grow your career, but that cannot happen for ever. You need to balance your work and your personal life so for that to happen, first you need to have a personal life!

So be smart, if you are a recent graduate or don’t have experience yet, then you need to show enthusiasm for what you’re doing. Then your interviews change a little bit, now you need to find out how you can get better in your chosen career, so have your questions follow this direction. Interestingly for a long while I was just thinking to write “how you can grow your flame”. That’s the expression of one of my favorite influencers Liz Ryan who I follow and respect for how she does things and how she sees things in the HR world!

Anyway, back on track. An interview is like a game of chess. Don’t let your opponent drag you into asking a stupid list of questions, instead ask what you care about. You’re not a sheep, you’re not brainless, you are someone who values their time and do not want to waste it with companies who are not worth it. Start with this idea and don’t be afraid to leave if you don’t like what you hear. Once you made up your mind that you’re not a fit for that company, feel free to thank them for their time and leave. Don’t waste your time.

I tend to interview quite a lot and I got to the point where I can smell trouble very quickly. I took jobs before where my spider senses told me something is not quite right. For example I had a company bang on a lot about how important their culture is. How they are not flexible because it works for them. I let them drill me with questions like a good little sheep. Had I asked my own questions I would have known that the previous guy lasted a week and left because he didn’t like the contract he was offered. The job turned up to be horrendous and I could have avoided wasting my time by not going there at all. The morale of the story is this: ask the questions and listen to your gut feeling. If something doesn’t feel right, do not risk it and move on. I don’t know why but the gut always knows so listen to it!

We mentioned the contract. This is another important topic. You don’t need to see one during your interview, you can accept a job offer without seeing one, but do not hand in your notice before you see it. The contract may have things in it that you cannot realistically say yes to. If that happens you need to negotiate those things out of it. If that can’t be done then move on.

A lot of companies here in UK stipulate in their contracts that you cannot work for anyone else and everything you do create as a software developer belongs to them even if it is on your own time and computer. That’s fine for a number of people, but not for me. I am a person who works outside of my normal full time job and my view is that what I do with my own time is no one’s business. What I create is my own property as long as it’s done on my time and on my own computer. What I do while at work belongs to my employer. As long as that is clear and understood, I am happy and we can proceed.

I had explanations that we don’t want you to be tired, but that doesn’t really stand. I could be climbing mountains, or playing football and go back to work tired because of those activities. Bottom line, no employer can dictate what you do with your own time so be mindful of those that try.

The conclusion, you need to know what you want in order to find the right company for you. Don’t be afraid to let them see the real you, don’t try to hide who you are just to please someone so they offer you a job. You don;t want any job, you want the right job. If they don’t like who you really are, do you really think you will have a good time while at work?

I’ve seen so much bad advice for job seekers. Try to impress, don’t show who you are, don’t ask too much questions, don’t ask these questions, don’t do this don’t do that. Be a little sheep so you get the job.

My advice is to never do that. You and your employer must really understand each other from the beginning. If you’re not a match that’s fine. If you accept a bad job all that means is that you’re giving up on your chance to find the right employer because you just took the job with the bad one and you stop looking. Don’t waste your time.

Posted in Personal Views | Tagged , , | Leave a comment

PCL Rpg engine – part 1 – actors and gear

I can see people wonder …. why would you bother ? Don’t we have enough engines already? Well, yes, but how many have you written so far ? Have you tried writing one? It is really really fun to work on something like this. If you like RPG games that is!

This article was born due to Eric Lippert. I follow what he writes, because let’s face it, the guy knows what he’s talking about. A few days ago he started to write Wizards and Warriors, part one.

That was such an awesome subject that I had to contribute and I remembered I actually had written such an engine a while back. It was just for fun and because I saw a mobile game which will go unnamed simply because I forgot what it was called! The game was not very complicated, you had up to three guys on the left side of the screen, up to 3 on the right, they would fight each other, do damage and whichever had guys still standing up at the end was the winner. You could have weapons and armors, knights, mages etc. it was not very complicated, but it was fun.

Fancying myself a programmer and a massive RPG lover I started to think how hard would it be to code something like this? So, I thought to myself .. why not? I had time and I was just getting into mobile stuff, so I wanted everything to run on a mobile device so there you go, another decision was born : to come up with a pcl version I could then run through Xamarin Android and deploy to my Nexus 7 tablet.

The thought process behind all this was quite interesting and it makes for the bulk of this article, it is in fact the purpose of this article. The code is available on github so please have a look so you can follow up with what comes next.

The solution is made up of two projects. One is the engine itself built as a PCL library. The second is a Console app I used to test some of the functionality. There is no graphical interface, I wouldn’t even dare to build one up myself!

First things first, what were my requirements ?


  • I wanted to have the concept of two sides fighting each other with an unlimited and unequal number of combatants. So I could have 1 guy fighting 5 if I wanted.
  • Next, I wanted to have the concept of inventory slots, different one for everything such as chest, left hand, right hand etc. This would allow me to add cool stuff like armour and weapons and shields. You can’t have an RPG game without those things!
  • Next, I wanted the concept of loot, the guy you would kill would drop something, it could be like 300 gold, or a cool item.
  • Finally I wanted to be able to change the combat system, the way damage was dealt in an easy manner, should i ever want to.

Now it was time to code something and see how it starts to shape up.

First I needed something to represent the players. I didn’t have a clear image of what this would require so I decided to start simple and have a character name and some base stats. I was pretty confident I wanted all my characters and AI controlled monsters to inherit from this  base class so I can do some basic initialization for everything in one place.

So this was settled, the base class would be an abstract class and the first thing was to create and attach some basic stats. I decided to keep it simple, so I would have three stats to begin with Damage, Defense and HitPoints.

These stats were needed so I can build some items which meant something and changed something visible. I could have a chest piece with 20 defense and 30 hit points which meant the hit points pool of the character would get bigger with each item added. This is al nice and cool but it’s obvious I needed to recalculate the stats the moment a gear item was equipped. Let’s not forget that equipping an item could mean another item was unequipped and then the new one equipped so I had to recalculate the stats by adding in the base stats and then the stats of each item in each slot.

This is how the Gear abstract class was born. It has a list of GearSlot items. What’s a GearSlot you ask? A GearSlot knows what slot it belongs to and what item is in it. It also has the concept of equipping an item.  In order to equip an item in that slot, I needed to be sure that the item can be equipped in that slow. So an Item would need to include this information in its definition. This is all nice and dandy but what exactly is an Item ? Should it be another abstract class ? I decided not to make it a class because there was no functionality I needed to add to it. All I needed was the name, the slot it belongs to, plus the stats it has. Remember the three base stats? I needed values for each of those in the definition of each item. Now, hang on a sec, characters also have stats so clearly I needed something I can reuse everywhere, something without any functionality. Well, an interface matches this perfectly. I needed an IStats interface, very simple, like in the code below:


As you can see, nothing fancy there, just the basic stats I wanted.

Now that I had the stats, the IItem interface started to shape up:


We can have an interface extend another interface so that’s what I did here. This way duplication was avoided, the stats remained in their own interface which would then be used in other places.

So, now let’s see how this is used in the Gear class. This class is an abstract one, it actually has various methods which is why it can’t be an interface. The whole point for this class was to hold data on all the slots, all the gear a character has equipped and provide a way to equip an item in a specific slots. It also recalculates its final stats. This statement is important because this means one thing : remember how we said each character has a set of base stats they start with? Think about racial differences. Well, we cannot recalculate the stats without knowing the base stats so I decided to add a reference to the owner of the gear.

This owner is the one who tries to equip the gear item in a specific slot, which is fine, I can do that, but let’s not forget that each slot has a method to equip an item so all I needed really was to call that base method and then recalculate the stats. This is only done in the ActorBase class since this is where we know the base stats. All we talked about here indicates a certain design. We will have a constructor which takes the owner, this allows us to calculate the stats and then offers a way to equip an item. The code could look like this :


Why did I make the Slots list read-only ? Simply because that list is not meant to be changed once it’s initialized. Each character is supposed to have one slot of each type and they never change so to indicate this design intent I made the list read-only.

Up to this point we talked about slots, items, gear but not about the main ActorBase class. Let’s have a look and see what’s going on in there. Why the name ? Well actor seemed suitable and base because it’s meant to be an abstract class.

It will hold data on the stats among other things. Ok I said stats, but which stats ? We have base stats to start with, but the stats values are different based on the gear equipped in the gear slots. So clearly we need to keep not only the base stats, but also the current ones with the latest values. Every time an item is changed we will clear the current stats, start from the base ones and add the stats of each equipped items. Once we’re done that’s what we store in the current stats. This method also frees us up to add spell effects which modify these stats further if we want to.

Cool, with this settled, we moved on to Gear. Well this is easy, we’ll simply add an instance of the GearAbstract class and be done with it. I chose this design so I can inject whatever implementation I choose and for that I chose a factory pattern. If things need to change, only a change in the factory needs to happen and nothing else changes. I could have added the implementation through dependency injection in the constructor, but this meant you could potentially have actors with different gear implementations and I did not want that. It would become way too complicated for this exercise and more difficult to follow.

An interesting point here, you’ll notice that the stats are actually private set. Why would I do that? the answer is simple. I chose this way of doing things because I only want the stats to be calculated not set directly everywhere. if no item changes or no spell is cast, there is no reason to alter a stat be it a base one or a current one and we know what the difference is.

Another  interesting aspect here is that you will notice another EquipItem method. You could wonder why, since we already have that in other places. This was done so that I could call it on the main actor. The code would be actor.EquipItem instead of actor.gear.slot.EquipItem. It makes it a lot easier to work with. The implementation calls the sub method anyway, but that’s hidden from the programmer. It’s just a little thing to make our own life a bit easier instead of having to think where something should live and keep going through a number of class levels to get there.

Finally the RecalculateStats method. This is triggered every time an item is equipped.


We start from the base stats values and then keep adding stats for each item equipped. Very simple.

How do we alter the stats? Let’s take a look at the ActorStats class which is used in ActorBase. We can see it implements the IStats interface, which forces us to keep the same stats names and thus remain consistent across the system. The most important method here is AddCharacterStatValue which tells us which stat we want to change and by what value. The values could be negative, imagine a curse spell effect or a drain.

This method is the one used by items to update the current stats.


Ok, so at this point in time we have characters, we have gear, items and everything fits nicely into place. How could we test this ? Well, this is what the Test console app is for!


Now, we want to see how the stats change when stuff is equipped. So, we create a player, we create a few items with fancy names and some random stats, equip them and output the result to the console. I could have written some unit tests here and I probably will but for now this will do. As you can see the code is easy to read and in my eyes it makes sense and it feels natural. I don’t have to call anything else myself as everything is called automatically when it should and my stats reflect the correct values without me having to worry about recalculating them. Awesome stuff for a programmer. I don’t need to remember anything basically! This is no way means that I am lazy! Or does it?

This concludes part 1. In part 2 we will look at the combat system. See you then!

Posted in Code | Tagged , , , | Leave a comment