I’ve been learning C & Objective-C for the last month or so now and I’m really enjoying it.  There is set to be quite a bit of iOS development involved in my new job as a senior mobile developer.

I write unit tests… a lot.  I use unit tests the way the dynamic kids use REPLs.  I find them a great way to test and explore solutions as well as enforcing expectations on / driving out the design of your code.  I have found them invaluable as an aid to helping me understanding and test different aspects of the Objective-C language and Cocoa libraries.  I would strongly recommend this strategy to anyone learning to develop on this platform (or any platform for that matter).

How to get your first unit tests running in Xcode 4:

1, Create a new Project  ( File > New > New Project  / ⇧⌘N )

2,  Create a new Target ( File > New >  New Target )
2.1, Select ‘Cocoa Unit Testing Bundle’

3, Edit Scheme ( Product > Edit Scheme / ⌘< )
3.1, Select Test (left)
3.2, Press [+] to add your test target.
3.3, Select your test target that you created in step 2.

You will see this dialog for editing your Xcode project scheme.

4, You will now be able to execute your tests by pressing ( ⌘U )

NOTE: When writing tests with the default testing library (SenTestingKit) all unit-tests should start with the word test.

Example: Unit Test

- (void) testDefaults
{
  STAssertEqualObjects(person.forename, @"Not", nil);
  STAssertEqualObjects(person.surname, @"Set", nil);
  STAssertEqualObjects(person.age, [NSNumber numberWithInteger:0] , nil);
}

That should be enough to get you started writing unit tests to aid your understanding of Objective-C and the Cocoa libraries. You will need to link to your Application code when you wish to import and test the code you have written there.

I strongly recommend you check out the following resources if you are learning Objective-C, Cocoa &| iOS development:

Tekpub Introduction to iPhone Development - $25
Peepcode Objective-C for Rubyists - $12
iTunes-U Developing Apps for iOS by Paul Hegarty (Stanford University) videos | resources – Free

I aim to demonstrate how you can leverage the dyanmic power in C# to do some funky meta-programming.

In this example, I demonstrate how to extract information from a method call to a Dynamic Object.

First I created a class called MetaInfo which inherits System.Dynamic.DynamicObject. I then override TryInvokeMember which will be called when we make a call on our dynamic instance of MetaInfo.

Lets see this in action:

static void Main(string[] args)
{
    dynamic meta = new MetaInfo();

    var result = meta.Foo(name: "Steven", age: 24);
}

The result is as follows:

Below is our MetaInfo class which extracts the information from dynamic method invocations. The xml comments on TryInvokeMember are worth reading:

public class MetaInfo : DynamicObject
{
    ///
    /// Provides the implementation for operations that invoke a member.
    /// Classes derived from the  class
    /// can override this method to specify dynamic behavior for operations such as calling a method.
    ///
    /// <param name="binder" />Provides information about the dynamic operation.
    /// The binder.Name property provides the name of the member on which the dynamic operation is performed.
    /// For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of
    /// the class derived from the  class,
    /// binder.Name returns "SampleMethod". The binder.IgnoreCase property specifies whether the member name
    /// is case-sensitive.
    /// <param name="args" />The arguments that are passed to the object member during the invoke operation.
    /// For example, for the statement sampleObject.SampleMethod(100), where sampleObject is derived from
    /// the  class,  is equal to 100.
    /// <param name="result" />The result of the member invocation.
    ///
    /// true if the operation is successful; otherwise, false.
    /// If this method returns false, the run-time binder of the language determines the behavior.
    /// (In most cases, a language-specific run-time exception is thrown.)
    ///
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        var methodName = binder.Name;
        var argumentNames = binder.CallInfo.ArgumentNames.ToList();
        var argumentTypes = args.Select(a => a.GetType()).ToList();
        var argumentValues = args.ToList();

        result = new {
                          Method = methodName,
                          ArgumentNames = argumentNames,
                          ArgumentTypes = argumentTypes,
                          ArgumentValues = argumentValues
                      };
        return true;
    }
}

As you can see we are able to treat the call, its parameters names, types and values as data. We are free to do whatever we wish with it.

Why is this useful?

The killer use case is implementing a library API which treats the invocation information as something that will be interpreted, based on a predefined convention.

A data access library could very easily treat Continue reading »

In a earlier post of mine I introduced Google’s Protocol Buffers in .NET.

Version 2 beta has just been released (read more on Marc Gravell’s blog).

This has involved a core rewrite, and has been eagerly anticipated by those who follow the progress of this project.

From Marc’s Post – Whats New:

  • the ability to define models at runtime (also useful for working with types you don’t control)
  • the ability to have separate models for the same types
  • pre-generation to dll
  • runtime performance improvements
  • support for structs
  • support for immutable objects via surrogates the ability to run on mobile platforms (unity, wp7 – and perhaps moot for a while: MonoDroid, MonoTouch – but presumably Xamarin)
  • the ability to serialize object graphs preserving references
  • the ability to work with types not known in advance (same)
  • probably about 40 other things that slip my mind

v2 is a big release, the above list was admittedly non-exhaustive.

I recommend you check this stuff out for all the reasons I went into in my introductory post.

Most eyes on this project the better, protocol buffers are awesomely flexible and lightweight… Check out the protobuf-net code here.

Now… looking forward to finishing up work so I can get my teeth into the code.

When writing unit tests, you may find yourself in a situation where you need to set some value to a private field or property.

This is generally true for me when developing applications that leverage an Object Relational Mapper. When using NHibernate in particular I define my Id property with a private setter so that only NHibernate may set this field.

I read a great article a while back on the use of dynamic to simplify reflection operations specifically for accessing private fields. It struck me that this could be useful in some cases when it comes to testing.

So, say we create an instance of Role and we wish to change the value within the Id property.   To do so we need to access the private setter for the Id field.  This can be achieved like so:

Role Class:

public class Role
{
    public Role()
    {
        Permissions = new List<Permission>();
        Employees = new List<Employee>();
    }

    public virtual int Id { get; private set; }
    public virtual string Title { get; set; }
    public virtual IList<Employee> Employees { get; private set; }
    public virtual IList<Permission> Permissions { get; private set; }
}

Accessing Id Private Setter:

var role = new Role();
//Access Private Member to Set Id
dynamic roleExposed = new AccessPrivateWrapper(role);
roleExposed.Id = 1;

This will directly change the role variable.

The code for the Access Private Wrapper (which you can add to your tool belt):

///
/// A 10 minute wrapper to access private members, havn't tested in detail.
/// Use under your own risk - amazedsaint@gmail.com
///
public class AccessPrivateWrapper : DynamicObject
{
    ///
    /// The object we are going to wrap
    ///
    private object _wrapped;

    ///
    /// Specify the flags for accessing members
    ///
    private static BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance
                                        | BindingFlags.Static | BindingFlags.Public;

    ///
    /// Create a simple private wrapper
    ///
    public AccessPrivateWrapper(object o)
    {
        _wrapped = o;
    }

    ///
    /// Create an instance via the constructor matching the args
    ///
    public static dynamic FromType(Assembly asm, string type, params object[] args)
    {
        var allt = asm.GetTypes();
        var t = allt.First(item => item.Name == type);

        var types = from a in args
                    select a.GetType();

        //Gets the constructor matching the specified set of args
        var ctor = t.GetConstructor(flags, null, types.ToArray(), null);

        if (ctor != null)
        {
            var instance = ctor.Invoke(args);
            return new AccessPrivateWrapper(instance);
        }

        return null;
    }

    ///
    /// Try invoking a method
    ///
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        var types = from a in args
                    select a.GetType();

        var method = _wrapped.GetType().GetMethod
            (binder.Name, flags, null, types.ToArray(), null);

        if (method == null)
            return base.TryInvokeMember(binder, args, out result);
        else
        {
            result = method.Invoke(_wrapped, args);
            return true;
        }
    }

    ///
    /// Tries to get a property or field with the given name
    ///
    public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
    {
        //Try getting a property of that name
        var prop = _wrapped.GetType().GetProperty(binder.Name, flags);

        if (prop == null)
        {
            //Try getting a field of that name
            var fld = _wrapped.GetType().GetField(binder.Name, flags);
            if (fld != null)
            {
                result = fld.GetValue(_wrapped);
                return true;
            }
            else
                return base.TryGetMember(binder, out result);
        }
        else
        {
            result = prop.GetValue(_wrapped, null);
            return true;
        }
    }

    ///
    /// Tries to set a property or field with the given name
    ///
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        var prop = _wrapped.GetType().GetProperty(binder.Name, flags);
        if (prop == null)
        {
            var fld = _wrapped.GetType().GetField(binder.Name, flags);
            if (fld != null)
            {
                fld.SetValue(_wrapped, value);
                return true;
            }
            else
                return base.TrySetMember(binder, value);
        }
        else
        {
            prop.SetValue(_wrapped, value, null);
            return true;
        }
    }
}

Above AccessPrivateWrapper class courtesy of: Anoop Madhusudanan.

Aside: I have seen numerous other implementations, I will update post accordingly with the alt implementations in time.

I hope I don’t need to tell you that accessing private data in this or any similar fashion is not something you want to be doing.  I feel that in certain cases it is acceptable to do so within tests, never production code.  It is an alternative to making something public or mutable purely for testability when the theory dictates it should be private.

In both theory & practice you should control how the object is used through access modifiers. Making fields public or mutable simply for your unit tests is a code smell, if you don’t intent for it to be used in such a fashion within you production code.

The last thing I want in the above example, is any other part of the system modifying or setting the Id property, other than the NHibernate in coordination with the source of all truth, the database.

Happy Testing.

I have been using NHibernate on and off for a while now, especially when I have used a relation database for persistence. It is no secret to most who know me that I’m a massive fan of object databases, particularly db4o.

I like to think I write code which matches my ethos of “Enable rapid change with safety wheels”, where the safety wheels keep me (and the team) on the right track.

When it comes to data access, in particular using Fluent NHibernate, mapping your application domain to your relational database doesnt get much simpler. Fluent NHibernate comes with its own set of safety wheels in the form of a Persistence Specification Testing library.

I think more as a developer than a DBA so I usually start by modeling the domain as a meaningful object model, paying particular attention to the nouns and the verbs used by the domain expert.  I like to make user intent (verbs) a first class citizen so I explicitly define the actions user can take as both methods on the domain and at a higher level as Commands that have intent capturing names which encapsulate the required information needed to execute the intent. This results in a system that can handle growth in an evolutionary manner as defined by the client.

With regards to my persistence concerns, as I was saying, I aim to have a level of flexibility in place to allow me react and change quickly without incurring massive time penalties.  This is achieved through the following:

  • Repository Pattern – providing a layer of persistence ignorance between Business Logic and the data access strategy.
  • Database Generation – allowing rapid changes to be made to the database structure to quickly to adapt to changing needs of the application.
  • Unit & Integration Testing – Green is Good.
  • Persistence Specification- Ensuring our data access layer is behaving as we expect it to.

I am a firm believer in exposing the full power of your data access strategy / Object Relational Mapper (ORM) to the Read related concerns & logic within your application, there is little point in creating your own abstraction on top of the ORM in that regard as you will hide the power through your potentially leaky abstraction.

When it comes to Business Logic, relating to the Write concerns within your application, a general Repository interface (as defined below) helps spare the brains of you application from having to care about what is taking place at a lower level. It also gives a very simple view of the persistence concerns, providing a readability boost subsequently aiding clarity within your Business Logic. This is especially important as you should strive to make you Business Logic very readable where the intent is easy to obtain, ensuring it is not obscured by implementation concerns such as the ORM.

public interface IRepository<T> where T : class
{
     void SaveOrUpdate(T instance);
     T Find(Func<T, bool> predicate);
     IList<T> All(Func<T, bool> predicate);
}

Lets take a glance at what a simple Persistence Specification test looks like:

[Test]
public void CanCorrectlyMapEmployee()
{
     new PersistenceSpecification<Employee>(session)
           .CheckProperty(c => c.Id, 1)
           .CheckProperty(c => c.Forename, "Steven")
           .CheckProperty(c => c.Surname, "Holdsworth")
           .VerifyTheMappings();
}

What we are doing here is checking that our Employee Mapping correctly Saves and then loads the data for the properties specified in the .CheckProperty( {property}, {value} ) calls. The PersistenceSpecification class handles the instantiation, persistence and loading of the the Employee object based on the information we provide it with, Simples.

Going forward as we define more database mappings, modify existing mappings and relationships, we can start this process by modifying our tests to define what we are trying to achieve. The next step is to then modify our mappings, and our tests will act as the good safety wheels that they are by verifying that our changes are non-breaking changes.

This leads me to the Database Generation. I like to create Session Manager classes when working with NHibernate. These act as my abstraction for creating new instances of ISessionFactory.

I have a special Test Session Manager which also contains the power to generate then populate the database, as well as exposing some nice little configuration options such as refresh the database data each time we create a Session Factory.

CreateSessionFactory returns our Session Factory, configured how we specify. This is useful for being dynamic with your tests, in essence adjusting your training wheels to meet your needs at any given time.

I know I could have used the turnery within the Mappings call ( .Mappings(… ? … : … ) ) here.

public static ISessionFactory CreateSessionFactory()
{
    return UseAutoMapping
                ? Fluently.Configure()
                        .Database(SQLiteConfiguration.Standard.UsingFile(DbFile))
                        .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Employee>()))
                        .ExposeConfiguration(BuildSchema)
                        .BuildSessionFactory()
                : Fluently.Configure()
                        .Database(SQLiteConfiguration.Standard.UsingFile(DbFile))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<EmployeeMap>())
                        .ExposeConfiguration(BuildSchema)
                        .BuildSessionFactory();
}

By setting UseAutoMapping to true, I am able to focus on changes to my domain, without having to spend time updating my ‘explicit’ mappings. This helps me drive out new ideas and design, with my tests still being useful in providing feedback during this period of rapid change. I favor explicit mappings as I gain more fine grained control, but I do not wish the sacrifice the development time agility offered by the auto mapping conventions.

Build Schema (below) is called when we create the Session Factory. This gives us the chance to rebuild our database in a way which suits us based on the configuration property RefreshOnEachTest.

private static void BuildSchema(Configuration config)
{
    if (RefreshOnEachTest || !_schemaBuiltAtLeastOnce)
    {
        _schemaBuiltAtLeastOnce = true;

        // delete the existing db on each run
        if (File.Exists(DbFile))
            File.Delete(DbFile);

        // this NHibernate tool takes a configuration (with mapping info in)
        // and exports a database schema from it
        new SchemaExport(config)
            .Create(false, true);
    }
}

It is a cross between rapid prototyping and testability. When the code starts to take shape the database structure will become more stable and finely tuned, you should have little bother if the database and application evolve independently in that regard.

You may be thinking “What are these Google Protocol Buffers that you speak of?”

In essence it is the name given to the binary serialization format used by Google for much of their data communications a.k.a. simply protobuffs.

It has been designed to be:

  • Small in size – efficient data storage (far smaller than xml)
  • Cheap to process – both at the client and server platform independent – portable between different programming architectures extensible – to add new data to old messages.
  • Version-able - decoupling the data message from the field names.

Protocol buffers have many advantages over XML for serializing structured data. Protocol Buffers:

  • are simpler
  • are 3 to 10 times smaller
  • are 20 to 100 times faster
  • are less ambiguous
  • generate data access classes that are easier to use programmatically

- ref: protocol buffers documentation

The main advantage of protocol buffers over JSON is the ability to version your “schema” as JSON uses the names of the fields as the key to access the data, when this changes it generally requires change to be made by the consumers of the data.

Marc Gravell (and others) have put together an open source .NET library and some tools around using protobuffs.  This is known as protobuf-net and can be found on Google Code.

Lets look at some code, we have a class and we can annotate with some attributes to allow serialization into the protobuff binary format:

    [ProtoContract]
    public class Person
    {
        [ProtoMember(1)]
        public string Name { get; set; }

        [ProtoMember(2)]
        public int Id { get; set; }
    }

The key thing to note here is that we are assigning integer values to our properties / fields. This enables the serializer to reference the data fields based on a integer “key”, rather than the name of the property / field in question. When you think about it, this grants a great deal of flexibility as well as reducing the size of the data to be transfered.

From reading the protocol buffers documentation you will see that we can define our messages using the Protocol Buffer Language and that it is common practice to generate your classes from these protocol message definitions.

Lets add an Address to our Person as defined as a protocol buffer message:

From this we are able to generate a partial C# class. The result is the following (Cleaned up in R# for readability):

[Serializable, ProtoContract(Name = @"Person")]
public class Person : IExtensible
{
    private Address _address;
    private int _id;
    private string _name;
    private IExtension extensionObject;

    [ProtoMember(1, IsRequired = true, Name = @"name", DataFormat = DataFormat.Default)]
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    [ProtoMember(2, IsRequired = true, Name = @"id", DataFormat = DataFormat.TwosComplement)]
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

    [ProtoMember(3, IsRequired = false, Name = @"address", DataFormat = DataFormat.Default)]
    [DefaultValue(null)]
    public Address Address
    {
        get { return _address; }
        set { _address = value; }
    }

    #region IExtensible Members

    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }

    #endregion
}

[Serializable, ProtoContract(Name = @"Address")]
public class Address : IExtensible
{
    private string _city;
    private int _number;

    private string _street;
    private IExtension extensionObject;

    [ProtoMember(1, IsRequired = true, Name = @"number", DataFormat = DataFormat.TwosComplement)]
    public int Number
    {
        get { return _number; }
        set { _number = value; }
    }

    [ProtoMember(2, IsRequired = true, Name = @"street", DataFormat = DataFormat.Default)]
    public string Street
    {
        get { return _street; }
        set { _street = value; }
    }

    [ProtoMember(3, IsRequired = true, Name = @"city", DataFormat = DataFormat.Default)]
    public string City
    {
        get { return _city; }
        set { _city = value; }
    }

    #region IExtensible Members

    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }

    #endregion
}

To achieve this code generation from within Visual Studio 2010 / 2008, protobuf-net comes with an executable which performs the code generation. There is also Visual Studio extension which can be found on the protobuf-net site.

Tip: Set the Custom Tool Namespace to “;fixCase” to obtain capilatal letters for your generated property names.

You are able to declare partial class for both Person and Address to add methods to these classes without directly touching the generated code.

Lets look at serialization.

The Serializer class which comes with the protobuf-net library is based heavily on the Stream class in .NET. This give the flexibility to use a wide variety of implements simply.

Serialization to a File:

var person = new Person
                    {
                        Id = 12345678,
                        Name = "Steven Holdsworth",
                        Address = new Address
                                        {
                                            Number = 20,
                                            Street = "Glenwood",
                                            City = "Belfast"
                                         }
                    };

using (var file = File.Create("person.bin"))
{
    Serializer.Serialize(file, person);
}

Deserialization from a File:

Person newPerson;
using (var file = File.OpenRead("person.bin"))
{
     newPerson = Serializer.Deserialize(file);
}

This has been a brief introduction to using Google’s protocol buffers in .NET using protobuf-net
In a coming post I will demonstrate how to use protocol buffers with WCF to transmit your data.

References:
protobuf-net Getting Started Wiki
Protocol Buffers Project Overview

Over the holiday weekend, my mind has wondered in the direction of defensive design at an architectural level.

This train of thought was sparked by Skynet becoming self aware last week and taking down Amazons AWS (http://twitter.com/#!/holsee/status/61122881370853376) and a subsequent post by Jeff Atwood in which he discusses “Working with Chaos Monkey“.

Distributed application design brings many boons, but dependencies between the distributed sub-systems need to be managed with care.

A lot of major sites were taken down during the failure of the AWS infrastructure last week. Netflix was not one of them as they had planned for intermittent failure of distributed components through the creation of Chaos Monkey which randomly took down services.  (I refer you to Jeff’s post).

In a talk I saw by Udi Dihan on SOA, he used Amazon as an example of an application which brings together numerous “vertical” sub-systems to form the whole application.

These sub-systems were highly cohesive yet highly decoupled from one another. The way in which messages were used to request and supply information between sub-systems allowed for the continued operation of the system even if one or more of the sub-systems was to go down.  The messages contain expiration / lifetime meta-data. This meta-data allowed the dependent sub-systems to use the data they already had received for as long as that data remained valid, all you need to do is let the user know when the data was last refreshed in many situations.

I have also read about introducing redundancies to allow sub-systems to operate in the case of a failure of one of the dependencies.  The purest in me screams “No!”, as having concerns replicated and spread across distributed sub-systems could surely lead to new features requiring changes across the board rather than within a single location. The strategy for achieving high availability during entropy of the real world is worth real investment and will vary for each application.

One thing that is certain is if you do not get defensive at the points of communication between distribute sub-systems you will pay the price later in both technical debt and loss of revenue.

This leads to my personal approach, which is to expose “Recovery Strategy Components”.   The components are executed when a subsystem fails providing the base functionality in the event of failure which can be shared across the dependent components.

At a more fine grained level, within a so called distributed vertical sub-system with a CQRS architecture, one of the key characteristics of the Read Model is that it is highly available to replication due to its semi-immutable nature.   If read models contained expiration timestamps (before it is forcibly refreshed) then even if write access to the component has went down, the data will remain available for dependent systems to continue operating.  This, in conjunction with the base recovery strategy components, would be a great stride towards a clean, reusable and maintainable way to consistently provide defensive boundaries between distributed components.

I would be interested to hear your thoughts on this issue.

I have just finished reading the Folklore.org post on 1980′s Apple developers and the cool hoodies that were made. I kinda want one…

I think about optimal development environments a lot.  This article got me thinking about what factors influence developer happiness outside of the project management style in place.

To briefly rhyme of a few which I personally feel are important:

  • Chill-out zones with the understanding of how the human mind works when problem solving for long periods of time.
  • Quadrant Desk structure, which I feel provides the right balance of peace with accessibility for communication.
  • A good developer machine, preferably chosen by developer.
  • Open and fast access to resources such as VMs and test environments.
  • Low friction environment: Continuous Integration and fast effective source control.
  • Team spirit built on team responsibilities and empowerment.

You can have all of the best resources at your finger tips in a great working environment but the single biggest factor in my opinion to achieving a work place where developers want to hang around long after they were meant to leave is the management techniques in place.

Developers don’t like to be battery farmed.  Battery farming rarely produces a Golden Egg.  The proverbial cage is how your treat your developers.  Freedom of thought whilst maintaining a overriding lazer focus on the targets is the sweet spot.  The management of teams to achieve these two factors is pretty complex, but at the most basic level defining a common goal, having excellent communication, coordination and understanding with a large dose of developer empowerment is how we will get there.

The agile movement has been a breath of fresh air in achieving these factors when the principles are applied in environments where the processes and philosophies are understood by the team coordinators.  It is my belief we have made great strides in the software community in pushing things forward for the betterment of developer happiness through our desire to be consistently productive in low friction environments.   I have also experienced more than once when agile goes wrong and becomes poisonous simply due to the decision makers lack of understanding and rigid behaviour which by definition is the opposite of agile, I can vouch first hand that this crushes moral and any desire to perform overtime.

In the “90 Hours A Week And Loving It!” the once proud employee Burrel Smith quits and changed the hoodie to read “0 hours per week and loving it” with tape.  We can only speculate as to why he left, but I have a feeling this lends to the point that large amounts of overtime is not sustainable in the long term, Apple was famous for pushing their developers super hard for long periods of time. Burn out is real and something that should be monitored, but not punished.  Motivation is key, motivation is drained by exhaustion, but keeping motivation high through the factors I have discussed will be the key to short term “over-clocking” of the software development teams. It is important that we don’t use tomorrows energy today, but I think every developer worth their weight has been finely tuning their all nighter skills over the years and it is not unlike us to pull those all nighters when we need to.

All I’m saying is the correct configuration with the developers is key to the ultimate productivity, quality and happiness of not only the code but the code base.

I would love to hear your thoughts on what makes an environment that would have you working “90 hours per week and loving it”?


For a while now I have been searching for blog writing software which is as nice as Live Writer for Windows.

I was recommended MarsEdit by Red Sweater by a friend, so far it seems quite nice.

The first screen you are presented with is nice and clean, allowing you to select your posts and pages.  These get downloaded when you give the app your blog url and credentials.

Screen shot 2010-09-12 at 21.37.24.png

The editor is nothing special, bit like writing an email.  The Server options are funky allowing you to apply settings to the post upon publishing it, such as allowing comments and accepting track backs, although I have not yet tested these.  The Categories were downloaded upon registering my blog with the app.

Screen shot 2010-09-12 at 22.06.16.png

MacJournal another blog writing app for OS X has a very pretty old school terminal style full screen mode.  I suppose this isn’t everyones cup of tea, but I like it.

Screen shot 2010-09-12 at 22.05.05.png

Inserting images is a tad tedious.  There is no in editor resizing of images.  Dragging and dropping images into a post is quite nice thou but nothing special.

Screen shot 2010-09-12 at 22.06.36.png

The preview falls a long way short as it doesn’t really reflect how the post will look on my blog once published.  It looks pretty much like the content does in the editor.

Screen shot 2010-09-12 at 22.28.50.png

The preview and editor is something I really like about Live Writer as it accurately reflects how your post will look in the target site.

My favourite feature of this app is inserting hyperlinks into the text, simply right click on the target text > Format > Paste Link…

Screen shot 2010-09-12 at 22.56.34.png

I need a nice blog editor to help me get over a spell of blog apathy.  I find blogging apps on OS X open too many windows for my tiny 13″ screen, I prefer transitions to encourage focus.

MarsEdit is pretty cool, but not worth the $40 price tag in my opinion.

Happy Blogging.

Over the past year the way I have developed code has been changing.  I have started to think differently about how I implement my code moving beyond traditional object orientated programming, making use of numerous functional concepts in my solutions.  I think this is due to the fact I have been trying to expose myself to as much code as possible across many different languages and platforms and somethings have just stuck.

One of the concepts I have came to know and love is that of a closure.  This was first exposed to me when C# started to incorporate more functional aspects into the language such as anonymous methods as first class citizens and later lambda expressions.

You might think this is quite odd that I specially call out closures & anonymous functions as being a functional concept, as closures are used heavily in dynamic languages due to the fact functions can be passed about as first class citizens. Passing functions about is the very nature of a functional language.

This is what Wikipedia has to say:

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself.

The closure aspect is simple… the anonymous function is “Trapping” the local variable within the functions context.  That means the local variable in question will remain in scope for the duration of the lifetime of the anonymous function. In the examples below I declare anonymous functions called “closure” and I en-close around variable called “x”.

So here is an example of a closure in my language of the month Groovy:

def loopTo(n, closure)
{
	for(int i = 0; i < n; i++)
	{
		if(closure(i))
			println i
	}
}

//Our variable to be "Closed Over"
int x = 2

// I like this syntax of '{ }' to create an anonymous method,
// in Groovy we can use 'it' by default
// to reference an undefined but passed parameter.
loopTo(100, { it % 2 == x })

Now in JavaScript:

function loopTo(n, closure){
	for(i = 0; i < n; i++){
		if(closure(i)){
			alert(i);
		}
	}
}

//Our variable being "Closed over"
var x = 0;
// In JS we use the 'function' keyword and specify the parameter
loopTo(10, function(i){
	return i % 2 == x;
});

Now in C#:

static void Main(string[] args)
{
    //Our variable being "Closed over"
    int x = 0;

    // In C# we can use a lambda expression.
    LoopTo(100, num => num % 2 == x );
}

// As C# is strongly typed we define the expected
// expression type as a 'Func<param, return type>'
public static void LoopTo(int n, Func<int, bool> closure)
{
    for (int i = 0; i < n; i++)
    {
        if(closure(i))
            Console.WriteLine();
    }
}

And now in Scala:

// Scala is sweet we store our range rather than writing a loop,
// then iterate over the list passing the index 'i' into our closure.
def main(args: Array[String]) :Unit = {
    val range = 0.until(100);
    range.foreach(num =>  if(closure(num)) println(num) );
}
//Our variable to be "Closed over"
val x:int = 0
// Our function is defined like so
def closure(num : Int) = {  num %  2 == x;  }

We can copy the Scala way in C#.
We had to cheat a tad and write a funky ‘Until’ C# Extension Method.
This gives us a nice fluent way to create a range of integers stored as a list like so:

public static void Main(string[] args)
{
    //Extension method 'Until' defined later in this post
    var range = 0.Until(100);
    range.ForEach(num => { if(Closure(num)) Console.WriteLine(num); });
}
int x = 0;
// Our function definition in C#
private static readonly Func<int, bool> Closure = num => num % 2 == x;
public static class Extensions
{
    // Called like so: 0.Until(100)
    public static List<int> Until(this int lower, int upper)
    {
        var range = new List<int>();

        for (int i = lower; i <= upper; i++)
        {
            range.Add(i);
        }

        return range;
    }
}

This is what the code would look like without using anonymous functions:

private static void Main(string[] args)
{
    LoopTo(100);
}

public static void LoopTo(int n)
{
    int x = 0;
    for (int i = 0; i < n; i++)
    {
        //Our logic for filtering is tied to the control structure
        if (i % 2 == x)
            Console.WriteLine(i);
    }
}

As you can see the code is not only verbose but breaks a the DRY rule (Don’t Repeat Yourself).  Closures are powerful because they encapsulate what might almost be described as a “Strategy”. You have separated out the control structure from the logic. This is the strategy design pattern.

Closures become powerful when your reach the level of understanding that the encapsulation of logic allows for some really powerful composition of “Strategy”.

I find this really intriguing.  I like languages, and I love the idea creating domain specific languages / fluent APIs which make the definition of “Strategy” trivial to the end user.  By combining closures (via currying) or by logically appending delegates together we can create something truly powerful.

If you didn’t know what anonymous functions & closures were when you started to read this post, then hopefully you do now and maybe you can see why they are worth using.

Just some food for thought.

© 2011 Holsee's Blog Suffusion theme by Sayontan Sinha