RSS
Facebook
Twitter

Sunday, October 19, 2014

4 programming books available online - for free

Software development books don’t come cheap and it’s fine. The author has spent countless hours and sleepless nights transferring his/her knowledge and should be compensated for it.
But some authors have decided to provide an online version of their book and in some cases even a free e-book you can download.
I found the book in the list below extremely useful and since I read them for free (legally free) I wanted to give something back in the form of a recommendation – so that both the author and and you might benefit from these good books.

 

Threading in C#

This is the only entry which is not a standalone book - It’s actually two chapters from C# in 4.0/5.0 in a nutshell book.
I’ve used (and still using) this book extensively both for learning new threading topics and as a reference. I found it to be easy to read and understand as well as extensive without being overwhelming.
It’s a must book for C# developers who need to write multi-threaded/task based/async code – which is about every C# developer out there.
Availability: Online, PDF

Introduction to Rx

IntroToRx_Cover
Although not the newest book on the subject this book is still relevant. This book guide you step by step on the path of using Reactive Extensions (Rx).
For only a few dollars (or less) you can purchase a kindle edition of this book.
Availability: Online

Dive into Python

cover-small
I’ve read this book when I’ve decided to learn IronPython a few years ago.
This book teaches by example - each chapter begins with a code example that shows an example of the chapter’s topic that is explained throughout  the chapter.
Availability: Online, PDF, Word and more.

Pro Git

pro-git@2x
If you never used a distributed source control before (you are using source control – right?) this is a good book to learn from.
It takes you step by step, not only explaining the various Git commands but also the concepts and overall picture of using a distributed system.
After reading a few chapters not only you’ll be able to set up Git and use it successfully but also gain a better understanding on why Git works this way and how to utilize it to benefit your project.
Availability: Online

That’s it for now - now go do some reading…

Thursday, October 16, 2014

Upcoming conferences

As 2014 ends and the new year begins I have a few speaking opportunities planned right around the corner:

 

NDC_london14_logo_boxed

When: 3rd December 2014

I’ve enjoyed speaking at NDC London last year and I’m glad I was given a chance to speak at that great conference again. I’ll be speaking about unit testing concurrent and asynchronous code – the session to end all (read: some) excuses not to unit test.

 

image[15]

When: 28th January 2015

I’ve been a long time speaker at the Agile Practitioners conference and this year I’m also a part of the organizing committee. I have a session planned “Designing with Tests”.

 

speaking

When: 18th-20th February 2015

I’m going to Canada to speak at ConFoo

I have two sessions planned – Who’s afraid of WinDbg?, and Unit testing patterns for concurrent code. This is my first time at ConFoo but I heard good things about this conference and I’m sure it would be fun to attend.

 

What a great way to start 2015 – three great conferences. If you happen to attend one (or more) of these conferences - drop by, say hello and let me know what you think about my talk.

Monday, October 13, 2014

Strongly typed localized strings in universal apps

Back in the old days when the need for localized string arose, I would add a new string and use AppResources to access the correct string in code.
In Windows Phone application (known today as Windows Phone Silverlight 8.0/8.1) I would do something like this:
public void SomeMethod()
{
    var localizedString1 = AppResources.MyFirstSring;
    var localizedString2 = AppResources.AnotherString;
}

In the new universal apps the story is a bit different:
  • Only strings are allowed in the resource files (which are .resw instead of .resx)
  • Using a directory for each supported language (i.e. Strings\en-US\)
  • Access to localized strings is string based
I can live with the first two (I actually prefer it that way) but I have huge problems with Stringly Typed API calls – it’s easy to get it wrong, and even worse a trivial rename can cause problems that would only show during application run.

Luckily a co-worker of mine has put together a T4 template that fixes this problem (thanks Noam):

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>

<# string str = this.Host.ResolvePath("strings\\en-us\\Resources.resw");
    System.Xml.Linq.XElement resXml = System.Xml.Linq.XElement.Load(str); // Read a data file here. "%aaa%/string/en-us/Resources.resw"
   IEnumerable<XElement> appElement = (from dataElements in resXml.Descendants("data") select dataElements); #>

using Windows.ApplicationModel.Resources;

namespace UniversalApp
{
    public class StringsResourceManager
    {
        private static readonly ResourceLoader _resourceLoader = new ResourceLoader();
        public StringsResourceManager()
        {
        }

<# foreach (var element in appElement) { #>  
        public static string <#= element.Attribute("name").Value.Replace(".","_")#>  
        {
            get
            {
                return _resourceLoader.GetString("<#= element.Attribute("name").Value#>");
            }
        } 
<# } #>
    }
}

Using the class created from this template I can get from this:
public void SomeMethod()
{
    var resourceLoader = new ResourceLoader();

    var string1 = resourceLoader.GetString("MyFirstSring");
    var string2 = resourceLoader.GetString("AnotherString");
}

To this:
public void SomeMethod() 
{ 
    var string1 = StringsResourceManager.MyFirstSring; 
    var string2 = StringsResourceManager.AnotherString; 
}


Happy coding…

Monday, September 29, 2014

What I hate about BDD

Disclaimer: this is not a TDD vs. BDD post – now that we’ve got that out of the way let’s discuss the thing I hate most about BDD…

I’ve recently started using BDD (again). My tests are still “unit tests” – they do not call a database nor any other external dependency, and since even when writing unit tests I aim to test functionality (mini-requirements) most of them didn’t change too much.
For the subject of this experiment I’ve chosen BDDfy which was a perfect fit for my needs.
Some BDD frameworks uses two “kinds” of files – text file(s) where the scenarios and stories are written (in plain text) and code file(s) that implement the functionality that correspond to steps in those scenarios.
BDDfy on the other hand uses code file which is also used to generate the specification – so less work for me.
By using BDDfy I can transform the following unit test:
[TestMethod]
public void RejectCall_UserRecieveCallAndRejectIt_SendReport()
{
    var fakeMessageEngine = A.Fake<IMessageEngine>();
    var phone = new Phone(fakeMessageEngine);
    var notificationService = new NotificationService(phone);

    var message = new NewCallMessage("otherUserId");
    fakeMessageEngine.OnMessageArrived += Raise.With(new MessageArrivedEventArgs(message)).Now;

    phone.AnswerCall(Answer.Reject);

    var result = notificationService.GetLastReport();

    Assert.AreEqual(ReportType.CallEnded, result.ReportType);
}

To something like this:

[TestClass]
public class NotificationBddTests
{
    IMessageEngine _fakeMessageEngine;
    Phone _phone;
    NotificationService _notificationService;

    public NotificationBddTests()
    {
        _fakeMessageEngine = A.Fake<IMessageEngine>();
        _phone = new Phone(_fakeMessageEngine);
        _notificationService = new NotificationService(_phone);
    }

    [TestMethod]
    public void RejectCall_UserRecieveCallAndRejectIt_SendReport()
    {
        new NotificationBddTests()
            .Given(s => s.RecievedCallFromUser())
            .When(s => s.CallRejected())
            .Then(s => s.EndCallReportAdded())
            .BDDfy();
    }

    private void RecievedCallFromUser()
    {
        var message = new NewCallMessage("otherUserId");
        _fakeMessageEngine.OnMessageArrived += Raise.With(new MessageArrivedEventArgs(message)).Now;
    }

    private void CallRejected()
    {
        _phone.AnswerCall(Answer.Reject);
    }

    private void EndCallReportAdded()
    {
        var result = _notificationService.GetLastReport();

        Assert.AreEqual(ReportType.CallEnded, result.ReportType);
    }
}

And it’s an improvement – the test is more readable and well organized.

But there’s a hidden “price” for writing this kind of tests – one that can cause brittle tests and stability issues in the near future – can you spot the problem?


It’s all about shared state

I have a confession to make: most BDD code samples on the internet cause me to cringe. They all have the same inherent flaw. It’s all about “how we test the real requirements” and “create living specification” but no one ever talks about the fact that the test above could become a huge maintainability issue!

The problem could be shown easily with the following example:

[TestClass]
public class ShoppingCartTests
{
    private readonly ShoppingCart _cart = new ShoppingCart()

    [TestMethod]
    public void EmptyCartTest()
    {
        new ShoppingCartTests()
            .Given(s => s.ShoppingCartIsEmpty())
            .Then(s => s.TotalPriceEquals(0))
            .BDDfy();
    }

    [TestMethod]
    public void AddItemTest()
    {
        var newProduct = new Product(id: "prd-1", price: 100
        new ShoppingCartTests()
            .Given(s => s.ShoppingCartIsEmpty())
            .When(s => s.AddProductToCart(newProduct))
            .Then(s => s.TotalPriceEquals(newProduct.Price))
            .BDDfy();
    }

    private void ShoppingCartIsEmpty() { }

    private void TotalPriceEquals(int expected)
    {
        Assert.AreEqual(expected, _cart.TotalPrice);
    }

    private void AddProductToCart(Product product)
    {
        _cart.Add(product);
    }
}

Do you see the field that is being used by all of the tests.

By using the same instance in all of the tests we accidently cause the test to pass (or fail) depending on the order in which they were run. Obviously it’s an easy fix (in this case), Unfortunately such a simple issue can become a huge problem, the more tests written the more initialization logic required and before you know it it’s the middle of the night and you’re using trying to figure out how could a test that used to work fails some of the times - for no apparent reason.

This is not a BDD problem – I can easily write (and written) the same code without the aid of a BDD framework. However it does seem as if all BDD framework push you towards this issue.


The Solution

Luckily it’s easy to avoid this issue completely – make sure that tests do not share the same state (I said it was easy).

I’ve created a new class called NotificationTestBuilder (because naming things is the hardest thing in programming) and shoved all of the test’s “state” inside it.

And now I can write the same BDD test using single state per test:

public class NotificationTestBuilder
{
    IMessageEngine _fakeMessageEngine;
    Phone _phone;
    NotificationService _notificationService;

    public NotificationTestBuilder()
    {
        _fakeMessageEngine = A.Fake<IMessageEngine>();
        _phone = new Phone(_fakeMessageEngine);
        _notificationService = new NotificationService(_phone);
    }

    public void RecievedCallFromUser()
    {
        var message = new NewCallMessage("otherUserId");
        _fakeMessageEngine.OnMessageArrived += Raise.With(new MessageArrivedEventArgs(message)).Now;
    }

    public void CallRejected()
    {
        _phone.AnswerCall(Answer.Reject);
    }

    public void EndCallReportAdded()
    {
        var result = _notificationService.GetLastReport();

        Assert.AreEqual(ReportType.CallEnded, result.ReportType);
    }
}

[TestClass]
public class NotificationBddTests
{
    [TestMethod]
    public void RejectCall_UserRecieveCallAndRejectIt_SendReport()
    {
        var builder = new NotificationTestBuilder();
        new NotificationBddTests()
            .Given(s => builder.RecievedCallFromUser())
            .When(s => builder.CallRejected())
            .Then(s => builder.EndCallReportAdded())
            .BDDfy();
    }
}

And if I needed to do some “cleaning” after the test has finished running – I can implement IDisposable and put the whole test inside a using block.

And so by creating the state in each test we make sure that they could not effect each other.


Happy coding…

Tuesday, September 09, 2014

Visual Studio 2014 CTP - first impressions

I’ve installed the latest VS2014 CTP3 on my aging I3 home machine – because why use a VM when I can always re-install windows.
And so far I’m impressed! this is a low end I3/4GB machine and it loaded fast and works without any noticeable performance issues – I might be mistaken but it seems the performance is so much better then previous versions.
I’ve stated by creating a new project and when I’ve tried to rename Class1 to the less generic MyClass I was surprised to see a new dialog opening up – it’s no Resharper but looks like VS refactoring is heading in the right direction:
Rename
 image
Also – preview changes – just in case you want to check what exactly a “trivial” rename has in store for you:
Rename2
Just to make sure I’ve checked the “Refactor” menu (what do you mean – what refactor menu???) and it has the same options we has in VS2013 but I did find two new options available – Quick fixes (whatever that is) and Organize Usings which I miss whenever I’m forced to use “plain vanilla” VS.
image
It’s not much but I can only speculate that with Roslyn inside we’ll see a many more Refactorings options (and inspections) real fast real soon - both by Microsoft and the “Community”.
After tinkering with the IDE for a while I was ready to try some cool C# 6 features.
I’ve added a Primary Constructor since I wanted to try the new Read-Only Properties feature when VS politely informed me that the feature is only available in “experimental” language version.
experimental
By the way – notice how much information I got just by hovering over the code – and it got to me as fast as my cursor moved.
After a quick trip to Google and back I found that in order to use the new C# 6 features all I need to do is update the project file (.csproj).
And so I’ve opened the project file using XML editor and added the required magic:
image
And the error went away –  and I got to compile this:
image
How cool is this – I have a Primary Constructor (after the class) and I can use the values passed to initialize fields and properties – read-only  properties!

So far it seems that the old(er) VS2013 on my machine was not affected and it’s still working just like before the installation – but I haven't done extensive development on this machine (because it’s slow) and so I won’t install it on my main machine (yet).

But so far so good…

Sunday, August 31, 2014

A few days ago a colleague of mine asked me to help with strange errors his C++ project kept throwing at him.
Since it was a C++ project we had more than 200 compilation errors but as the  C++ veterans that we are we’ve ignored most of them and scrolled up until we’ve found the patient zero of the issue – inside an header file that looked something like this:
class MyClassWP8
{
public:
    MyClassWP8();
    ~MyClassWP8();

    MyClassWP8& operator=(const MyClassWP8&) = delete;
    MyClassWP8(const MyClassWP8&) = delete;
    MyClassWP8(MyClassWP8&&) = delete;
};

Do you see the problem? – me neither.

If you’re not familiar with delete/default keyword (for a method), it’s a (relatively) new functionality added as part of C++ 11.
In C++11, defaulted and deleted functions give you explicit control over whether the special member functions are automatically generated. Deleted functions also give you simple language to prevent problematic type promotions from occurring in arguments to functions of all types—special member functions, as well as normal member functions and non-member functions—which would otherwise cause an unwanted function call.
From MSDN
Back in the days of VS2012 this functionality was not supported but since we were using VS2013 there was no apparent reason for it not to work.
We’ve verified that VS2013 support default/delete in desktop, WP8.1 and even Windows Phone Silverlght 8.1 applications. However when using the good old Windows Phone 8.0 application the code refused to compile.
After enabling verbose build  (Properties –> C/C++ –> General –> Suppress startup logo == No) I found the reason for the issue - while all of the projects used the newest C/C++ compiler
image

Windows Phone 8.0 projects used and older compiler version that do not support some of C++11 features including explicitly deleted functions.
image

this is both logical and annoying at the same time - I guess that’s one more reason to upgrade to WP8.1.

Happy coding…

Monday, August 25, 2014

Unit testing – you’re measuring it wrong

I’ve been having this problem ever since I’ve started teaching (and preaching) about SCRUM, clean code, unit testing and TDD and any other software development practice.
When implementing a change - how do you measure its success?
For that matter – how can you measure a developer productivity?
Faccia is watching by Our Hero, on Flickr
Creative Commons Creative Commons Attribution-Noncommercial-Share Alike 2.0 Generic License   by Our Hero

A few years ago I worked with a “brilliant” manager who tried to measure developer’s productivity by counting the number of bugs a developer fixed on a given day. Being my argumentative old self I’ve explained that no two bugs are created equal and besides we should aspire not to write these bugs in the first place.
My comment was not well received – I was branded a subversive element – he felt that I wanted to prevent him from assessing developer’s work (which I didn’t).
Over the years several attempts has been made to calculate developer’s productivity – with similar result such as counting lines of code:
“Measuring programming progress by lines of code is like measuring aircraft building progress by weight.”
- Bill Gates
And it only get’s trickier when faced with the need to measure unit testing efforts.

How to measure unit testing effectiveness

The problem is that it’s impossible to measure both how much time was saved and how many bugs were prevented. The only viable way is to have two developers write the same feature and compare the results – and I’m yet to find a company willing to throw money down the drain.
A few years ago I found a research (which I use all the time) that did something similar: two teams working at the same same projects, one using TDD and one not were timed coding time and bug density was checked afterwards (guess who had less bugs). Unfortunately I cannot reproduce that experiment on every single company I work with in order to show that unit testing/TDD improved the way they are doing things.
There are two “matrices” that seem to interest managers when unit testing are concerned:
  1. Test count (i.e. how many tests we have)
  2. Test coverage (i.e. what percentage of the code was tested)
Both are inherently flawed.
Test count does not tell me anything about the project’s state and it’s impossible to provide a number of tests per feature developed - how many tests are “enough”? 10, 100, 1000 or maybe a million?
As for code coverage it’s a tool, a very effective tool that helps me daily to find code I need to test and help me understand how healthy my unit testing suite is – to put it in the words of one of a former boss of mine:
What do you mean 20% code coverage? we had 75% three months ago…
I know that I need an excellent reason to have less then 50% code coverage for a component, but how much coverage is enough coverage? 80%, 95% or 100%?
And just like any other tool code coverage can be gamed and easily abused to show good results for very bad code and tests.

Both code coverage and test count are good at showing quantity not quality and can be used to measure progress (to some extent- we had 100 tests a week ago and 50% coverage and now we have 1000 tests and 85% coverage), and both should be handled with care.

Why do you want to know?

There’s always a reason behind the need to measure or predict success. Usually when asked about measuring unit tests it’s due to a need to estimate future effort (which we still don’t know how to do). Someone up the food chain needs to fill reports, Gantt-charts  and approve expenses and needs to know what would be changed in the next X days/weeks/months. Perhaps the guy who wanted to start using unit tests needs to explain it to his superior or investors.
The problem is that any metric given would be inaccurate – I can show you two different projects with roughly the same amount of unit tests and 90% code coverage -one would be a success and one an utter and complete failure.
From time to time I’m forced to provide these guesstimates – since people need to be able to know where they heading and how much work is planned. When doing this I do my best to explain that these are educated guesses and the real benefits are more then these numbers but hard to predict and quantify – but no one ever listens…
It all comes back to the fact that I cannot show time saved nor bugs which were not created due to the change – the two factors that I find most interesting.

Success is measurable – in retrospective

I promise you one thing – after a short while the team would feel the change – for better or worse (usually for the better). Adding features would be a breeze, less bugs introduced with each new feature, shipping a working product would be easier and faster and developers tends to be more effective in their work (and usually happier)
Success by aloshbennett, on Flickr
Creative Commons Creative Commons Attribution 2.0 Generic License   by aloshbennett

I usually use nDepend to show the current code complexity and how various coding violations disappeared after a few tests were written an refactoring were made.
Looking back after a few weeks I can show real tangible improvement that I couldn’t possible predict with an accurate number.
And so I keep collecting these numbers with hope that someday when asked to predict or set measureable targets for developments I’ll have  a good answer…
Related Posts Plugin for WordPress, Blogger...