Misconceptions about Stoicism

Stoicism is a somewhat familiar idea to most people. It’s usually characterized as a from of emotional dishonesty, where you put on a brave face, or further to the extreme, deny yourself the ability to feel. My parents were very much of the former school of thought, which may be why Stoicism sits fairly comfortably with me.

In truth though, both of those ideas are antithetical to true Stoicism, although when you read the Stoic ‘masters’, it’s easy to see how people could come away with the wrong idea. In this post I’ll go through some common misconceptions and attempt to use them as a way to explain what Stoicism is really about.

Brief History

Stoicism originated with the Greeks, but was taken on with gusto by the Romans, which is where most modern practitioners take their lead from. The three most well known Roman Stoics are Epictetus, a freed slave; Seneca, a businessman, politician and royal adviser; and Marcus Aurelius, Emperor. Their writings make up the core of Roman Stoicism.

Core ideas

Somewhat surprisingly, the aim of practicing Stoicism is to increase the joy that we can experience. The method to achieve this is to “rid ourselves of negative emotions”. Phrased like this (as it often is), it’s easy to see how the reputation of emotional dishonesty might be accurate. But the devil, and in this case I think, the beauty, is in the details.

The Stoics do not advocate pretending that negative emotions do not exist, nor do they think it likely that anyone will achieve a level of mastery where they are no longer affected by them. Instead, they provide a framework for dealing with negative emotions which allows you to exercise some control over the extent to which they effect your life.

The single core principle of Stoicism is that we can maximize our joy by focusing our attention on things that are fully within our control. Inbuilt into this is the idea that we as adults can reason about our emotions, and take some measures to influence them. Virtually every other Stoic lesson is an extension or example of this principle. As a practicing Stoic then, one should split every situation they encounter into components that are either fully in one’s control, or not. Irvine calls this the dichotomy of control.

Here’s an example: you’ve just stared a new job, and it’s going to be intellectually challenging for you to get up to speed. It’s quite normal for you to be nervous about impressing your new boss and teammates, and to worry that you will fall short. A Stoic would advise you to apply the dichotomy of control: can you fully control what your boss or teammates think of you? No. Can you fully control how quickly you pick up the work? No. Can you fully control the focus and effort you make to get up to speed? Yes, so that should be your focus.

This change of focus, from external to internal, has several benefits. Firstly, it allows you to base your self-judgement on something you can change. If your new boss just happens to be hard to please, that won’t interfere with your happiness. Secondly, you will likely perform at a higher level because you’re freeing yourself of the doubt and distraction that comes from trying to please others, giving you more time to focus on what’s important. Thirdly, a likely (though unintended, and out of your control) consequence is that you will impress these people, because you are able to perform at a higher level.

Misconception 1: Hiding emotions

Stoics can appear to be putting on a “brave face”, but in truth they are more likely to have reasoned about the situation they are facing, and chosen to focus on what they can control. In the example above, the new employee isn’t hiding her nervousness: she’s is minimizing or eliminating it.

Of course not all, or even most, emotions can be completely reasoned away. We all experience fears and doubts, and while the Stoicism gives us a framework to deal with them, it does not expect us to hide those that we cannot reason away.

It does have some advice on who to share your feeling with, however. Seneca advises that you should be comfortable telling a true friend anything that is in your heart. When it comes to public displays of emotion, Stoics would ask: why are you doing this? Is it to gain sympathy? If so, that is something that’s out of your control, and so shouldn’t be your focus.

Conversely, if you are hiding your emotions to save face, this is also an attempt to control what others think of you, and is likewise a bad idea.

In general, the Stoics preach the value of honesty, particularly to yourself, but also to others. There is no need to seek attention by sharing your distress, but if someone you trust asks you, there is also no reason to hide.

Misconception 2: Seeing the worst in everything

This misconception has a very solid basis in Stoic teaching, although that teaching seems to be misunderstood. The Stoics encourage us to focus on possible negative outcomes as a way to inoculate us if they should occur, and to help us appreciate what we have right now. This seems a little counter-intuitive, so here’s an example.

When you watch a film where the focus is on the main character losing a loved one, do you walk away thinking about how lucky you are to have your loved ones? Does it heighten your sense of appreciation, make your love feel more immediate, more intense, more real? It certainly does for me.

The Stoics want us to tap into this, and include it in our daily lives. It’s not, as the stereotype goes, about focusing on the bad, it’s about being honest with ourselves about what can happen to us, and using that realisation to help us be present and connected.

Misconception 3: Lying to yourself

I mentioned before that there is the perception that Stoics lie to themselves about their emotions. I also mentioned that in reality, Stoicism places on heavy emphasis on truth. Rather than pretending that negative emotions don’t exist, Stoics go to great lengths to analyse and contemplate their emotions and the truth of their lives.

As an example of self-truth (and also inoculating against the bad), I regularly tell myself: “one day, either through my death or theirs, I won’t have Ange and the boys in my life. The boys may not want to speak with me often or at all when they grow up. They may not group up at all.” It hurts, but it’s the truth, and it helps me to appreciate them while I have them.

Every night as I’m going to bed, I go over the day in my head, and think of times that day where I felt badly. That is, situations in which I either didn’t appply Stoic practice, or where it didn’t work particularly well. Then I reason about what I could have done to deal with the situation differently: where was my focus? On what I control, or on what I do not? How could I shift that focus?

I also take the time to think about where I did apply reason successfully. This can be a really pleasing time, realising that I have successfully taken control of a situation that had the potential to disrupt my joy.


There’s a lot more to Stoicism than I’ve covered here. Things get particularly interesting when it comes to wealth and civic duty. Maybe I’ll write about those later, when I have a better grasp of them.

I’ve been reading the 3 Romans on and off for a year or so, after starting with Irvine’s A Guide to the Good Life. Epictetus in particular resonates with me: he’s concise, witty, and not afraid to use hyperbole or scathing judgments. I’m working my way through Seneca’s Letters, which is much more verbose, but also softer and gentler than the more extreme Epictetus. Meditations I struggle with: Marcus is like a prototypical blogger, with ideas thrown on the page willy nilly. There’s some good one-liners in there though.

Perhaps it’s because of my pseudo-Stoic family traditions, but I’ve found in Stoicism a philosophy that sits comfortably with me. It has a surprising amount of overlap with Buddhism (particularly with regard to wealth and attachment to the transient), which I always wanted to like, but couldn’t quite get the feel for. I’m still very much a beginner – my reason fails me much more often than not – but I’m starting to claw back some of the natural resilience, patience and strength that I had as a young adult, before life got… complicated.

References

  1. William Irvine: A Guide to the Good Life
  2. Epictetus: Discourses incl The Enchiridion
  3. Seneca: Letters from a Stoic
  4. Marcus Aurelius: Meditations

Music I wish I’d found earlier

Over the last couple of years, especially since subscribing to Rdio, I’ve been falling in love with music that’s been around for ages, but that I somehow had missed. This is playlist of “old” music I’ve recently discovered, which has made my life better.

I’ve made playlists of the tracks on Rdio and YouTube:

Daft Punk: Robot Rock/Oh Yeah

I mostly dismissed electronic and rap music for a long time, with some rare exceptions. Not getting into Daft Punk earlier has meant 5 years without hearing Alive 2007, which just makes me sad. The album is awesome to work to, and this is killer opening track.

Azealia Banks: 212

This breaks from the theme a little: I did’t miss this track when it came out. It is, however, a song I wish had been around longer. Completely fun and addictive. Plus, you know, cunnilingus.

The Black Keys: Next Girl

This kinda dirty, rock-y blues competely does it for me. Excellent for Sunday mornings, or any time, really. It feels so effortless and graceful, while being rough and funky. So good.

Bill Withers: Who Is He? (And What Is He To You?)

I can’t remember how I stumbled across Bill Withers. I think I had Lean On Me stuck in my head and looked it up on Rdio. In any case, I now adore him. This track in particular is just perfect.

Broken Face: Pixies

Of all the music on this list, the Pixies are the band I least understand missing. I had friends in late primary school whose parents were into them; they’re referenced everywhere as the precursor to grunge; hell, I even had/have a crush on Cannonball-era Kim Deal. I dunno, it’s a mystery.

Suffice it to say that they’re now firmly on my shortlist of all-time favourite bands.

Jay Z & Kanye West: Otis

As I said, I dismissed rap for a long time. I’ve been listening to a lot of Jay Z and Kanye’s albums, but Watch The Throne is up there as a favourite. I know SFA about rap, but I know I like this.

The Dresden Dolls: Half Jack

I vaguely remember hearing Girl Anachronism and thinkiing it was cool, but didn’t bother checking out the band because it didn’t seem like the sort of thing that could fill a whole album well. Fast forward a few years and everyone in my Twitter feed is losing their shit about Amanda Palmer touring. I decided to see what the fuss was about….

Punk Caberet is such an accurate description. High energy, messy, dark but also showy and inescapably entertaining. As with the Pixies, the Dolls have cemented their place in my all-time favs.

The Dillinger Escape Plan: Dead As History

Back in the day on alt.music.tool (usenet kids, remember that?) a lot of people were going on about this DEP band. I still wasn’t really into metal, and because they were heavier than Tool I never bothered looking them up.

I like to describe DEP as Faith No More cross Straping Young Lad, on speed. This is challenging music if you’re not used to it; complex, wall-of-sound insanity that takes some patience to get through. But man oh man, once you get there…

This is an easier track to listen to, but you’ll stil get the idea. DEP are probably my favourite “metal” band (so long as NIN don’t get pulled into that genre).

High On Fire: Turk

I have Thomas to thank for both DEP and High On Fire. I dunno what to say about them, really, but their gravelly, grubby style really appeals to me.

Machine Head: Darkness Within

I had friends who were into Machine Head in highschool. I was really surprised that they were still around. But this album (Enter the Locust) is extrememly solid metal, with some great depth and variance.

Cream: Tales of Brave Ulysses

So I got to 32 without ever heaving heard Cream, other than on the radio. Go figure.

Bruce Springsteen: Magic

Another artist I’d dimissed because I assumed I wouldn’t be into him. Not long after Ange and I met she mentioned she liked Sprinsteen, so I bought her his lastest album, Magic. I was pretty blown away by just how good it, and he, is. Solid, well written, unaplogetic rock.

Tired Pony: Pieces

Kat gets the credit for this one. I’ve had her mix tapes in the car for months, and every time this comes on I get lost in it.

Pixies: Where Is My Mind

Because you can never have too much of the Pixies. Plus you get to feel like you’ve just blown up a whole heap of shit.

Remapping Android Buttons

My Huawei 8150 has come back to me again, after filling in as a spare phone for my wife (she wasn’t as impressed with it as I am). One of the not-so-great things about it is the 3 massive physical buttons which are set to ‘call’, ‘select’ and ‘end call’ respectively. I mean, who uses a smartphone for making calls?

Anyway, to make the phone a lot more usable, in the past I’ve used ButtonRemapper to change what these buttons do. Unfortnately ButtonRemapper isn’t playing nicely for some reason, so I did some digging, and I found an generic way to remap any key (on, presumably, any Android device). Here’s what to do:

Get Root Access

In order to change the system file that the key mappings are stored in, you need root access. I’m not going to go into this here: it’s device-specific and there’s guides everywhere. It’s not as scary as it seems though.

Install SSHDroid

SSHDroid is a free app that runs an SSH server on your phone. That means you can connect to it remotely and do things. Things like mess with files.

Install PuTTY

If you’re on Windows, PuTTY is pretty much the best SSH client going. You’ll need it to connect to the SSH server that SSHDroid is running

SSH to your phone

When you run SSHDroid, it gives you an address to connect to (something like sftp://root@192.169.1.1). In PuTTY, connect to the host (192.168.1.1) with the username root. The password is admin.

Check your /system mount

Run this command:

mount | grep /system

You should see one line, something like

/dev/block/mtdblock4 on /system type yaffs2 (rw,relatime)

If it says (rw, relatime) then you’re golden: go to the next step. If it says (ro,relatime) then run the following command:

mount -o rw,remount /system

On some devices /system is mounted as read-only: what you’re doing is re-mounting it as read-write so you can change the file.

Change some stuff

cd to /system/usr/keylayout, then run ls. You’ll see one or more .kl files. This may change per device (so you may need to experiement) but for me, qwerty.kl is the file I need to modify. Let’s be a little sensible though:

cp qwerty.kl qwerty.kl.orig

Now you’ll want to vim qwerty.kl. I love vim, but it can be a pretty alien text editor if you’re not used to it. I’ll try and walk you through gently.

The file should contain a whole lot of key mappings that look something like this:

    key 158   BACK              WAKE_DROPPED
    key 230   SOFT_RIGHT        WAKE
    key 60    SOFT_RIGHT        WAKE
    key 107   ENDCALL           WAKE_DROPPED
    key 62    ENDCALL           WAKE_DROPPED
    key 229   MENU              WAKE_DROPPED
    key 139   MENU              WAKE_DROPPED
    key 59    MENU              WAKE_DROPPED
    key 127   SEARCH            WAKE_DROPPED
    key 217   SEARCH            WAKE_DROPPED
    key 228   POUND
    key 227   STAR
    key 231   CALL              WAKE
    key 61    CALL              WAKE_DROPPED
    key 232   DPAD_CENTER       WAKE_DROPPED
    key 108   DPAD_DOWN         WAKE_DROPPED
    key 103   DPAD_UP           WAKE_DROPPED

key 158 is the identifier of the key. The next column is the action (BACK, MENU etc). The last column is something to do with when the key is active, although I don’t really understand it.

It’s a bit of a pain, but to find the keys you want to remap, you need to do a bit of guess-work based on what the action is. For example, key 231 is CALL, which on the IDEOS happens to be the left (green) physical button (ie, one I want to change). But notice there’s another CALL: the only way to work out which is the one you want it trial and error, sadly.

Once you’ve identified a key you want to try remapping, use the arrow buttons to move the cursor to the action part of the line. For example, if I’m remapping key 231, I’ll put the cursor on the C in CALL. Now, type dw, which will delete the word. Type i to go into ‘insert’ mode, then type the action you want, for example, MENU.

Hit esc to go out of insert mode. If you’re happy, type :x to save and exit. If you’ve screwed something up, :q! will get you out without saving any of your changes.

Once you’ve finished editing, restart your phone and see if the remapping worked. If not, rinse and repeat. If you need to go back to the original state, copy the backup back over the top of your changes, with

cp qwerty.kl.orig qwerty.kl

Changes for the IDEOS

Here’s the keys I changed for the IDEOS:

    key 107   BACK              WAKE_DROPPED
    key 231   MENU              WAKE
    key 232   HOME              WAKE_DROPPED

Worst Case

I found this out the hard way, but if you really screw something up, re-flashing your ROM (assuming you’re using a custom ROM..) restores the original .kl files.

Good luck :)

Functional Javascript for OO developers, Part 2

In part 1 I breifly introduced functional language concepts from the point of view of a traditional OO developer. In this post we’ll apply some of those concepts to a real world problem, which we’ll approach in both OO and functional ways.

The Problem

Suppose you need to create an API that produces XML containing data about a book store. You’ve got a store with books, stock levels, that sort of thing.

The OO Solution

This is a great problem for OO modelling: it natually decomposes into modellable objects. So we’d have something like this:

public class Store
{
    public Store(string address, string phone, List<Book> books)
    {
        Address = address;
        PhoneNumber = phone;
        Books = books;
    }

    public string Address {get; set;}
    public string PhoneNumber {get; set;}
    public List<Book> Books {get; private set}

    public string ToXML()
    {
        var doc = new XmlDocument();
        var store = doc.begin("store");

        store.Add("Address", Address).Up()
            .Add("PhoneNumber", PhoneNumber);

        var books = store.Add("books");

        foreach(var book in Books)
            books.Children.Add(book.ToXMLFragment());

        return doc.ToString();
    }
}

public class Book
{
    pubilc Book(string title, List<string> authors, double price, int stockLevel)
    {
        Title = title;
        Authors = authors;
        Price = price;
        StockLevel = stockLevel;
    }

    public string Title {get; set;}
    public List<string> Authors {get; set;}
    public double Price {get; set;}
    public int StockLevel {get; set;}

    public string ToXMLFragment()
    {
        var book = new XmlElement("book")
                    .Add("title", Title).Up()
                    .Add("price", Price)Up()
                    .Add("stock", StockLevel);

        foreach(var a in Authors)
            book.Add("author", a);

        return book;
    }
}

We could flesh out the model further, but you get the idea. Each class defines the structure of the data needed, and instances of the classes maintain the state. Each object is responsible for generating its own part of the XML hierarchy. Simple and encapsulated.

(Sidenote: if that XML construction looks easier than what you’re used to in C#, it’s because I’m using XMLGuy).

The Functional Solution

In a statically typed functional language, you might go ahead and define data types that resemble the classes above, then functions to work on thosse types. Javascript, however, is dynamic and classless, so there’s not really a sensible way to define a data type.

Our convert to XML function still needs a certain structure to its input data. The cleanest way to do this is with some helper functions:

function store(addr, phone, books){
    return {address: addr,
            phoneNumber: phone,
            books: books || []};

function book(title, authors, price, stock){
    return {title: title,
            authors: authors || [],
            price: prince,
            stock: stock};
}

Each function creates an anonymous object that contains the properties needed by the XML generator. Keep in mind of course that any object with the right properties could be passed in, no matter how it was constructed.

And now the generate function:

function ToXML(store){
    function addBook(book){
        books.ele("book")
                .ele("title", book.title).Up()
                .ele("price", book.price).Up()
                .ele("stock", book.stock);

        each(book.author, function(a){ book.ele("author", a)};
    }

    var doc = xmlBuilder.create();
    var root = doc.begin("store");

    root.ele("address", store.address).Up()
        .ele("phoneNumber", store.phoneNumber();

    var books = root.ele("books");

    each(site.books, addBook);

    return doc.toString();
}

The thing to notice here is that the logic to produce XML for a particuar data structure is not encapsulated in the same construct that defines the data structure: instead it will be a function that lives elsewere. A function transforms data; it doesn’t own it.

This sort of separation is of course possible in OO, athough it’s not how you would generally approach it. However, if you had a pre-existing domain model for stores and books you might create a separate class that produces XML from a Store object. You might even extract IStore and IBook interfaces to stop the generator being tied directly to your domain.

Where do the functions live?

Wherever makes sense :) Javascript itself doesn’t (yet) have inbuit module support, but node.js and some client-side libraries do provide it. I tend to group functions that work on the same data structures into a module, so in this case I’d put the object creation functions and the main generation function in a single module.

One of the advantages of OO is that it gives you a structure and a direction when it comes to the ‘right’ way to group things, but that can also be a limitation that prevents you from structuring your code in the most sensible way.

What’s the big deal?

You may be thinking that, while the solutions are somewhat different, they are essentialy the same. Taking a functional approach didn’t really make the solution any easier or clearer. There are some benefits though. The data structure code is solely responsible for creating the data structure, which makes it easier to re-use without modification. That is, you can create other users of the structure that are essentially peers of the XML generator.

Additionally, the code that works on the data structure to create the XML is all together, making it (to me) easier to follow. The code is grouped by function (generate XML) rather than by model (a Book).

Best of all though, you’re not fighting the language. The OO C# code is pretty readable, but if we were to use Javascript the Store ‘class’ would look something like this:

function Store(addr, phone, books){
    // protect against people forgetting the 'new' keyword
    if(!(this instanceof Store))
        return new Store(addr, phone, books);

    // properties with getters and setters
    var addr = addr;
    this.getAddress = function(){ return addr;};
    this.setAddress = function(val){ addr = val;};

    var phone = phone;
    this.getPhoneNumber = function(){ return phone;};
    this.setPhoneNumber = function(val){ phone = val;};

    var books = books || [];
    this.getBooks = function(){ return books;};
    this.addBook = function(book){ books.push(book);};
}

Store.prototype.toXML = function(){
    var doc = xmlBuilder.create();
    var root = doc.begin("store");

    root.ele("address", this.getAddress()).up()
        .ele("phoneNumber", this.getPhoneNumber());

    var booksXML = root.ele("books");

    each(this.getBooks(), function(book){
        booksXML.children.push(book.toXMLFragment());
    });

    return doc.toString();
}

It’s still fairly clear what’s going on, but the hoops you need to jump through to get proper encapsulation are pretty horrible. And if you want to make inheritance work somewhat classically, it gets messier. Essentially you’re building OO plumbing on top of the language.

Conclusion

More than just letting you write cleaner Javascript, thinking functionally will encourage you to approach probems in a different way. You may start to find that re-use via composition (bringing many functions together to do something) rather than inheritance feels much cleaner and much less fragile. And if you’re like me you’ll find the functional approach a nice change from years of OO :)

MVC is only part of the picture

There’s been a lot of discussion in the Rails community and on Hacker News over the last couple of weeks about where business logic belongs in Rails in particular, and MVC in general. There seem to be broadly two camps: DHH’s “just put it all in the model” and the “objects should have single concerns” guys. To me though, business logic doesn’t belong in MVC at all.

Design patterns are not always, or even often, competitors.  Using multiple patterns to architect your application is common and quite sensible. For example, MVC and MVVM are both UI decoupling patterns, but they manage different concerns, and can be used well together. In a rich client framework like .NET’s WPF, you end up with a kind of MVVMC setup; a combination of the patterns where the controller treats the V/VM part of MVVM as its view. In a web app it’s quite possible to have a ‘pure’ MVC design on the server side which feeds an MVVM setup on the client, which in turn calls back to the MVC controller.

The patterns are not competitors. Neither of them solve the “full stack”, from UI back to persistence. And to get back to the main point, this is the problem with the Rails debate: it tries to use MVC to design the whole stack. This will work for apps where the domain is fairly simple. Some of the models may get a bit messy, but on the whole it’ll be fine. But when the domain becomes complex the models becomes unmanageable. And that’s where another design pattern comes in: n-tier.

Remember that guy? He’s the one who says you should separate your app into logical layers like persistence, business logic and presentation. The full stack MVC approach is trying to put persistence and business logic all into the one “model” concept, whereas really MVC addresses just the presentation layer. If your MVC model isn’t simple, it probably needs to be abstracted away until it is. That doesn’t necessarily mean services and DTOs, but some form of abstraction is needed.

I’m not a “big architecture” guy by any means. I’ve seen apps with fairly simple business logic transformed into overly complex beasts as the result of too much separation of concerns (eg. service calls between the presentation tier and the business tier, which always run on the same box). There’s a balance that depends in large part on the scale and complexity of what you’re creating: sometimes architecture adds unnecessary complexity and indirection; sometimes it provides necessary structure and control.

If it’s the opinion of Rails that MVC is an appropriate full stack pattern, then that naturally limits the complexity of the problems you can solve with it before you have to start working against the framework.

Functional Javascript for OO developers, Part 1

Functional Javascript for OO developers, Part 1

Javascript can be a weird thing to a traditional OO developer. For small tasks it’s easy enough to pick up and hack around with, with it’s familiar looking syntax and the fairly forgiving nature of most browsers. But when you try to do something larger than a couple of dozen lines you realise that the familiarity is only skin deep.

Javascript is the antithesis of traditional OO languages like C++, Pascal, Java and C#. Where they are static, strongly typed, imperative languages with classical inheritance; it is dynamic, weakly typed, with prototypical inheritance. Although it can be used imperatively, Javascript has many of the features of a functional language. And on top of that it has a bunch of quirks that confuse the crap out of most people.

In short, it’s its own beast. But it’s a beast that is quite a lot of fun, and well worth learning. This is particularly true of its functional aspects.

In part 1 of this article, I’ll briefly introduce functional concepts in Javascript from the point of view of an OO developer. In part 2 I’ll go through a detailed comparison of how you would approach the same problem from OO and functional perspectives.

Why does functional Javascript matter?

When they first play with it, most OO developers will try to architect their Javascript in an OO way. There are hundreds of articles and books on how to get prototypical inheritance kinda/sorta working like a class, CoffeeScript does it automagically for you, and the ECMAScript panel are even thinking of including class-type stuff in future versions of the language itself. So you’d be by no means alone if you went down that path; I’ve certainly been there.

But, even with the helpers and the potential language changes, classes in Javascript just seem to… suck. There’s all this hand-wavey orchestration required to construct them safely, but in the end I’m still not sure they give you much, other than the ability keep mentally modelling the world in a way you’re familiar with.

Stop solving problems using classes, and not having classing will stop being a problem

Don’t get me wrong: OO has its advantages and it can be a helpful way to think about a problem. Dynamic OO languages like Python and Ruby address some of the deep inheritance insanity that can come with statically typed languages. But there are other ways to model problems, and the more I use it, the more I like the functional approach.

Lets get functional

This article came out of my own frustrating experience of trying to solve a problem in Javascript using OO design. I started to read up on functional design approaches and found it fun and interesting, and it lead to a more satisfactory solution.

In the first year of my IT degree, a maths professor attempted to teach us functional programming (in Miranda, an intellectual precursor of Haskell). He was very excited about being able to prove the mathematical correctness of algorithms; most of us stared blankly and didn’t take much in. It certainly went well over my head, despite having done well in maths in High School. The next year they moved the course to third year. That experience, and the lack of industry use, turned me off functional programming for a long time.

Fast forward a few(!) years, and Microsoft adds LINQ to objects to C# 3.0. LINQ is a beautiful thing. It allows you to perform all sorts of set-based transformations by passing anonymous functions (in the form of lambda expressions). It’s a bit weird when you first see it, but soon you can’t live without it. For example, if you have a list of objects, and you want to create a new list with certain properties for each object, you could do it like this:

var newList = new List<string>();
foreach(var item in list)
    newList.Add(item.Name);

With LINQ, you can do it like this

var newList = list.Select(x => x.Name);

And there’s a whole bunch of LINQ methods: Where(), First(), Any(), Count(), SelectMany(), Aggregate(). Things get more fun when you chain them together:

var adultNames = people.Where(x => x.Age > 18).Select(x => x.Name);
var distinctTagCount = posts.SelectMany(p => p.Tags).Distinct().Count();

It may seem like syntactic sugar, and to a degree it is. But so is almost everything useful about modern languages (otherwise we’d still all be writing C). But more than just sugar, LINQ starts to change the way you think: from “how do I get what I want” to “what do I want”. That is, from imperative to functional thinking.

Microsoft has surreptitiously been teaching OO programmers to think functionally

Unsurprisingly, it turns our that LINQ is inspired by good old functional languages, arguably by way of Ruby. Select() is the equivalent of a functional language’s map(); Aggregate() is reduce(), SelectMany() is flatten(map()).

Where C# has these “what do I want” methods for collections of certain types, functional languages take this approach with everything. Where imperative (and OO) languages concern themselves with manipulating state, functional languages concern themselves with answering questions.

Which brings us back to…

Javascript. Where classes in Javascript are ugly hacks, functional design feels very at home. This is doubly the case if you use underscore.js, a library which provides many of the standard “functional” functions. But even without underscore, it’s easy to roll your own. Lets do that, to get into the functional flow.

First up, we’re going to need some sort of array iterator. We can do this by wrapping up Javascript’s for:

function each(list, func){
    for(var i = 0; i < list.length; i++)
        func(list[i]);
}

This is simple enough, unless you’re not used to seeing functions passed as arguments (hold on tight, we’ll do that a lot). If you’re really keen, you can implement each() in a more ‘functional’ style with a recursive function rather than relying on the more imperative-style for loop.

We can use each() to build up some other useful functions, like a conditional count:

function count(list, predicate){
    if(!predicate)
        return list.length;

    var result = 0;    
    each(list, function(x){if (predicate(x)) result++});

    return result;
}

The predicate here is a function that takes a list item and returns a boolean: if it evaluates to true the count is incremented, otherwise it’s not. If you don’t supply a predicate we substitute a function that always returns true, counting all the items. Here’s how it would be used:

var a = [1,2,3,4];
count(a); // 4
count(a, function(x){ return x > 1}); // 3

The ability to pass functions around as arguments and return values is known as having ‘first class functions’, and is a core feature of functional languages. Unfortunately Javascript’s anonymous function syntax isn’t as clean as, say, C#’s lambda syntax, but it is still quite readable.

You’ll also notice that we reference result in our anonymous function, even though it is declared in the outer count() function. This works because of a funky functional concept called closure. In essence, the anonymous function ‘closes over’ the variable, taking a reference with it whereever it goes and keeping it in scope. In some cases this can mean that a variable remains in scope longer than the function that declared it. It sounds weird, but is immensely useful.

You can see it in use again here in the implementation of map():

function map(list, func){
    var values = [];

    each(list, function(x){ values.push(func(x))});

    return values;
}

Closures allow our first class functions to do rather useful things: it would be much harder to implement a generically useful each() if the function you gave it couldn’t manipulate a data structure defined in the calling function.

Next Time…

By now you should be getting a feel for how you can construct small, specific functions that answer a question (“what are the names of all the people 18 years or older”) rather than modify state. But it’s probably still not clear how you organise and orchestrate them to solve a problem that you may have traditionally modelled as classes and interfaces. I’ll cover that in the next post.

XMLGuy: a fluent XML builder for .NET

One of my (yet to be released) side projects has stalled in part because working with XML in .NET is annoying, and I find it hard to be motivated to do annoying things in my downtime.

DynamicBuilder is a good attempt at making things nicer, but because it is built using the standard .NET XML classes it has the same restrictions about what elements can be named etc. Generally this isn’t an issue, but it can be annoying. And while the syntax is nice, I personally prefer the fluent way xmlbuilder-js does things.

So I wrote XMLGuy: a fluent, lightweight, flexible XML builder for .NET. You can use it like this:

Which produces the following XML:

There’s still a bit of work to be done around namespaces, validation and testing, but it seems pretty solid so far.

The source is available on github and NuGet.

Thoughts on Prometheus

In a line: Prometheus is a stunningly beautiful and perfect execution of a potentially interesting but majorly flawed script. It’s worth seeing, despite the flaws.

Major spoilers follow

The opening scenes are mesmerising. The soundtrack tells the story of the birth of the human species while we fly over massive scenery. Intially the soundtrack seemed a bit OTT, until you realise that at this point it is the narrative, and it’s telling a pretty big story.

The scenes with David before the crew wakes up are a beautiful contrast. From the huge open, noisy landscape to the pristine, silent, interior of the ship. Fassbender aboslutely nails it. Once the crew wakes up, it’s all very Alien/Aliens, which is just fine, if a touch too familiar. Some of the dream/flashback stuff seems like it’s trying too hard to give Shaw some depth, but at this point of the film it’s a minor distraction.

Things start getting distracting once we’re on LV223 (nb, this is not LV426 of the first two movies). Walking through the pitch black underground structure, the scientists are constantly shining their torches in each others’ faces, which is just the first of many unrealistic character behaviours (esp from the scientists) that started to break my suspension of disbeleif.

Plot holes

The most frustrating thing about Prometheus is that many of the plot holes are obvious and could be easily corrected. Why do guys with a 3D map get lost? Why does the biologist go from being scared and uninterested to being fatally curious? Obviously they need to set up a scenario for interaction with the uh, magic goo, but this was just sloppy.

Why is the rare and expensive surgical machine, in the life boat for the female company owner, only configured to operate on males? In what possible world can we make automated surgical instruments but can’t manage to run software that handles both sexes?

In the openning scenes we see the magical goo destroy and re-combine Built Alien Dude’s DNA into what presumably becomes the basis for (human? maybe all?) life. Presumably evolution still ocurred. Maybe. So why are the obviously pysically different Built Alient Dudes an exact genetic match to humans?

The magic goo create xenomorph-like creatures, but it’s never explained why (when the same goo to have created life on earth) it goes so wrong.

Why do ancient human civilisations worship Built Alien Dudes on a planet that the film implies is just an outpost for the manufacture of WMDs?

Why does the geologist gain super-strength from his goo exposure, while Shaw’s partner gets sick and weak from a much smaller exposure.

And then there’s the “lets run in the path of this giant alien ship” thing. Manufactured drama for the sake of an (admittedly impressive) action schene.

And why, for the love of God, does a women stumble into a room covered in blood with her stomach stapled together and no one askes her what happened? Why doesn’t she mention she just gave birth to Cthulhu!?

Characters

I felt zero attachment to any of the characters. Honestly, if Shaw had been eaten by Cthulhu I would have been cool with it. The attempts at backstory etc just felt painted on.

One of the wonderful things about the first two Alien movies is that they’re heavily character driven. You really get the sense that these are multi-dimension, real characters who are finding out how to deal with some exceptionally horrific curcumstances. Sure, characters like Hicks and Vasquez are pretty cliched, but they’re beleivable cliches. The characters in Prometheus don’t feel real: there’s no depth to anyone other than David and they’re constantly doing thngs that make no sense.

Missed opportunities

I can see what they were trying to do with the David/Human/Engineer dynamic, and it had a lot of potential. The ‘obsession with your maker’ theme was the strongest thing in the script, but I’m sure it was fully exploited.

The half-hearted attempt at religiosity was jarring and souless. Oh, “it’s what you choose to beleive”? Fuck you. (My reaction is as subtle as the treatment of the topic).

LV426 vs LV223

I’ve seen people complaining that the ending doesn’t properly leave things as they need to be for Alien to begin, because the Engineer isn’t in the giant canon/seat contraption with his mask on, and there’s human bodies littered everywhere. But the film gets it right here: this is a completely different planet. Presumably at some other point some magic goo gets lose on another Engineer ship and creates the xenomorphs we know and love.

But still

I’d see it again. I’m sure I’ll watch it once it comes out on iTunes/DVD. It looks wonderful, there’s some actual horror moments, and it’s generally entertaining. The flaws I’ve listed make it sound horrible, but it wasn’t. It was just could have been so much better.

Misogynists around me

Or, how I started to see the light on rape culture

I have a knee-jerk defensive response to the term rape culture. It feels accusatory. It feels like the intent is to say that “all men are rapists”. I think I’ve had it all wrong.

Even living under my news rock it was hard to miss the controversy about Girls Around Me:

“It’s not, really, that we’re all horrified by what this app does, is it? […] It’s that we’re all horrified by how exposed these girls are, and how exposed services like Facebook and Foursquare let them be without their knowledge.”
Cult of Mac

Actually, that’s not what horrifies me. Some people are misogynistic creeps, and some of those creeps are app developers who will use data in unintended ways. That doesn’t make me happy, but it doesn’t particularly worry me. What horrifies me is that the focus on “women being exposed” perpetuates the predator/victim dynamic between men and women. It is victim blaming (don’t want to be hunted by sexual predators? Better not share your location!) and it takes as given that men are inherently dangerous.

Instead of the privacy of women’s location data, we should be talking about why that data being shared is “dangerous”. In our attempt to “protect” women I think we are unintentionally normalising and spreading the myth (please God, let it be a myth) that men are sex-obsessed beasts ruled by their cocks, who don’t much care who they fuck. That we are obsessed with impressing and obtaining women while simultaneously hating them. And of course that women and helpless victims who need saving (except when they’re treacherously plotting to steal our manhood).

I’m a guy trying to raise 3 boys into decent, humane men. I want them to grow up being conscious of how they treat other people, especially sexually, but without carrying the baggage of being “potential rapists”. I don’t want them to think of women as “potential victims” in any sense.

We teach boys that they are dangerous. We joke about men being ruled by their dicks. We normalise and excuse attitudes that are eerily similar to those held by rapists. We unquestionably accept that Girls Around Me will be used by leacherous men to hunt women.

This is rape culture. While I still despise the term, I don’t think I can dismiss the concept any more. And honestly, that makes me pretty sad.

Of course, all of this is from the perspective of a 30-something white guy. For a different (but I think complementary) perspective, check out Rosie Ryan’s post.