Showing posts with label thoughts. Show all posts
Showing posts with label thoughts. Show all posts

Sunday, 6 September 2015

Practice Test Driven Development with C# Exercises on Exercism.io

I was recently introduced to Exercism.io which is a place where you can download a number of C# exercises to work on. Exercism.io not only supports C# but also other programming languages. Each exercise comes with a pre-written suite of unit tests and it is your task to implement the required functionality in order to make the unit tests pass.

The exercises are a good way to get familiar with Test Driven Development (TDD) without having to write the tests. You can still semi-follow the prescribed red-green-refactor approach, where you initially have a test that fails, you then write an implementation to make the test pass and then you refactor your implementation until you're happy with it.

The Exercism.io website provides a useful command line interface tool which you use to fetch exercises and then also submit your solutions. Once a solution is submitted, it is made available on Exercism.io for others to "nitpick". This is a great feature where others who have done the same exercise can view your solution and suggest improvements. Although I've found the C# community on Exercism.io to be fairly quiet (with only a few people nitpicking), I can see this being a very useful feature once more people start to use the site.

If you've also heard of Project Euler (which I blogged about here), then yes, Exercism.io is similar in principle, but there are differences which you'll find quickly after trying both sites. I've tried a few exercises in the C# section of Exercism.io - they are fun and a good to practice your C#/.NET framework knowledge. Highly recommend this site to anyone who enjoys small programming exercises in their spare time and anyone who is interested in trying TDD. You can get started here.

Saturday, 22 November 2014

Short-circuit Boolean Evaluation

A useful but often not thought about feature is that many programming languages, including C#, support short-circuit evaluation of Boolean expressions. For example, in the following logical AND condition:

if (OperandOne && OperandTwo) 
{    
}

OperandTwo is only evaluated if OperandOne equals the Boolean value of true. If OperandOne's value is false, then the entire condition evaluates to false regardless of the value of any other operand in the condition (basic boolean algebra). Hence, there is no reason to continue evaluating the subsequent operands. This functionality is known as short-circuiting. You can confirm this language feature in C# with some basic code:

void Main()
{
    if (MethodOne() && MethodTwo())
    {
    }
}

bool MethodOne()
{
    Console.WriteLine("MethodOne: I got evaluated!");
    return false;
}

bool MethodTwo()
{
    Console.WriteLine("MethodTwo: I got evaluated!");
    return true;
}

After executing the code above, you'll see that the Console.WriteLine call in MethodOne only gets called. Short-circuit evaluation also works for the logical OR operator. Let's change the condition in the above code snippet to look like:

if (MethodOne() || MethodTwo())
{
}

If you now execute the code, you'll see that both of the Console.WriteLine calls in MethodOne and MethodTwo get called. However, if you now change MethodOne to return true and re-execute, you'll see that C#'s short-circuit evaluation kicks-in and only the Console.WriteLine in MethodOne gets executed.

Short-circuit evaluation gives you, as the programmer, a neater way to express your code. For example, without short-circuit evaluation, you wouldn't be able to construct conditions such as:

if (person != null && person.Age > minimumAge)
{
}

In this condition, a check is first made to ensure the person object isn't null before we go ahead and try to access the Age property on the object. If the person object is null, then the short-circuiting kicks-in and prevents the incorrect access of the Age property (which would result in a NullReferenceException to be thrown).

A lesser known nuance of C# is that short-circuit evaluation can be bypassed as a side effect of using the bitwise operators & and | without losing the semantics of the logical operation. For example, if we reuse our code snippet from earlier and make a minor adjustment to the condition to use the bitwise AND operator, we'll have:

void Main()
{
    if (MethodOne() & MethodTwo())
    {
    }
}

bool MethodOne()
{
    Console.WriteLine("MethodOne: I got evaluated!");
    return false;
}

bool MethodTwo()
{
    Console.WriteLine("MethodTwo: I got evaluated!");
    return true;
}

After executing the snippet above, you'll now see that both the Console.WriteLine in each of MethodOne and MethodTwo get called despite MethodOne (the first operand) returning false. Using a single & over && does not affect the semantics of the logical AND operator - so the code within the braces of the if-condition would still not get executed in this case (as the entire expression still evaluates to false). However, the key thing to note is that all operands are evaluated when bypassing short-circuit evaluation. Similar to the single & operator, short-circuit evaluation is also bypassed when using a single | (bitwise OR) without losing the semantics of OR.

It is generally advised not to bypass short-circuit evaluation but I find that it is important to be aware of it to catch bugs. In the past, I have noticed on several occasions that subtle bugs were introduced where a developer has used a single & and one of the operands in the expression had a side effect (e.g. a method that performs an action). Perhaps they came from a non-short-circuit-featured language where the single character versions of && and || are used to express logical AND and OR?. Take the following code snippet as an example:

if (person.HasChanges & _repository.UpdatePerson(person))
{
    ...
}

In this case, the UpdatePerson method will always be called, even when the person object states that it has no changes. This is a subtle bug which can easily be missed. Nevertheless, it is fixed by using the && operator to make use of short-circuit evaluation!

Sunday, 10 August 2014

C# Static Code Analysis with NDepend

I was fortunate enough to recently obtain a Pro license for NDepend. If you've never heard of NDepend, it is a powerful .NET code analysis tool which provides useful information to support you in writing better code. As I work on a large codebase, my initial worry was that NDepend may slow down my user experience with Visual Studio. However, after using it for one month, I have not come across a single moment in which NDepend slowed my IDE experience.

I'll quickly admit that I have no extensive experience of using code analysis tools, therefore I can't comment on how NDepend compares to other tools in the market - but I can comment on the features that I've found very useful. A quick glance on the documentation section of the NDepend website shows the powerful feature set that the tool supports. Below I briefly go through some of the features that I've found useful to date. I still feel that I've barely scratched the surface of some of the features that NDepend supports (particularly CQLinq), so the hope is to come back and update this post as and when I find something else I like.

Visual Studio Support and Integration - NDepend supports all the major versions of Visual Studio (2008, 2010, 2012 and 2013). I installed NDepend (the Pro license) on Visual Studio 2010 Professional Edition and have had no issues since installation. I have also installed a trial version of NDepend on the more later Visual Studio 2013 and found that it works just as good. The installation process was quick and straight forward. I particularly like the non intrusive nature of the tool - after installation, you get an "NDepend" menu option in Visual Studio. From this menu you can run an analysis on your projects. There is also a small circle icon which appears in the bottom right corner of Visual Studio - if you hover your mouse over it you'll get quick access to certain options (like running an analysis or viewing the dashboard) and also information on the number of NDepend code rules violated (more on Code Queries and Rules below).

NDepend Dashboard - Once an NDepend analysis completes, you get the option to view the NDepend Dashboard. The dashboard itself opens within Visual Studio as a new tab and provides a comprehensive array of information. Some of the information you get is:

- Lines of code (split by the number of lines you've written and the number of lines not written by you)
- Method complexity information
- Quantity information on assemblies, namespaces, methods, fields, source files and lines of comments
- Code coverage by tests
- Third party usage
- Information on violated code rules

Note that NDepend also is able to create a report in HTML which provides all this information and more. I imagine that saving "snapshots" of these reports over time would really help in assessing how your codebase is growing in terms of quality over time.

Code Rules and Queries - Perhaps one of the main features which makes NDepend so powerful is CQLinq. CQLinq stands for Code Query LINQ which allows you to query your codebase using LINQ-based queries. NDepend comes with a large number of predefined queries which give you useful information out of the box. Using the "Queries and Rules Explorer" panel you can see the CQLinq code for each query and also define your own query. You can think of CQLinq as a way to very easily reflect on your codebase using simple LINQ-based syntax that you'll already be familiar with. CQLinq provides a very useful mechanism for you to extend NDepend based on the information you want to extract from your code base. It also opens the opportunity for you to share your CQLinq queries with other NDepend users. You can find out more about CQLinq here.

Additional Visual Studio Features - In addition to its core features, NDepend provides a number of extra useful features like code diffing, dependency analysis, visualisation of code metrics and richer code search features. From what I understand, NDepend search is essentially a user interface over CQLinq.

As mentioned above, I'm a fairly new NDepend user. I find it an intuitive tool to use and quickly found myself benefitting from the information the tool provides. I'm particularly now interested in trying out NDepend on a greenfield project and seeing how it affects and shapes the day-to-day development of a new codebase. The features mentioned above are a very small subset of NDepends full feature set. If you're interested in trying out and knowing more about the tool - you can download it from here and read about all the supported features here. I also encourage you to go through the very useful documentation part of the site.

Saturday, 19 July 2014

Empty Collections

I was reading one of my favourite Java programming books this morning and came across a simple coding pattern that I've been practicing in C# since I first read this book. I feel it's a useful thing to share here. For those of you that are interested, the book is "Effective Java" by Joshua Bloch. It contains a series of bite sized chunks of tips/recommendations that Java developers can use. Although the book focuses on the Java programming language, I feel there are lots of things it discusses that are transferrable to any programming language. One of these tips is the topic of this post.

Joshua mentions that it's better to return empty collections rather than null when writing methods. The reason being that any code calling your method then doesn't need to explicitly handle a special null case. Returning an empty collection makes the null check redundant and results in much cleaner method calling code. In C#, the System.Linq.Enumerable class has a useful generic method called Empty. When called with a type parameter, this method returns an empty instance of IEnumerable<T> (where T is your type parameter).

An example use:
public class House
{
    public IEnumerable<Person> CurrentOccupants { get; set; }
        
    public House()
    {
        CurrentOccupants = Enumerable.Empty<Person>();
    }
}
I also find that this method of instantiating (or returning) a collection states my intent more clearly than something like:
CurrentOccupants = new List<Person();
The MSDN documentation for Enumerable.Empty states that it caches the returned empty sequence of type TResult - so using this consistently for the same types can give (probably negligible) performance or memory usage advantages.

This pattern also reduces the chances of null reference errors from being raised in calling code. As mentioned above, the calling code then doesn't need to go through the usual boiler-plate null check code on the returned collection. Naturally, this leads to cleaner code as the calling code can process the collection the same way if it has items or doesn't have items within it.

Friday, 9 November 2012

Initial thoughts on NoSQL with MongoDB

I have heard about the NoSQL movement for a while now but only recently started to properly look into a NoSQL technology. A few weeks ago I found out that 10gen (the team behind the popular NoSQL database called MongoDB) are starting a free "MongoDB for developers" course. The course runs weekly, with each week containing a number of videos that you watch, take a quiz on and then submit homework for. So far it has been very useful despite some initial hiccups in administrating the course. We're now starting Week 3 and have already covered quite a lot about NoSQL in general and how MongoDB can be used in a CRUD sense.
 
Week 3 of the course dives deeper into schema design in MongoDB and compares this with schema design in the more familiar relational data model. The course also has a project that runs throughout - which is to create a simple blogging engine using MongoDB and Python. It seems like the future weekly homeworks are going to be geared towards extending the blogging engines' functionality. Although the course material is using Python to communicate with MongoDB, there are a number of driver libraries that you can download from the MongoDB website for other programming languages - such as C#. I haven't had a chance to play with the C# driver yet but plan on writing a blog post about my experience with it in the future.
 
My training at university and all of the work experience I have gained so far has been around working with relational database management systems. So it is quite exciting moving away from the relational mindset and thinking about a different way to persist application data. It is weirdly refreshing to work with JSON documents in collections than working with the tables and rows abstraction in relational databases.
 
One thing that the course instructors emphasise about MongoDB is that your schema design should be geared towards how your application will access your data. So unlike in a relational data model, where you typically normalise your model to the third normal form - in MongoDB your data model will reflect the access pattern your application will use to get or update the data. As MongoDB doesn't provide support for joining data, you typically model your data (or JSON documents) so that each document contains all of the necessary information your application will regularly need for a particular use case. This is interesting as I think there is an implicit assumption here that you'd only ever have one particular access pattern for your MongoDB database... for example what if I wanted to build another application that accesses the data for a purpose that is different from when the original MongoDB database was designed? I'm hoping the answer to this question is not along the lines of migrating/copying the data to a schema that's more appropriate for the new application!
 
At this stage of my exploration, another concern with MongoDB is that there doesn't seem to be a quick out-of-the-box method to generate a pretty looking report for the data stored in the collections. In the relational world, SQL with the table and rows abstraction lends itself nicely to generating reports that non-technical users can easily make sense of. With MondoDB, you can query your collections of JSON documents easily enough in the shell using mongo.exe and the find() method on a collection - but the resulting output is in JSON format which probably won't go down too well with a non-technical user. Having said this, there may still be solutions/explanations to these concerns that I haven't come across - so I'm definitely not letting them stop me from diving deeper into the NoSQL MongoDB world.

Thursday, 4 October 2012

The Pragmatic Programmer

When studying for my undergrad degree, one of my lecturers recommended the book The Pragmatic Programmer (by Andrew Hunt and David Thomas). The book is written by a couple of experienced Software Engineers and contains a wealth of useful knowledge for anyone who is considering a serious career in software development.

The topics covered range from general tips that the authors learnt from their experiences, some useful tools you should know about as a programmer, how to think when you're writing code, how to write testable code and much more. It's a mixed bag of eight chapters, with each chapter broken down into smaller digestable sections. It was the perfect companion to someone who commuted into university on the train.

I know this post isn't relevant to C# per se, but thought it may encourage you to get hold of the book and learn some useful practices that you can apply in your projects.