Blogging on the Train

I am looking to update my blog from the train on my daily commute. The main hurdle to overcome is the fact that the computer will not be connected to the internet during this time. And so the hunt for a decent offline blog editor begins.

The obvious place to start is Windows Live Writer.

I need to find out how to post source code using it. Apparently there is a plug in.

Watch this space.

Mono for Android: Just too expensive

There has been much talk in the office about mobile development.

I work with several devs that are building mobile apps in various different techs on different platforms.

For ages, I’ve been flying the Xamarin flag and fighting its corner. I’ve got the guys to come to Stuart Lodge’s MVVM Cross talks etc. As a development environment, I like it very much and I’m comfortable. I’m a c# WPF developer and so I like C# and Visual Studio.

But with the new pricing, I feel as though I’ve been let down.

$1000 is just way too high for the hobbiest app developer. Not to mention that that is per dev, so the guys that are in a small team of 3 or 4 – is their app going to make back $4000? Not any time soon that’s for sure.

And so they are going the Javascript, Typescript, Angular etc route under PhoneGap or whatever. And I don’t blame them.

Meanwhile, I’ve 11 months left of my annual subscription to build something in Mono for Android before the $1000 bill comes around again. And I feel I’ll have a hard time justifying it.

Common UI? Spotify on WP8 != Spotify on Android

Welcome Spotify!

Several friends of mine have the beautiful Nokia 920 running Windows Phone 8. It is a nice piece of hardware and it showcases WP8 very nicely.

One notable omission from the WP app store until now has been Spotify.

I’ve been a big supporter of Spotify ever since the beginning and happily pay my monthly premium subscription. Being able to store music offline on my phone is an absolute killer feature.

And so I am genuinely pleased that it has made it to the WP platform.

A Common UI

A hot topic of recent conversation amongst the boys has been HTML5 and the possibility of a common UI across multiple platforms. The conversation typically includes:

“You can write it once and it’ll run on desktops, iPads, mobiles…”

I have been developing in Mono for Android which allows for the code from the “viewmodel” (a logical representation of the view), interaction and business logic, service calls, etc to be shared.

Crucially though, the view, the UI, is not shared. And I believe this is a good strategy.

Users of Android expect their apps to be Android-like. Ditto for iDevices and Windows Phone.

Looking at screenshots of the new WP8 Spotify app, it is clear that the UI has been redesigned specifically for the Windows Phone. And rightly so.

So I applaud Spotify for making this (what I believe to be the) correct decision.

 

http://blogs.windows.com/windows_phone/b/windowsphone/archive/2013/02/08/spotify-arrives-on-windows-phone-8.aspx

Observable Cache

Source Code: https://gist.github.com/4115023

Given: An async operation that returns a value e.g web/service call or complex calculation
When: I request the value multiple times
Then: I only perform the operation once and cache the value

When: I haven’t requested the value
Then: Don’t perform the operation

When: I clear the cached value
Then: requesting the value again performs the async operation again

My current solution:


    public class Cache<T> : IDisposable
    {
        private readonly IConnectableObservable<T> _source;
        private IDisposable _connection;

        public Cache(IObservable<T> source)
        {
            _source = Observable.Create<T>(o => source.Subscribe(o))
                                .Replay(1, Scheduler.Immediate);
        }

        public IObservable<T> GetValue()
        {
            return Observable.Create<T>(o =>
                                         {
                                             var subscription = _source.Subscribe(o);
                                             _connection = _source.Connect();
                                             return subscription;
                                         });
        }

        public void Clear()
        {
            if (_connection != null)
            {
                _connection.Dispose();
                _connection = null;
            }
        }

        public void Dispose()
        {
            Clear();
        }
    }

Owned without Owned<> – Part 1

Our neverending quest to make our code neater and tidier continues.

“Given a screen in our application, when the screen closes, make sure everything has been disposed.”

Seems reasonable.

When using a DI container such as Autofac, it seems like a good idea to make the most of its powerful features. If we create the screen is its own child container / lifetime scope, then disposing of that child container disposes the screen and all other objects that it resolved (or that they resolved and so on).

This works very nicely and viewing the app under the memory profiler magnifying glass confirms that everything is being cleared away nicely.

Owned<T>

The syntax for creating the Child Container in AutoFac is by injecting the object you want wrapped (for example the screen) inside an Owned<T>. For more details, see the AutoFac Documentation or Nicholas Blumhardt’s “An Autofac Lifetime Primer”.

Whilst Owned is without doubt powerful and useful, it does has the slight drawback that the fact that an object is Owned can leak out of your component.

So for example, let’s say you are using a strategy pattern to create different Screens, like this:


// Our example Strategies look like this:
public interface IStrategy
{
     IScreen GetScreen();
}

// Here's a strategy that returns Red Screens
public class RedStrategy : IStrategy
{
    private Func<RedScreen> _redScreenFactory;

    // Inject our factory
    public RedStrategy(Func<RedScreen> redScreenFactory)
    {
        _redScreenFactory = redScreenFactory;
    }

    public IScreen GetScreen()
    {
        return _redScreenFactory();
    }
}

You can imagine having several different types of strategies returning, say, Blue and Green screens.

Anyway, let’s say that Red Screens create lots of children and are particularly prone to leaking memory. It would be nice to wrap them in an Owned.

However, what does our strategy return to the consumer?


public class RedStrategy : IStrategy
{
    // Our factory now creates Owned<RedScreen>
    private Func<Owned<RedScreen>> _redScreenFactory;

    // Inject our factory
    public RedStrategy(Func<Owned<RedScreen>> redScreenFactory)
    {
        _redScreenFactory = redScreenFactory;
    }

    public IScreen GetScreen()
    {
        var ownedRedScreen = _redScreenFactory();
        return // ...?
    }
}

If we return ownedRedScreen.Value then we are losing the reference to the child container. This means that we can’t dispose it and clean up all of the contents.

On the other hand, if we change the IStrategy interface to this:

Owned<IScreen> GetScreen()

…then we are forcing all IStrategy implementations to wrap their IScreens in a child container. We are also leaking the fact that they are Owned the consumer and it must now handle Owned<IScreen>.

(This is not to even mention that Owned<RedScreen> can’t be cast to Owned<IScreen> either).

I’ll explain a couple of solutions we came up with – one neat, and one very neat (imho of course :-))

Simple Sequences

It’s always interesting coming to a new codebase.

Often you find things that are done in a different way than perhaps you would code it. If you’re lucky, you might find things that are done in a better way than you might have seen before.

Take the opportunity to pass on what you know to your fellow developers and improve the code. And of course to learn everything they have to teach you too!

One simple example I encountered recently is the use of sequences.

Most developers know that arrays and lists (and others) can be treated as IEnumerable, which means that you can use foreach on them.

Often however, it’s easy to miss just how powerful and expressive sequences can be. There is also the often misunderstood yield key word.

What is this Sequence of which you speak?

A sequence can be thought of as taking one item at a time from a line of items. Like sweets from a tube.

You define what happens to each of the items as you take them. For example, you could eat them, or maybe use them to create different items in another sequence.

Let’s have a look at a simple example:

        // <summary>
        // Convert some Models into ViewModels
        // </summary>
        private IEnumerable<ViewModel> CreateViewModels(IEnumerable<Model> models)
        {
            // Create a list to put the new ViewModels in:
            var viewmodels = new List<ViewModel>();

            // Loop over ALL of the models
            foreach (var model in models)
            {
                // Create a new ViewModel:
                var viewModel = new ViewModel(model.Id, model.Name);

                // Add it to the list
                viewmodels.Add(viewModel);
            }

            // finally, return the list of ALL ViewModels
            return viewmodels;
        }

This code is simply taking some Models and converting them into ViewModels.

However, if we think of things as Sequences, then there isn’t any need for the List because we do this:


        // <summary>
        // Convert some Models into ViewModels
        // </summary>
        private IEnumerable<ViewModel> CreateViewModels(IEnumerable<Model> models)
        {
            return models.Select(m => new ViewModel(m.Id, m.Name));
        }

Now there are some very important and subtle differences in these two pieces of code and they’ll become more familiar as you get used to thinking about Sequences.

Lazy Evaluation

No ViewModels are created until the IEnumerable is evaluated. What evaluates a sequence then? Here are some examples of evaluating the sequence.


var viewModels = CreateViewModels(models);

// This pulls each viewModel, one at a time from the sequence.
foreach(var viewModel in viewModels)
{
   ...
}


var viewModels = CreateViewModels(models);

// This pulls each viewModel, one at a time and puts them into an array.
var viewModelsArray = viewModels.ToArray();


var viewModels = CreateViewModels(models);

// This pulls each viewModel, one at a time and puts them into a list.
var viewModelsArray = viewModels.ToList();


var viewModels = CreateViewModels(models);

// This pulls each viewModel, one at a time and counts them.
var viewModelsArray = viewModels.Count();

As you request the ViewModels, the Select statement in CreateViewModels pulls the models from the IEnumerable sequence.

Re-Evaluation

We’ve seen a few examples of calls that evaluate a sequence. Care must be taken to not re-evaluate the sequence repeatly when you don’t mean to.

For example:


var viewModels = CreateViewModels(models);

// The entire sequence must be evaluated to work out the count
var numberOfViewModels = viewModels.Count();

// .. and now we are evaluating the sequence from scratch again
foreach(var viewModel in viewModels)
{
    ...
}

Finally

Before this post gets too long, I’ll finish this post with a few examples of other simple keywords.

Have a think about how much work they are doing, and in particular when they are getting away with doing as little as possible.

var viewModels = CreateViewModels(models);

// This means it only takes one Model and only creates this one ViewModel
var justTheFirstViewModel = viewModels.First();
var viewModels = CreateViewModels(models);

// This means it ignores the first 3, then assigns the value of the fourth one.
// Note that it must fully evaluate (i.e. instantiate) all 4 ViewModels, then though it's ignoring the first 3.
var justTheFourthViewModel = viewModels.Skip(3).First();
var viewModels = CreateViewModels(models);

// Must read all the way through (i.e. instantiate all viewmodels in) the sequence to remember just the last one.
var justTheFourthViewModel = viewModels.Last();