RSS
Facebook
Twitter

Friday, April 18, 2014

3 Windows Phone 8.1 features I’m already using

Two days ago I couldn’t take it anymore…
There was a new and shiny (dev) release for my Windows Phone and I just had to install it. With trembling hands and a heavy heart I’ve installed Preview for Developers on my HTC 8x and dived right into the dreaded “download –> install –> reboot”  cycle which took forever (or 30 min – hard to tell). After the final 8.1 installation finished “importing” my stuff I’ve tried turning my phone on and was genuinely amazed that it worked without a hitch.
I very was impressed – here I am using a non-Nokia phone and installing a preview release and it just worked!
After less then a day as a WP8.1 user I discovered three new capabilities/apps that I always wanted and found their way to the new OS – thank you Microsoft for listening.
I could talk about Cortana – but there have been  numerous blog posts and articles about that specific feature and besides it’s not (yet?) available for all countries (including the one I’m  writing this post from).
And so without further ado – here are my top three new things WP8.1:

Podcastpodcastss

WP8 had “Podcasts” but it was lacking. It was available via the Store  whole experience felt half baked. Due to arcane (legal?) reasons if you happen to live outside of a few selected counties (US) you couldn’t subscribe to and of the freely available podcasts. I had to download the podcasts using ITunes (?!) and sync the downloaded files using the Windows Phone App for Desktop.
Those days are over – now I have a shiny new app where all of my podcast reside.wp_ss_20140417_0006 wp_ss_20140417_0005wp_ss_20140417_0007
I can even pin my favorites podcast to the start screen – although no notification has been observed.

Notifications center

Another high profile feature on the new OS is known as the notification center. This is where all of your phone notification would appear in a form which start to become de-facto standard in mobile operating systems. wp_ss_20140417_0002
But this is not what I like most about it – check out the top part of the notification center:
image
That’s right! no more searching the setting just to turn my Bluetooth on or connect to a new Wi-Fi network. Doing these common tasks has just become much simpler and to top it there’s even a link to the “All Settings” page.

Calendar

I always felt that my phone calendar left much to be desired. It was impossible to use – month view was too top level and impossible to read while finding a meeting in the daily view was a real pain. These two view are still there (I guess we need to leave something for the 8.2 release) but the weekly view become so much better:
wp_ss_20140417_0004
It’s easy to see my weekly and daily meetings and I like the fact that the bottom left part was left for a “high level” monthly view.
It’s seemly to see my schedule as well as next week’s plans and to top it all they even added a weather forecast for the day (also in daily view) image.

Conclusion

There are many features and new apps bundled in the 8.1 release but for me the features above are the “instant win” features – I’ve been using them immediately after the install finished (+ reboot) and I liked what I saw.
Although the WP8.1 is supposed to be released sometimes soon - I know I’ll be keeping my “Dev” version until it happens because I’m already hooked.

Monday, April 07, 2014

Faking a long running asynchronous call

A few days ago I needed to make sure that a specific method would only get called once no matter how many times it’s caller is invoked. The simplified code looked something like this:
public async Task CallLongOperation()
{
    var result = await _client.LongWebCall();

    if (result.Failed)
    {
        // log failure and exit
    }    
}
I needed to make sure that the client was invoked just once no matter how many times CallLongOperation gets called – and to make things interesting the client’s method is asynchronous. Usually when I want to fake a long running call I use WaitHandle but in this case I had something even better…

During previous work I’ve used TaskCompletionSource in order to enable async calls where needed and it seemed only logical that the same method would work for my unit tests:
[TestMethod]
public void CallLongOperation_DuringOperationCallAgain_CalledOnlyOnce()
{
    var fakeClient = A.Fake<IClient>();

    var completionSource = new TaskCompletionSource<Result>();
    A.CallTo(() => fakeClient.LongWebCall()).Returns(completionSource.Task);

    var cut = new ClassUnderTest(fakeClient);
    
    cut.CallLongOperation();
    cut.CallLongOperation();

    completionSource.SetResult(new Result());
    A.CallTo(() => fakeClient.LongWebCall()).MustHaveHappened(Repeated.Exactly.Once);
}
Using the TaskCompletionSource (line 6) help me simulate an async call that won’t return until I call SetResult on it (line 14) and since I do not muse await on the actual call I write the whole test without creating any additional threads – creating a simple and deterministic unit test.
It amazed me on how simple it become testing methods that uses async/await - just because the code uses asynchronous calls does not mean that its unit tests need to be complicated or unpredictable.

Happy coding...

Sunday, March 02, 2014

Book review: Modern C++ Programming with Test-Driven Development

 

9781937785482

I’m always looking for ways to learn more about unit testing and TDD, I was elbow deep in a C++ project and I was looking to learn more about the tools & tricks of TDD in the unforgiving C++ world when this book was published and so I’ve started reading it.

This book does two things which I believed to be impossible (or really, really hard) - teach TDD without first explaining about unit testing by using C++.

Don’t be fooled by the title this is not a C++ book, but rather a very good book about TDD – the tooling, how to write a unit test, how to think the TDD way, legacy code – you name it.

After the first chapter which handles the logistic of compiling and setting the development environment (it’s still C++) the book really starts with a good example - easy to understand but not trivial and shows how using TDD and Google Testing framework you can create an emerging design.

The book covers everything I expected from a good unit testing book and more. Other than the obvious red-green-refactor, unit testing (and mocking) frameworks and how to structure a good unit test, there is much more - great topics which could save time and frustration to anyone who practice TDD: there’s a chapter about how to introduce TDD to your peers and supervisors (non techies), a chapter about the Mikado method, a chapter about unit testing and multi-threading and a chapter about creating a sustainable TDD suite – which anyone who failed implementing TDD can really appreciate.

I do not agree with everything in the book – for example I try to avoid using Setup/teardown methods because I’ve seen the horrors that they can become if not managed correctly and I have some thoughts about the ways that some of the tests are structured in the book – but I was relived to find out that this book while teaching on way to write unit tests does not advertise it as the only way and say so towards the last chapter.

I highly recommend this book to anyone who want to learn TDD or improve the way tests are written and designed - not just C++ developers.

 

So pick up this book and perhaps you can also “Code Better, Sleep Better” or at least understand TDD much better…

Tuesday, February 25, 2014

call_once for C#

One of the useful gems that made it into C++11 Standard Template Libraries (STD) is call_once, this nifty little method makes sure that specific code is called only once (duh) and it follows these 3 rules:
  • Exactly one execution of exactly one of the functions (passed as f to the invocations in the group) is performed. It is undefined which function will be selected for execution. The selected function runs in the same thread as
    thecall_once invocation it was passed to.
  • No invocation in the group returns before the abovementioned execution of the selected function is completed successfully, that is, doesn't exit via an exception.
  • If the selected function exits via exception, it is propagated to the caller. Another function is then selected and executed.
I needed something similar – I had a method that should only be called once (initialize) and I wanted to implement something similar to the call_once I’ve been using for my C++ development.
My first object was to try and make it as preferment as possible and so I’ve looked for a solution that does not involve locks:
public static class Call
{
    public static void Once(OnceFlag flag,  Action action)
    {
        if (flag.CheckIfNotCalledAndSet)
        {
            action.Invoke();            
        }
    }
}

since I was  trying to mimic the C++ code I wrote two objects Call (above) and OnceFlag which has all of the magic inside using Interlocked:

public class OnceFlag
{
    private const int NotCalled = 0;
    private const int Called = 1;
    private int _state = NotCalled;
    internal bool CheckIfCalledAndSet
    {
        get
        {
            var prev = Interlocked.Exchange(ref _state, Called);
            
            return prev == NotCalled;
        }
    }

    internal void Reset()
    {
        Interlocked.Exchange(ref _state, NotCalled);
    }
}

I’m using Interlocked as a thread-safe way to check & set the value making sure that only once it would return true – try it:

class Program
{
    static OnceFlag _flag = new OnceFlag();
    static void Main(string[] args)
    {
        var t1 = new Thread(() => DoOnce(1));
        var t2 = new Thread(() => DoOnce(2));
        var t3 = new Thread(() => DoOnce(3));
        var t4 = new Thread(() => DoOnce(4));

        t1.Start();
        t2.Start();
        t3.Start();
        t4.Start();

        t1.Join();
        t2.Join();
        t3.Join();
        t4.Join();
    }

    private static void DoOnce(int index)
    {
        Call.Once(_flag, () => Console.WriteLine("Callled (" + index + ")"));
    }
}

It’s very simple solution unfortunately not entirely correct –  the method used will only be called once, but requirements 2 & 3 were not implemented. Luckily for me I didn’t need to make sure that exception enable another call to pass through nor did I need to block other calls until the first call finishes.

But I wanted to try and write a proper implementation, unfortunately not as preferment due to the use of locks:

public static void Once(OnceFlagSimple flag, Action action)
{
    lock (flag)
    {        
        if (flag.CheckIfNotCalled)
        {
            action.Invoke();
    
            flag.Set();            
        }
    }
}

It works, and since I’m already using lock I can split the check and Set methods and use a bool value inside the flag instead of Interlocked.
  • All other threads are blocked due to lock until first finish running – check!
  • In case of exception other method can execute the once block – check!
  • If exited properly the block would only execute once – check!
But not very good performance due to locking on ever time the method gets called.

I’m still looking for a better way to implement call_once – it’s a good exercise in threading and I might find a cool new ways to use the classes under Threading or Task namespaces.

please let me know if you have a better implementation – that’s what the comments are for…

Wednesday, February 12, 2014

Navigating your design

Let’s pretend you’re visiting a foreign country and you want to get somewhere interesting, in order to do so you need to drive to this new place, one where you’ve never been before. And so you get into your (rented) car and all you’ve got left to do is to ask yourself - how to find the quickest/simplest/shortest way from where you are to your desired destination?

In my case Well that question depends on when you were asking me..

Navigation 101

My preferred tool of navigation used to be a simple map. I would find my destination on the map and my point of origin and try to decide the optimal route (or at least the one which is easier to remember) and write it down and be on my way.

But I don’t do that anymore…

multiple-gps-in-the-one-car1

Meet my little friend

 

Nowadays all I need to do is tell my trusty GPS (A.K.A phone) where I want to go and it would guide me step by step until I arrive at my destination.

Unlike the map of days of old – he knows when the road is blocked and can update my route if I made a wrong turn left (as I do from time to time). It even can suggest a route based on current traffic conditions – a trick which my map is yet to learn.

When using a GPS I find that I no longer care about the entire road but only how long do I have until the next turn.

All in all a good driving experience.

What does it have to do with Software development?

If you know me you know where I heading with this, if not – keep on reading.

 

It occurred to me last week while teaching Test Driven Development how similar is this practice to using a GPS – when using TDD I know where I want to get but instead of trying to plan the entire trip in advance, I take small incremental steps (turn right here, exit on the 2nd lane, drive through tunnel etc.) until I reach my destination.

When looking at my code design in that perspective I also understood something else –The practice of designing the implementation before writing code is very similar to planning the trip using a map – it would work for small (short) problems but as soon as the trip/problem becomes too big, too complicated or you run into any obstacles (feature change, design bugs, annoying manager) – the map needs to be consulted again, and hopefully while having a good idea where you are.

Another point where using my GPS and writing my code are similar is the fact that although I write my code iteratively I always keep my eyes on big picture – architecture, use case and so on. In a similar matter usually when using a GPS I’ll have a look at the proposed route from start to end – just to make sure that the GPS does not try to take me through “interesting” terrain (dirt roads - happened before) or somewhere I don’t (or can’t) go to - a particularly faulty GPS has tried to get rid of me by suggesting I pass the border – obviously I’ve stopped using that one.

 

When driving – which to you prefer? the old fashioned, fixed route of the map or the updating, simple directions the GPS provide?

 

I believe the same rule should apply to your code as well.

Thursday, January 23, 2014

One assert to rule them all

What’s wrong with Assert.X

Quick – what is the different between the following two lines:
Assert.IsTrue(result == expected);
Assert.AreEqual(expected, result);

Essentially both Asserts check for the same condition, in practice once fail we get very different error messages:

imageimage

While this example is easy to understand – when facing less than trivial test it can be downright impossible to understand the reason for the failure without a good error message (e.c. the 2nd message).

And that’s why unit testing courses have a slide or two about using the correct assert - because  using the more “general” IsTrue would give you a general error message which most of the time means that you power up your debugger just to find out what went wrong.
I cannot even start the count the times I caught this issue during code reviews or mentoring sessions. It seems such a time consuming activity – explaining yet again why a specific assert should be used instead of another.
Some developers don’t even know that many unit testing frameworks have specific assertion classes for string and collection and instead created complicated tests using the wrong assertion methods.

did you ever wrote the values in the assertion in the wrong order? – I know I did
For some reason someone decide a million years ago that the right order should be Assert.xyz(expected, result) – that is unless it’s InstanceOfType and you’re using MSTest.
It’s so unintuitive to think that the expectation comes before the actual value I’m checking that most developers gets it wrong the first time they write a test, gets a weird error message and understand the error of their ways while fixing a few tests.

The other day I’ve encountered another problem with the existing assert methods:
I did a small refactoring that caused a few of my tests to fail. The refactoring consisted of changing an Enumeration value to a class. Why on earth didn’t I get a compilation error – I got a runtime error instead due to the way Assert.AreEqual was defined.

Existing solutions

There are several approaches that have been tried before when dealing with asserts.
One approach is to use one of the fluent API libraries built on top of the existing unit testing framework API – in .NET there are many: NFluent, Should and good old Fluent Assertions to name a few.

A long time ago I read a blog post that suggested another solution:
I found this post after trying to understand unit tests that a co-worker wrote for his Silverlight code – he had a new assert type I never saw before Test.Assert which he used all over the place. At first I assumed that he made a mistake similar to using Assert.IsTrue but I quickly learnt that this one “assert” had magic inside that run the right check and output proper messages. After some digging I found a post by Jaffar Husain – the creator of this wonderful library explaining what he did.
I liked the way that his code harnessed to compiler and .NET to provide the right assertion error message without requiring any additional work from the user.
Unfortunately the code is no longer available, although you can probably find it somewhere on the internet – just look for “Silverlight unit testing framework”.

I know I wanted to create something similar of my own– for three main reasons:
  1. I couldn’t use the original code
  2. I wanted to have a different behavior for several asserts
  3. I was looking for a chance to use Expressions
And so I’ve created a new project on GitHub – AssertHelper

How to use AssertHelper

In order to use it all you have to do is specify your condition as a lambda using Expect.That method:
[Test]
public void CheckCompare()
{
    var myClass = new MyClass();

    var expected = 10;
    Expect.That(() => myClass.ReturnFive() == expected);
}

[Test]
public void CheckTrue()
{
    var myClass = new MyClass();

    
    Expect.That(() => myClass.ReturnFalse() == true);
}

[Test]
public void StringStartsWith() {
    var s1 = "1234567890";

    Expect.That(() => s1.StartsWith("456"));
}

[Test]
public void CollectionContains()
{
    var c1 = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

    Expect.That(() => c1.Contains(41));
}

I've even thrown in multiple assert support. Just put "&&" between your expectations/assertions to make sure all of them run even if some of them fail.

Getting AssertHelper

It’s out there either from GitHub or better yet use nuget and add a reference to your project.

It’s as simple as that…

Are there any limitations?

Yes there are, at the moment you can only use AssertHelper with NUnit.

I’m sure I didn’t cover all of the possible assertions out there, instead I choose the more commonly used:

ConditionNUnit

value == true

Assert.IsTrue

value == false

Assert.IsFalse

value == null

Assert.IsNull

value != null

Assert.IsNotNull

result == expected

Assert.AreEqual

result != expected

Assert.AreNotEqual

result is expectedType

Assert.IsInstanceOfType

aString.StartsWith(subString)

StringAssert.StartsWith

aString.EndsWith(subString)

StringAssert.EndsWith

aString.Contains(subString)

StringAssert.Contains

aCollection == expected

CollectionAssert.AreEqual

aCollection != expected

CollectionAssert.AreNotEqual

aCollection.Contains(value)

CollectionAssert.Contains

I do plan to add more support at the future, I’m still prioritizing future features - so let me know if some capability is really important for you.

I hope other developers would find this utility useful feel free to let me know what you think in the comments.

Monday, December 30, 2013

Test Drive your windows phone application

Today I presented the topic of unit testing (surprise, surprise) and Test Driven Development for windows pone applications.

I’d like to thank those who managed to arrive to the meeting despite the weather – it was a pleasure.

My talk was at the second part of the meeting - right after Eyal who showed how to use SignalR with windows phone and had a cool demo in which he controlled a game remotely using his phone (asteroids).

The code for my session is already on GitHub and here are the slides to go with it:

I’ve enjoyed preparing for this talk and I hope I’ll make the time in the future to continue working on the library I’ve created for this session.

But until then:

 

Happy coding…

Related Posts Plugin for WordPress, Blogger...