ACCU World of Code

  • Catch2 Released

    I’ve been talking about Catch2 for a while – but now it’s finally here The big news for Catch2 is that it drops all support for pre-C++11 compilers. Other than meaning that some users will not be supported (you can still use Catch “Classic” (1.x) – …

  • I think I’ve worked out why Uni is so stressful.

    The study environment generates panic.I’m back at University after taking a year out to work as a professional software developer.I got back and instantly found everything so incredibly stressful.Moreso than I felt before during my earlier years at Uni…

  • How to read water

    is an excellent book by Tristan Gooley (isbn 978-1-473-61522-9). As usual I’m going to quote from a few pages: One of the universal truths of human observation is that we see more of what we expect to see and less of what we don’t expect to see…

  • How to read water

    is an excellent book by Tristan Gooley (isbn 978-1-473-61522-9). As usual I’m going to quote from a few pages: One of the universal truths of human observation is that we see more of what we expect to see and less of what we don’t expect to see…

  • Organize for Complexity

    is an excellent book by Niels Pflaeging (isbn 978-0-9915376-0-0). As usual I’m going to quote from a few pages: What Taylor pioneered was the idea of consistently dividing an organization between thinking people (managers) and executing people (w…

  • Organize for Complexity

    is an excellent book by Niels Pflaeging (isbn 978-0-9915376-0-0). As usual I’m going to quote from a few pages: What Taylor pioneered was the idea of consistently dividing an organization between thinking people (managers) and executing people (w…

  • TECH(K)NOW Day workshop on “Writing a programming language”

    My OpenMarket colleagues and I ran a workshop at TECH(K)NOW Day on how to write your own programming language: A big thank you to my colleagues from OpenMarket who volunteered to help: Rowan, Jenny, Zach, James and Elliot. An extra thank you to Zach …

  • FileZilla with proxy not working with strange characters in the password

    Today I found I could not connect out through my proxy server with FileZilla It stopped working when I changed my password to something containing a double quote “. The solution? Change to use WinSCP.

  • HTML5 CSS Toolbar + zoomable workspace that is mobile-friendly and adaptive

    I have been working on a prototype level editor for Rabbit Escape, and I’ve had trouble getting the layout I wanted: a toolbar at the side or top of the screen, and the rest a zoomable workspace. Something like this is very common in many desktop appli…

  • maven-assembly-plugin descriptor for a simple tarball with dependencies

    Today I was trying to make a simple tarball of a project + its dependent jar using the maven-assembly-plugin. I know this is a terrible way to do anything, but hey, just in case someone else wants to do something just as terrible, here are my pom.xml a…

  • Blog aggregator/planet in WordPress using FeedWordPress

    I used to run Planet Code using Venus but that started breaking recently with 500 errors for SNI-enabled sites, and it looks very unmaintained. I considered some other static aggregators, but on shared hosting it’s hard to get the right Ruby version an…

  • The book of five rings

    is an excellent book by Miyamoto Musashi, translated by Thomas Cleary (isbn 1-57062-748-7). As usual I’m going to quote from a few pages: Preface: In common parlance, to do something with a real sword means to do it with utmost earnestness… The Bo…

  • The book of five rings

    is an excellent book by Miyamoto Musashi, translated by Thomas Cleary (isbn 1-57062-748-7). As usual I’m going to quote from a few pages: Preface: In common parlance, to do something with a real sword means to do it with utmost earnestness… The Bo…

  • Unit Testing with Mocha, a local instance of dynamoDB & Promises

    I’m writing the backend for my current iOS App in Javascript using node.js, AWS Lambda along with DynamoDB. My AWS Lambda code is mostly AWS Lambda agnostic except for the initial handler methods, this makes them fairly testable outside of AWS. Howeve…

  • Unit Testing with Mocha, a local instance of dynamoDB & Promises

    I’m writing the backend for my current iOS App in Javascript using node.js, AWS Lambda along with DynamoDB. My AWS Lambda code is mostly AWS Lambda agnostic except for the initial handler methods, this makes them fairly testable outside of AWS. Howeve…

  • Adding a day in Python datetimes – use timedelta, not the datetime constructor

    If you want “tomorrow” in Python datetimes, don’t construct a datetime like this: from datetime import datetime, timedelta td = datetime.today() tm1 = datetime(td.year, td.month, td.day + 1, 14, 0, 0) # Don’t do this! Because it will work sometimes, b…

  • practising jQuery in cyber-dojo

    cyber-dojo now supports practising jQuery. Enjoy 🙂

  • practising jQuery in cyber-dojo

    cyber-dojo now supports practising jQuery. Enjoy 🙂

  • Thames path improvements – Letter to Oxfordshire County Council

    I have sent the following letter to LTS.Team AT oxfordshire.gov.uk in response to https://consultations.oxfordshire.gov.uk/consult.ti/OxfordRiversideRoutes/. &nbsp Hi, &nbsp I have submitted the following via the questionnaire: &nbsp The Oxpe…

  • Thames path improvements – Letter to Oxfordshire County Council

    I have sent the following letter to LTS.Team AT oxfordshire.gov.uk in response to https://consultations.oxfordshire.gov.uk/consult.ti/OxfordRiversideRoutes/. &nbsp Hi, &nbsp I have submitted the following via the questionnaire: &nbsp The Oxpe…

  • Broken Levels Challenge – Egham Raspberry Pi Jam July 2017

    Today at the Egham Raspberry Pi Jam we did two things: 1. The Broken Levels Challenge Some nasty person came and broke our levels for our game Rabbit Escape and we need you to fix them! To play this game you will need a PC version of Rabbit Escape, ou…

  • Pride Vibes 2017: Isle of Wight Pride

    Isle of Wight Pride welcomed people of all ages to a fantastic eventPride Vibes: As a photographer for Gay Pride Pics, I attend lots of Prides across the UK every year. Each Pride has a different feel. This series will describe what each Pride was like…

  • On Company Diversity Targets

    A diversity target number isn't all it might seem to be.Diversity targets show you’re dedicated to giving women a big enough boxThis a reply to Carol Roth’s piece for Entrepreneur. Please read that piece before this one. Make sure to form your own …

  • compile time assertions in C

    C has a facility for checking dynamic assertions at run-time. It’s inside <assert.h> and its called assert. Now assert is a macro, so why isn’t it called ASSERT? I don’t know. Prior art no doubt. Anyway, assert is a dynamic runtime feature, you can only use it inside functions.

    /* not inside a function, won't compile :-( */
    assert(sizeof(int) * CHAR_BIT >= 32);  
    

    That’s a pity because it would be nice if I could get the compiler to check things like this automatically at compile time. I’ve occasionally seen an attempt at a compile-time check like this…

    #if sizeof(int) * CHAR_BIT < 32
    #error People of Earth. Your attention please...
    #endif
    

    But this doesn’t work. The C preprocessor is a glorified text reformatter: it knows practically nothing about C. However, there is a way to write this as a compile time assertion (and moving any error trap to an earlier phase is a Good Thing)

    { yourself }

    #define COMPILE_TIME_ASSERT(expr)   \
        char constraint[expr]
    
    COMPILE_TIME_ASSERT(sizeof(int) * CHAR_BIT >= 32);
    

    What’s is going on here? Well, the example preprocesses to…

    char constraint[sizeof(int) * CHAR_BIT >= 32];
    

    If the expression is true, (an int is at least 32 bits), the expression will have a value of one, and constraint will be an array of one char. If the assertion is false, (an int is less than 32 bits), the expression will have a value of zero, and constraint will be an empty array. That’s illegal, and you’ll get a compile time error. Viola, a compile time assertion 🙂 You can use it inside and outside a function but you can’t use it twice in the same function, as you end up with a duplicate definition. To solve that problem you could resort to some convoluted macro trickery:

    #define COMPILE_TIME_ASSERT(expr)       char UNIQUE_NAME[expr]
    #define UNIQUE_NAME                     MAKE_NAME(__LINE__)
    #define MAKE_NAME(line)                 MAKE_NAME2(line)
    #define MAKE_NAME2(line)                constraint_ ## line
    

    But this is pretty horrible. Also, you will probably get warnings about unused variables. Take a step back for a moment and think about why it works at all. It’s because you have to specify the size of an array as a compile time constant. The formal grammar of a direct-declarator tells you this. Let’s look at some bits of grammar more closely:

    Constrained arrays

     direct-declarator:
      identifier
      ( declarator )
      direct-declarator [ constant-expression opt ]
      direct-declarator ( parameter-type-list )
      direct-declarator ( identifier-list opt )
    

    I just piggy backed on this, using the constraint that the value of the constant expression cannot (in this context) be zero. A natural question (to the curious) is are there other parts of the formal grammar that require a constant expression. The answer, of course, is yes.

    Constrained enums

     enumerator:
      enumeration-constant
      enumeration-constant = constant-expression
    

    However, I can’t use this because there are no useful constraints in this context.

    Constrained bit-fields

     struct-declarator:
      declarator
      declarator opt : constant-expression
    

    Reading the constraints of a bit field I see that if the width of a bit-field is zero the declaration cannot have a declarator. In other words this is legal…

     struct x { unsigned int : 0; };
    

    but this is not…

     struct x { unsigned int bf : 0; };
    

    This suggests another way to create a compile time assertion

    #define COMPILE_TIME_ASSERT(expr)   \
        struct x { unsigned int bf : expr; }
    
    COMPILE_TIME_ASSERT(sizeof(int) * CHAR_BIT >= 32);
    

    Trying this we again get duplicate definitions, not of a variable this time, but of the type struct x. However we can fix this by creating an anonymous struct:

    #define COMPILE_TIME_ASSERT(expr)   \
        struct { unsigned int bf : expr; }
    

    This works. However, now you’ll probably get warnings about the unused untagged struct.

    There is one last bit of grammar that uses a constant-expression.

    Constrained switch

     labelled-statement:
      identifier : statement
      case constant-expression : statement
      default : statement
    

    It’s well known that you can’t have two case labels with the same constant. The following will not compile…

    switch (0)
    {
    case 0:
    case 0:;
    }
    
    So, here’s yet another way to create a compile time assertion. This time we don’t create a dummy variable, or a dummy type, but a dummy statement. A dummy switch statement:
    #define COMPILE_TIME_ASSERT(pred)       \
        switch(0){case 0:case pred:;}
    
    COMPILE_TIME_ASSERT(sizeof(int) * CHAR_BIT >= 32);
    

    If pred evaluates to true (i.e., 1) then the case labels will be 0 and 1. Different; Ok. If pred evaluates to false (i.e., 0) then the case labels will be 0 and 0. The same; Compile time error. Viola. However, a switch statement cannot exist in the global scope. So the last piece of the puzzle is to put the compile time assertions inside a function.

    #include <limits.h>
    
    #define COMPILE_TIME_ASSERT(pred)            \  
        switch(0){case 0:case pred:;}
    
    #define ASSERT_MIN_BITSIZE(type, size)       \
        COMPILE_TIME_ASSERT(sizeof(type) * CHAR_BIT >= size)
    
    #define ASSERT_EXACT_BITSIZE(type, size)     \
        COMPILE_TIME_ASSERT(sizeof(type) * CHAR_BIT == size)
    
    void compile_time_assertions(void)
    {
        ASSERT_MIN_BITSIZE(char,  8);
        ASSERT_MIN_BITSIZE(int,  16);
        ASSERT_EXACT_BITSIZE(long, 32);
    }
    

  • compile time assertions in C

    C has a facility for checking dynamic assertions at run-time. It’s inside <assert.h> and its called assert. Now assert is a macro, so why isn’t it called ASSERT? I don’t know. Prior art no doubt. Anyway, assert is a dynamic runtime feature, you can only use it inside functions.

    /* not inside a function, won't compile :-( */
    assert(sizeof(int) * CHAR_BIT >= 32);  
    

    That’s a pity because it would be nice if I could get the compiler to check things like this automatically at compile time. I’ve occasionally seen an attempt at a compile-time check like this…

    #if sizeof(int) * CHAR_BIT < 32
    #error People of Earth. Your attention please...
    #endif
    

    But this doesn’t work. The C preprocessor is a glorified text reformatter: it knows practically nothing about C. However, there is a way to write this as a compile time assertion (and moving any error trap to an earlier phase is a Good Thing)

    { yourself }

    #define COMPILE_TIME_ASSERT(expr)   \
        char constraint[expr]
    
    COMPILE_TIME_ASSERT(sizeof(int) * CHAR_BIT >= 32);
    

    What’s is going on here? Well, the example preprocesses to…

    char constraint[sizeof(int) * CHAR_BIT >= 32];
    

    If the expression is true, (an int is at least 32 bits), the expression will have a value of one, and constraint will be an array of one char. If the assertion is false, (an int is less than 32 bits), the expression will have a value of zero, and constraint will be an empty array. That’s illegal, and you’ll get a compile time error. Viola, a compile time assertion 🙂 You can use it inside and outside a function but you can’t use it twice in the same function, as you end up with a duplicate definition. To solve that problem you could resort to some convoluted macro trickery:

    #define COMPILE_TIME_ASSERT(expr)       char UNIQUE_NAME[expr]
    #define UNIQUE_NAME                     MAKE_NAME(__LINE__)
    #define MAKE_NAME(line)                 MAKE_NAME2(line)
    #define MAKE_NAME2(line)                constraint_ ## line
    

    But this is pretty horrible. Also, you will probably get warnings about unused variables. Take a step back for a moment and think about why it works at all. It’s because you have to specify the size of an array as a compile time constant. The formal grammar of a direct-declarator tells you this. Let’s look at some bits of grammar more closely:

    Constrained arrays

     direct-declarator:
      identifier
      ( declarator )
      direct-declarator [ constant-expression opt ]
      direct-declarator ( parameter-type-list )
      direct-declarator ( identifier-list opt )
    

    I just piggy backed on this, using the constraint that the value of the constant expression cannot (in this context) be zero. A natural question (to the curious) is are there other parts of the formal grammar that require a constant expression. The answer, of course, is yes.

    Constrained enums

     enumerator:
      enumeration-constant
      enumeration-constant = constant-expression
    

    However, I can’t use this because there are no useful constraints in this context.

    Constrained bit-fields

     struct-declarator:
      declarator
      declarator opt : constant-expression
    

    Reading the constraints of a bit field I see that if the width of a bit-field is zero the declaration cannot have a declarator. In other words this is legal…

     struct x { unsigned int : 0; };
    

    but this is not…

     struct x { unsigned int bf : 0; };
    

    This suggests another way to create a compile time assertion

    #define COMPILE_TIME_ASSERT(expr)   \
        struct x { unsigned int bf : expr; }
    
    COMPILE_TIME_ASSERT(sizeof(int) * CHAR_BIT >= 32);
    

    Trying this we again get duplicate definitions, not of a variable this time, but of the type struct x. However we can fix this by creating an anonymous struct:

    #define COMPILE_TIME_ASSERT(expr)   \
        struct { unsigned int bf : expr; }
    

    This works. However, now you’ll probably get warnings about the unused untagged struct.

    There is one last bit of grammar that uses a constant-expression.

    Constrained switch

     labelled-statement:
      identifier : statement
      case constant-expression : statement
      default : statement
    

    It’s well known that you can’t have two case labels with the same constant. The following will not compile…

    switch (0)
    {
    case 0:
    case 0:;
    }
    
    So, here’s yet another way to create a compile time assertion. This time we don’t create a dummy variable, or a dummy type, but a dummy statement. A dummy switch statement:
    #define COMPILE_TIME_ASSERT(pred)       \
        switch(0){case 0:case pred:;}
    
    COMPILE_TIME_ASSERT(sizeof(int) * CHAR_BIT >= 32);
    

    If pred evaluates to true (i.e., 1) then the case labels will be 0 and 1. Different; Ok. If pred evaluates to false (i.e., 0) then the case labels will be 0 and 0. The same; Compile time error. Viola. However, a switch statement cannot exist in the global scope. So the last piece of the puzzle is to put the compile time assertions inside a function.

    #include <limits.h>
    
    #define COMPILE_TIME_ASSERT(pred)            \  
        switch(0){case 0:case pred:;}
    
    #define ASSERT_MIN_BITSIZE(type, size)       \
        COMPILE_TIME_ASSERT(sizeof(type) * CHAR_BIT >= size)
    
    #define ASSERT_EXACT_BITSIZE(type, size)     \
        COMPILE_TIME_ASSERT(sizeof(type) * CHAR_BIT == size)
    
    void compile_time_assertions(void)
    {
        ASSERT_MIN_BITSIZE(char,  8);
        ASSERT_MIN_BITSIZE(int,  16);
        ASSERT_EXACT_BITSIZE(long, 32);
    }
    

  • C# struct/class differences

    Events are locked?

    Events declared in a class have their += and -= access automatically locked via a lock(this) to make them thread safe (static events are locked on the typeof the class). Events declared in a struct do not have their += and -= access automatically locked. A lock(this) for a struct would not work since you can only lock on a reference type expression.

    Exist on stack or heap?

    Value type local instances are allocated on the stack. Reference type local instances are allocated on the heap.

    Can cause garbage collection?

    Creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a reference type instance can cause garbage collection.

    Meaning of this?

    In a class, this is classified as a value, and thus cannot appear on the left hand side of an assignment, or be used as a ref/out parameter. For example:

    class Indirect
    {
        //...
        public void Method(Indirect that)
        {
            RefParameter(ref this); // compile-time error
            OutParameter(out this); // compile-time error
            this = that;            // compile-time error
        }
        //...
    }
    In a struct, this is classified as an out parameter in a constructor and as a ref parameter in all other function members. Thus it is possible to modify the entire structure by assigning to this or passing this as a ref/out parameter. For example:
    struct Direct
    {
        //...
        public void Reassign(Direct that)
        {
            RefParameter(ref this); // compiles ok
            OutParameter(out this); // compiles ok
            this = that;            // compiles ok
        }
        //...
    }
    Furthermore, you can reassign a whole struct even when the struct contains readonly fields!
    struct Direct
    {
        public Direct(int value)
        {
            Field = value;
        }
    
        public void Reassign(Direct that)
        {
            RefParameter(ref this); // compiles ok
            OutParameter(out this); // compiles ok
            this = that;            // compiles ok
        }
    
        public readonly int Field;
    }
    
    class Show
    {
        static void Main()
        {
            Direct s = new Direct(42);
            Console.WriteLine(s.Field); // writes 42
            s.Reassign(new Direct(24));
            Console.WriteLine(s.Field); // writes 24
        }
    }
    Note however that when you call a method on a readonly value-type field, the method call is made on a copy of the field.
    struct Direct
    {
        // as above
    }
    
    class Caller
    {
        public void Method()
        {
            Console.WriteLine(d.Field); // writes 42
            d.Reassign(new Direct(24));
            Console.WriteLine(d.Field); // writes 42!
        }
    
        private readonly Direct d = new Direct(42);
    }
    
    class Show
    {
        static void Main()
        {
            Caller c = new Caller();
            c.Method();
        }
    }

    Always have a default constructor?

    A struct always has a built-in public default constructor.

    class DefaultConstructor
    {
        static void Eg()
        {
              Direct   yes = new   Direct(); // always compiles ok
            InDirect maybe = new InDirect(); // compiles if c'tor exists and is accessible
            //...
        }
    }
    This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.
    class NonInstantiable
    {
        private NonInstantiable() // ok
        {
        }
    }
    
    struct Direct
    {
        private Direct() // compile-time error
        {
        }
    }

    Default construction triggers static constructor?

    A structs static constructor is not triggered by calling the structs default constructor. It is for a class.

    struct Direct
    {
        static Direct()
        {
            Console.WriteLine("This is not written");
        }
    }
    
    class NotTriggered
    {
        static void Main()
        {
            Direct local = new Direct();
        }
    }

    Can be null?

    A struct instance cannot be null.

    class Nullness
    {
        static void Eg(Direct s, Indirect c)
        {
            if (s == null) ... // compile-time error
            if (c == null) ... // compiles ok
        }
    }

    Use with the as operator?

    A struct type cannot be the right hand side operand of the as operator.

    class Fragment
    {
        static void Eg(Direct s, Indirect c)
        {
              Direct  no = s as   Direct; // compile-time error
            InDirect yes = c as InDirect; // compiles ok
            //...
        }
    }

    Can be locked?

    A struct type expression cannot be the operand of a lock statement.

    class LockStatement
    {
        static void Eg(Direct s, InDirect c)
        {
            lock(s) { ... } // compile-time error
            lock(c) { ... } // compiles ok
        }
    }

    Can have a destructor?

    A struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garbage collection.

    struct Direct
    {
        ~Direct() {} // compile-time error
    }
    class InDirect
    {
        ~InDirect() {} // compiles ok
    }

    And the CIL for ~Indirect() looks like this:

    .method family hidebysig virtual instance void
            Finalize() cil managed
    {
      // ...
    } // end of method Indirect::Finalize

    Default field layout?

    The default [StructLayout] attribute (which lives in the System.Runtime.InteropServices namespace) for a struct is LayoutKind.Sequential whereas the default StructLayout for a class is LayoutKind.Auto. (And yes, despite its name you can tag a class with the StructLayout attribute.) In other words the CIL for this:

    public struct Direct
    {
        //...
    }

    looks like this:

    .class public sequential ansi sealed beforefieldinit Direct
           extends [mscorlib]System.ValueType
    {
      //...
    }

    whereas the CIL for this:

    public sealed class InDirect
    {
        //...
    }

    looks like this:

    .class public auto ansi sealed beforefieldinit Indirect
           extends [mscorlib]System.Object
    {
        //...
    }

    Can be a volatile field?

    You can’t declare a user-defined struct type as a volatile field but you can declare a user-defined class type as a volatile field.

    class Bad
    {
        private volatile Direct field; // compile-time error
    }
    class Good
    {
        private volatile Indirect field; // compiles ok
    }

    Can have synchronized methods?

    You can’t use the [MethodImpl(MethodImplOptions.Synchronized)] attribute on methods of a struct type (if you call the method you get a runtime TypeLoadException) whereas you can use the [MethodImpl(MethodImplOptions.Synchronized)] attribute on methods of a class type.

    using System.Runtime.CompilerServices;
    
    class Indirect
    {
        [MethodImpl(MethodImplOptions.Synchronized)] // compiles and runs ok
        public void Method()
        {
            //...
        }
    }
    
    struct Direct
    {
        [MethodImpl(MethodImplOptions.Synchronized)] // compiles ok, runtime TypeLoadException
        public void Method()
        {
            //...
        }
    }

    Can be pointed to?

    Clause 25.2 of the C# standard defines an unmanaged type as any type that isn’t a reference type and doesn’t contain reference-type fields at any level of nesting. That is, one of the following:

    • Any simple value type (11.1.3, eg byte, int, long, double, bool, etc).
    • Any enum type.
    • Any pointer type.
    • Any user-defined struct-type that contains fields of unmanaged types only.
    You can never take the address of a instance of a type that is not unmanaged (a fixed variable 25.3).
    class Bad
    {
        static void Main()
        {
            Indirect variable = new Indirect();
            unsafe
            {
                fixed(Indirect * ptr = &variable) // compile-time error
                {
                    //...
                }
            }
        }
    }
    If you want to fix an unmanaged instance you have to do so by fixing it through an unmanaged field. For example:
    class Indirect
    {
        public int fixHandle;
    }
    class Bad
    {
        static void Main()
        {
            Indirect variable = new Indirect();
            unsafe
            {
                fixed(int * ptr = &variable.fixHandle) // compiles ok
                {
                    //...
                }
            }
        }
    }
    In contrast, you can (nearly) always take the address of an unmanaged instance.
    struct Direct
    {
        // no reference fields at any level of nesting
    }
    class SimpleCase
    {
        static void Main()
        {
            Direct variable = new Direct();
            unsafe
            {
                Direct * ptr = &variable; // compiles ok
                //...       
            }
        }
    }
    However, you have to take the address inside a fixed statement if the variable is moveable (subject to relocation by the garbage collector, see 25.3 and example above). Also, you can never take the address of a volatile field.

    So, in summary, you can never create a pointer to a class type but you sometimes create a pointer to a struct type.

    Can be stackalloc’d?

    You can only use stackalloc on unmanaged types. Hence you can never use stackalloc on class types. For example:

    class Indirect
    {
        //...
    }
    class Bad
    {
        static void Main()
        {
            unsafe
            {
                Indirect * array = stackalloc Indirect[42]; // compile-time error
                //...
            }
        }
    }
    Where as you can use stackalloc on struct types that are unmanaged. For example:
    struct Direct
    {
        // no reference fields at any level of nesting
    }
    class Good
    {
        static void Main()
        {
            unsafe
            {
                Direct * array = stackalloc Direct[42]; // compiles ok
                //...
            }
        }
    }

    Can be sizeof’d?

    You can only use sizeof on unmanaged types. Hence you can never use sizeof on class types. For example:

    class Indirect
    {
        //...
    }
    class Bad
    {
        static void Main()
        {
            unsafe
            {
                int size = sizeof(Indirect); // compile-time error
                //...
            }
        }
    }
    Where as you can use sizeof on struct types that are unmanaged. For example:
    struct Direct
    {
        // no reference fields at any level of nesting
    }
    class Good
    {
        static void Main()
        {
            unsafe
            {
                int size = sizeof(Direct); // compiles ok
                //...
            }
        }
    }

    How to initialize fields?

    The fields of a class have a default initialization to zero/false/null. The fields of a struct have no default value.

    struct Direct
    {
        public int Field;
    }
    
    class Indirect
    {
        public Indirect()
        {
        }
        //...
        public int Field;
    }
    
    class Defaults
    {
        static void Main()
        {
            Direct s;
            Console.WriteLine(s.Field);  // compile-time error
    
            Indirect c = new Indirect();
            Console.WriteLine(c.Field); // compiles ok
        }
    }

    You can initialize fields in a class at their point of declaration. For example:

    class Indirect
    {
        //...
        private int field = 42;
    }
    You can’t do this for fields in a struct. For example:
    struct Direct
    {
        //...
        private int field = 42; // compile-time error
    }
    Fields in a struct have to be initialized in a constructor. For example:
    struct Direct
    {
        public Direct(int value)
        {
            field = value;
        }
        //...
        private int field; // compiles ok
    }
    Also, the definite assignment rules of a struct are tracked on an individual field basis. This means you can bypass initialization and “assign” the fields of a struct one a time. For example:
    struct Direct
    {
        public int X, Y;
    }
    class Example
    {
        static void Main()
        {
            Direct d;
            d.X = 42;
            Console.WriteLine(d.X); // compiles ok
            Console.WriteLine(d.Y); // compile-time error
        }
    }

    Inheritance differences?

    • a struct is implicitly sealed, a class isn’t.
    • a struct can’t be abstract, a class can.
    • a struct can’t call : base() in its constructor whereas a class with no explicit base class can.
    • a struct can’t extend another class, a class can.
    • a struct can’t declare protected members (eg fields, nested types) a class can.
    • a struct can’t declare abstract function members, an abstract class can.
    • a struct can’t declare virtual function members, a class can.
    • a struct can’t declare sealed function members, a class can.
    • a struct can’t declare override function members, a class can. The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString().

    Equals behavior?

    classes inherit Object.Equals which implements identity equality whereas structs inherit ValueType.Equals which implements value equality.

    using System.Diagnostics;
    
    struct Direct
    {
        public Direct(int value)
        {
            field = value;
        }
        private int field;
    }
    
    class Indirect
    {
        public Indirect(int value)
        {
            field = value;
        }
        private int field;
    }
    
    class EqualsBehavior
    {
        static void Main()
        {
            Direct s1 = new Direct(42);
            Direct s2 = new Direct(42);
    
            Indirect c1 = new Indirect(42);
            Indirect c2 = new Indirect(42);
    
            bool structEquality = s1.Equals(s2);
            bool classIdentity  = !c1.Equals(c2);
    
            Debug.Assert(structEquality);
            Debug.Assert(classIdentity);
    
        }
    }
    Overriding Equals for structs should be faster because it can avoid reflection and boxing.
    struct Direct
    {
        public Direct(int value)
        {
            field = value;
        }
    
        public override bool Equals(object other)
        {
            return other is Direct && Equals((Direct)other);
        }
    
        public static bool operator==(Direct lhs, Direct rhs)
        {
            return lhs.Equals(rhs);
        }
    
        //...    
    
        private bool Equals(Direct other)
        {
            return field == other.field;
        }
    
        private int field;
    }

  • C# struct/class differences

    Events are locked?

    Events declared in a class have their += and -= access automatically locked via a lock(this) to make them thread safe (static events are locked on the typeof the class). Events declared in a struct do not have their += and -= access automatically locked. A lock(this) for a struct would not work since you can only lock on a reference type expression.

    Exist on stack or heap?

    Value type local instances are allocated on the stack. Reference type local instances are allocated on the heap.

    Can cause garbage collection?

    Creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a reference type instance can cause garbage collection.

    Meaning of this?

    In a class, this is classified as a value, and thus cannot appear on the left hand side of an assignment, or be used as a ref/out parameter. For example:

    class Indirect
    {
        //...
        public void Method(Indirect that)
        {
            RefParameter(ref this); // compile-time error
            OutParameter(out this); // compile-time error
            this = that;            // compile-time error
        }
        //...
    }
    In a struct, this is classified as an out parameter in a constructor and as a ref parameter in all other function members. Thus it is possible to modify the entire structure by assigning to this or passing this as a ref/out parameter. For example:
    struct Direct
    {
        //...
        public void Reassign(Direct that)
        {
            RefParameter(ref this); // compiles ok
            OutParameter(out this); // compiles ok
            this = that;            // compiles ok
        }
        //...
    }
    Furthermore, you can reassign a whole struct even when the struct contains readonly fields!
    struct Direct
    {
        public Direct(int value)
        {
            Field = value;
        }
    
        public void Reassign(Direct that)
        {
            RefParameter(ref this); // compiles ok
            OutParameter(out this); // compiles ok
            this = that;            // compiles ok
        }
    
        public readonly int Field;
    }
    
    class Show
    {
        static void Main()
        {
            Direct s = new Direct(42);
            Console.WriteLine(s.Field); // writes 42
            s.Reassign(new Direct(24));
            Console.WriteLine(s.Field); // writes 24
        }
    }
    Note however that when you call a method on a readonly value-type field, the method call is made on a copy of the field.
    struct Direct
    {
        // as above
    }
    
    class Caller
    {
        public void Method()
        {
            Console.WriteLine(d.Field); // writes 42
            d.Reassign(new Direct(24));
            Console.WriteLine(d.Field); // writes 42!
        }
    
        private readonly Direct d = new Direct(42);
    }
    
    class Show
    {
        static void Main()
        {
            Caller c = new Caller();
            c.Method();
        }
    }

    Always have a default constructor?

    A struct always has a built-in public default constructor.

    class DefaultConstructor
    {
        static void Eg()
        {
              Direct   yes = new   Direct(); // always compiles ok
            InDirect maybe = new InDirect(); // compiles if c'tor exists and is accessible
            //...
        }
    }
    This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.
    class NonInstantiable
    {
        private NonInstantiable() // ok
        {
        }
    }
    
    struct Direct
    {
        private Direct() // compile-time error
        {
        }
    }

    Default construction triggers static constructor?

    A structs static constructor is not triggered by calling the structs default constructor. It is for a class.

    struct Direct
    {
        static Direct()
        {
            Console.WriteLine("This is not written");
        }
    }
    
    class NotTriggered
    {
        static void Main()
        {
            Direct local = new Direct();
        }
    }

    Can be null?

    A struct instance cannot be null.

    class Nullness
    {
        static void Eg(Direct s, Indirect c)
        {
            if (s == null) ... // compile-time error
            if (c == null) ... // compiles ok
        }
    }

    Use with the as operator?

    A struct type cannot be the right hand side operand of the as operator.

    class Fragment
    {
        static void Eg(Direct s, Indirect c)
        {
              Direct  no = s as   Direct; // compile-time error
            InDirect yes = c as InDirect; // compiles ok
            //...
        }
    }

    Can be locked?

    A struct type expression cannot be the operand of a lock statement.

    class LockStatement
    {
        static void Eg(Direct s, InDirect c)
        {
            lock(s) { ... } // compile-time error
            lock(c) { ... } // compiles ok
        }
    }

    Can have a destructor?

    A struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garbage collection.

    struct Direct
    {
        ~Direct() {} // compile-time error
    }
    class InDirect
    {
        ~InDirect() {} // compiles ok
    }

    And the CIL for ~Indirect() looks like this:

    .method family hidebysig virtual instance void
            Finalize() cil managed
    {
      // ...
    } // end of method Indirect::Finalize

    Default field layout?

    The default [StructLayout] attribute (which lives in the System.Runtime.InteropServices namespace) for a struct is LayoutKind.Sequential whereas the default StructLayout for a class is LayoutKind.Auto. (And yes, despite its name you can tag a class with the StructLayout attribute.) In other words the CIL for this:

    public struct Direct
    {
        //...
    }

    looks like this:

    .class public sequential ansi sealed beforefieldinit Direct
           extends [mscorlib]System.ValueType
    {
      //...
    }

    whereas the CIL for this:

    public sealed class InDirect
    {
        //...
    }

    looks like this:

    .class public auto ansi sealed beforefieldinit Indirect
           extends [mscorlib]System.Object
    {
        //...
    }

    Can be a volatile field?

    You can’t declare a user-defined struct type as a volatile field but you can declare a user-defined class type as a volatile field.

    class Bad
    {
        private volatile Direct field; // compile-time error
    }
    class Good
    {
        private volatile Indirect field; // compiles ok
    }

    Can have synchronized methods?

    You can’t use the [MethodImpl(MethodImplOptions.Synchronized)] attribute on methods of a struct type (if you call the method you get a runtime TypeLoadException) whereas you can use the [MethodImpl(MethodImplOptions.Synchronized)] attribute on methods of a class type.

    using System.Runtime.CompilerServices;
    
    class Indirect
    {
        [MethodImpl(MethodImplOptions.Synchronized)] // compiles and runs ok
        public void Method()
        {
            //...
        }
    }
    
    struct Direct
    {
        [MethodImpl(MethodImplOptions.Synchronized)] // compiles ok, runtime TypeLoadException
        public void Method()
        {
            //...
        }
    }

    Can be pointed to?

    Clause 25.2 of the C# standard defines an unmanaged type as any type that isn’t a reference type and doesn’t contain reference-type fields at any level of nesting. That is, one of the following:

    • Any simple value type (11.1.3, eg byte, int, long, double, bool, etc).
    • Any enum type.
    • Any pointer type.
    • Any user-defined struct-type that contains fields of unmanaged types only.
    You can never take the address of a instance of a type that is not unmanaged (a fixed variable 25.3).
    class Bad
    {
        static void Main()
        {
            Indirect variable = new Indirect();
            unsafe
            {
                fixed(Indirect * ptr = &variable) // compile-time error
                {
                    //...
                }
            }
        }
    }
    If you want to fix an unmanaged instance you have to do so by fixing it through an unmanaged field. For example:
    class Indirect
    {
        public int fixHandle;
    }
    class Bad
    {
        static void Main()
        {
            Indirect variable = new Indirect();
            unsafe
            {
                fixed(int * ptr = &variable.fixHandle) // compiles ok
                {
                    //...
                }
            }
        }
    }
    In contrast, you can (nearly) always take the address of an unmanaged instance.
    struct Direct
    {
        // no reference fields at any level of nesting
    }
    class SimpleCase
    {
        static void Main()
        {
            Direct variable = new Direct();
            unsafe
            {
                Direct * ptr = &variable; // compiles ok
                //...       
            }
        }
    }
    However, you have to take the address inside a fixed statement if the variable is moveable (subject to relocation by the garbage collector, see 25.3 and example above). Also, you can never take the address of a volatile field.

    So, in summary, you can never create a pointer to a class type but you sometimes create a pointer to a struct type.

    Can be stackalloc’d?

    You can only use stackalloc on unmanaged types. Hence you can never use stackalloc on class types. For example:

    class Indirect
    {
        //...
    }
    class Bad
    {
        static void Main()
        {
            unsafe
            {
                Indirect * array = stackalloc Indirect[42]; // compile-time error
                //...
            }
        }
    }
    Where as you can use stackalloc on struct types that are unmanaged. For example:
    struct Direct
    {
        // no reference fields at any level of nesting
    }
    class Good
    {
        static void Main()
        {
            unsafe
            {
                Direct * array = stackalloc Direct[42]; // compiles ok
                //...
            }
        }
    }

    Can be sizeof’d?

    You can only use sizeof on unmanaged types. Hence you can never use sizeof on class types. For example:

    class Indirect
    {
        //...
    }
    class Bad
    {
        static void Main()
        {
            unsafe
            {
                int size = sizeof(Indirect); // compile-time error
                //...
            }
        }
    }
    Where as you can use sizeof on struct types that are unmanaged. For example:
    struct Direct
    {
        // no reference fields at any level of nesting
    }
    class Good
    {
        static void Main()
        {
            unsafe
            {
                int size = sizeof(Direct); // compiles ok
                //...
            }
        }
    }

    How to initialize fields?

    The fields of a class have a default initialization to zero/false/null. The fields of a struct have no default value.

    struct Direct
    {
        public int Field;
    }
    
    class Indirect
    {
        public Indirect()
        {
        }
        //...
        public int Field;
    }
    
    class Defaults
    {
        static void Main()
        {
            Direct s;
            Console.WriteLine(s.Field);  // compile-time error
    
            Indirect c = new Indirect();
            Console.WriteLine(c.Field); // compiles ok
        }
    }

    You can initialize fields in a class at their point of declaration. For example:

    class Indirect
    {
        //...
        private int field = 42;
    }
    You can’t do this for fields in a struct. For example:
    struct Direct
    {
        //...
        private int field = 42; // compile-time error
    }
    Fields in a struct have to be initialized in a constructor. For example:
    struct Direct
    {
        public Direct(int value)
        {
            field = value;
        }
        //...
        private int field; // compiles ok
    }
    Also, the definite assignment rules of a struct are tracked on an individual field basis. This means you can bypass initialization and “assign” the fields of a struct one a time. For example:
    struct Direct
    {
        public int X, Y;
    }
    class Example
    {
        static void Main()
        {
            Direct d;
            d.X = 42;
            Console.WriteLine(d.X); // compiles ok
            Console.WriteLine(d.Y); // compile-time error
        }
    }

    Inheritance differences?

    • a struct is implicitly sealed, a class isn’t.
    • a struct can’t be abstract, a class can.
    • a struct can’t call : base() in its constructor whereas a class with no explicit base class can.
    • a struct can’t extend another class, a class can.
    • a struct can’t declare protected members (eg fields, nested types) a class can.
    • a struct can’t declare abstract function members, an abstract class can.
    • a struct can’t declare virtual function members, a class can.
    • a struct can’t declare sealed function members, a class can.
    • a struct can’t declare override function members, a class can. The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString().

    Equals behavior?

    classes inherit Object.Equals which implements identity equality whereas structs inherit ValueType.Equals which implements value equality.

    using System.Diagnostics;
    
    struct Direct
    {
        public Direct(int value)
        {
            field = value;
        }
        private int field;
    }
    
    class Indirect
    {
        public Indirect(int value)
        {
            field = value;
        }
        private int field;
    }
    
    class EqualsBehavior
    {
        static void Main()
        {
            Direct s1 = new Direct(42);
            Direct s2 = new Direct(42);
    
            Indirect c1 = new Indirect(42);
            Indirect c2 = new Indirect(42);
    
            bool structEquality = s1.Equals(s2);
            bool classIdentity  = !c1.Equals(c2);
    
            Debug.Assert(structEquality);
            Debug.Assert(classIdentity);
    
        }
    }
    Overriding Equals for structs should be faster because it can avoid reflection and boxing.
    struct Direct
    {
        public Direct(int value)
        {
            field = value;
        }
    
        public override bool Equals(object other)
        {
            return other is Direct && Equals((Direct)other);
        }
    
        public static bool operator==(Direct lhs, Direct rhs)
        {
            return lhs.Equals(rhs);
        }
    
        //...    
    
        private bool Equals(Direct other)
        {
            return field == other.field;
        }
    
        private int field;
    }

  • HikingMaps for Tizen

    HikingMaps is now also available in the Tizen Store for Tizen 3.

  • HikingMaps for Tizen

    HikingMaps is now also available in the Tizen Store for Tizen 3.

  • Women Who Code workshop on “Write your own programming language”

    On Wednesday 28th June 2017 a group of people from OpenMarket went to the Fora office space in Clerkenwell, London to run a workshop with the Women Who Code group, who work to help women achieve their career goals. OpenMarket provided the workshop “Wri…

  • Tell, don’t ask

    More than twelve years ago Tim Joyce passed on some programming wisdom: With programs tell don’t ask, vice versa for people. This was a bit abstract for me at the time but last night it came back to me as what is wrong with the code I am currently …

  • Tell, don’t ask

    More than twelve years ago Tim Joyce passed on some programming wisdom: With programs tell don’t ask, vice versa for people. This was a bit abstract for me at the time but last night it came back to me as what is wrong with the code I am currently …

  • Running a virtualenv with a custom-built Python

    For my attempt to improve the asyncio.as_completed Python standard library function I needed to build a local copy of cpython (the Python interpreter). To test it, I needed the aiohttp module, which is not part of the standard library, so the easiest w…

  • Adding a concurrency limit to Python’s asyncio.as_completed

    Series: asyncio basics, large numbers in parallel, parallel HTTP requests, adding to stdlib In the previous post I demonstrated how the limited_as_completed method allows us to run a very large number of tasks using concurrency, but limiting the number…

  • “git what” is “git status” on steroids

    For when git status is not enough, I wrote git what: If you often have a few branches on the go, it could be useful.

  • Pride Vibes 2017: Coventry Pride

    Laura Tapp performs on Saturday evening at Coventry PridePride Vibes: As a photographer for Gay Pride Pics, I see lots of Prides across the UK every year. Each Pride has a different feel. This series will describe what each Pride was like and what the …

  • Making 100 million requests with Python aiohttp

    Series: asyncio basics, large numbers in parallel, parallel HTTP requests, adding to stdlib Update: slides of a talk I gave at the London Python Meetup on this: Talk slides: Making 100 million HTTP requests with Python aiohttp. Update: see how Cristian…

  • Python – printing UTC dates in ISO8601 format with time zone

    By default, when you make a UTC date from a Unix timestamp in Python and print it in ISO format, it has no time zone: $ python3 >>> from datetime import datetime >>> datetime.utcfromtimestamp(1496998804).isoformat() ‘2017-06-09T09:00:…

  • Pride Vibes 2017: Birmingham Pride

    Marching in Birmingham’s ParadePride Vibes: As a photographer for Gay Pride Pics, I see lots of Prides across the UK every year. Each Pride has a different feel. This series will describe what each Pride was like and what the vibe of the pride was like…

  • Berkhamsted to Tring Walk

    Went for a walk from Berkhamsted to Tring, see GPS data and some pictures: here, here and here.

  • Berkhamsted to Tring Walk

    Went for a walk from Berkhamsted to Tring, see GPS data and some pictures: here, here and here.

  • Galloway Camping Holiday

    Been to Galloway for a few days of (wild) camping (around Loch Dee, Loch Trool, Merrick, Loch Finlas, Loch Doon). Also stopped in Carlisle before returning back to London. See my digital photo album for a few pictures.

  • Galloway Camping Holiday

    Been to Galloway for a few days of (wild) camping (around Loch Dee, Loch Trool, Merrick, Loch Finlas, Loch Doon). Also stopped in Carlisle before returning back to London. See my digital photo album for a few pictures.

  • Python 3 – large numbers of tasks with limited concurrency

    Series: asyncio basics, large numbers in parallel, parallel HTTP requests, adding to stdlib I am interested in running large numbers of tasks in parallel, so I need something like asyncio.as_completed, but taking an iterable instead of a list, and with…

  • Basic ideas of Python 3 asyncio concurrency

    Series: asyncio basics, large numbers in parallel, parallel HTTP requests, adding to stdlib Update: see the Python Async Basics video on this topic. Python 3’s asyncio module and the async and await keywords combine to allow us to do cooperative concur…

  • Cotswolds Walk

    Went for a walk in the Cotswolds from Kingham to Moreton-in-Marsh, see GPS data and some pictures: part 1, part 2, part 3, part 4, and part 5.

  • Cotswolds Walk

    Went for a walk in the Cotswolds from Kingham to Moreton-in-Marsh, see GPS data and some pictures: part 1, part 2, part 3, part 4, and part 5.

  • C++ iterator wrapping a stream not 1-1

    Series: Iterator, Iterator Wrapper, Non-1-1 Wrapper Sometimes we want to write an iterator that consumes items from some underlying iterator but produces its own items slower than the items it consumes, like this: ColonSep items(“aa:foo::x”); // Prints…

  • How to write a programming language ACCU talk

    My talk from ACCU Conference 2017 where I describe a tiny programming language I wrote: Slides: How to write a programming language Cell source code: github.com/andybalaam/cell

  • C++ iterator wrapper/adaptor example

    Series: Iterator, Iterator Wrapper, Non-1-1 Wrapper If you want to wrap an iterable range with another that transforms the underlying iterators in some way and allows looping or constructing other objects: for (auto ch : Upper(“abcdef”)) { // Print…

  • C++ iterator example (and an iterable range)

    Series: Iterator, Iterator Wrapper, Non-1-1 Wrapper To make your own iterable range in C++ that you can loop over or make a vector out of (mine is called Numbers): // Prints: // 3,4, for (auto n : Numbers(3, 5)) { std::cout << n << “,”;…

  • Make Android Gradle display unit test failure messages

    By default, Gradle does not show you what happened when a unit test failed: $ ./gradlew test … MyTest > Black_is_white FAILED org.junit.ComparisonFailure at MyTest.java:6 ^^^ WHAT ACTUALLY FAILED???? … This is insane, and can be fixed (t…

  • ACCU C++ Countdown Pub Quiz

    The ACCU conference is one of the highlights of my year. I ran a brand new session, a C++ Pub Quiz with an emphasis on fun and interaction, based loosely on the popular UK TV game show Countdown. In the TV version, contestants play individually …

  • ACCU C++ Countdown Pub Quiz

    The ACCU conference is one of the highlights of my year. I ran a brand new session, a C++ Pub Quiz with an emphasis on fun and interaction, based loosely on the popular UK TV game show Countdown. In the TV version, contestants play individually …

  • Planet Code updates

    I maintain an unofficial aggregator of blogs by people who are involved with ACCU and things they might be interested in. It’s called Planet Code. Today I made it look slightly less ugly, and added several new blogs after attending the excellent ACCU C…

  • A story about magic and how we treat each other

    For a lightning talk at the ACCU Conference I wrote a little story: A story about magic and how we treat each other It describes one person’s journey towards realising that we need to act to be kind to each other, and not to expect it to happen automat…

  • Docker in Action

    is an excellent book by Jeff Nickoloff. As usual I’m going to quote from a few pages. The docker stop command tells the program with PID #1 in the container to halt. Like most Docker isolation features, you can optionally create containers …

  • Docker in Action

    is an excellent book by Jeff Nickoloff. As usual I’m going to quote from a few pages. The docker stop command tells the program with PID #1 in the container to halt. Like most Docker isolation features, you can optionally create containers …

  • Siddhartha

    is an excellent book by Herman Hesse. As usual I’m going to quote from a few pages. He learned more from the river than Vasudeva could teach him. He learned from it continually. Above all, he learned from it how to listen, to listen with a st…

  • Siddhartha

    is an excellent book by Herman Hesse. As usual I’m going to quote from a few pages. He learned more from the river than Vasudeva could teach him. He learned from it continually. Above all, he learned from it how to listen, to listen with a st…

  • The Hidden Life of Trees

    is an excellent book by Peter Wohlleben (isbn 1771642483). As usual I’m going to quote from a few pages. In forked trees, at a certain point, two main shoots form, they continue to grow alongside each other. Each side of the fork creates it…

  • The Hidden Life of Trees

    is an excellent book by Peter Wohlleben (isbn 1771642483). As usual I’m going to quote from a few pages. In forked trees, at a certain point, two main shoots form, they continue to grow alongside each other. Each side of the fork creates it…

  • Annual cost of clean water for every human

    According to a 2010 WHO-backed study the cost of safe water for every human would be about 10 billion US dollars per year. The UK government revenue for 2010-2011 was about 639 billion US dollars. I would vote for a political party proposing to raise …

  • Iterating over the lines of a file in Java

    If you’re trying to write a standard command-line tool in Java you are going to experience pain. In Python, if we want to do something with each line on input to your program, we can do something like: import sys for ln in sys.stdin: print(ln) # (…

  • the DevOps Handbook

    is an excellent book by Gene Kim, Jez Humble, Patrick Debois, and John Willis (isbn 978-1-942788-00-3). As usual I’m going to quote from a few pages. Make infrastructure easier to rebuild than to repair. The average age of a Netflix AWS ins…

  • the DevOps Handbook

    is an excellent book by Gene Kim, Jez Humble, Patrick Debois, and John Willis (isbn 978-1-942788-00-3). As usual I’m going to quote from a few pages. Make infrastructure easier to rebuild than to repair. The average age of a Netflix AWS ins…

  • Raspberry Pi Jam “Chaos Car!”

    Raspberry Pi 1 + battery pack + Bluetooth USB dongle + i-racer bluetooth car + Raspberry Pi camera + some Python code + loads of sellotape = Chaos car! Here’s the code: #!/usr/bin/env python2 import os import random import bluetooth import sys import…

  • Catch Up

    It’s been just over six years since I first announced Catch to the world as a brand new C++ test framework! In that time it has matured to the point that it can take on the heavyweights – while still staying true to its original goals of being light…

  • Catch Up

    It’s been just over six years since I first announced Catch to the world as a brand new C++ test framework! In that time it has matured to the point that it can take on the heavyweights – while still staying true to its original goals of being light…

  • NDC Does C++ Countdown!

    It was my pleasure to run a small workshop style session at the excellent NDC-London conference. I ran a fun C++ game which parodies the popular UK TV gameshow Countdown. In the TV version contestants take turns picking 9 random vowels/consonants…

  • NDC Does C++ Countdown!

    It was my pleasure to run a small workshop style session at the excellent NDC-London conference. I ran a fun C++ game which parodies the popular UK TV gameshow Countdown. In the TV version contestants take turns picking 9 random vowels/consonants…

  • Automated UI tests on Android

    I recently fought the Android emulator a lot to get my UI tests to run automatically during the build of Rabbit Escape, so I thought I’d better write down what I did before I forget. I already have tests that drive the Android UI (see e.g. SmokeTest.ja…

  • Submitting a package to F-Droid

    Here’s what I needed to get a dev environment for F-Droid up and running on Ubuntu 16.10, using F-Droid server version 0.7.0 (commit id 8147f9235), so that I could submit a package for inclusion in the F-Droid repository. Doing this is apparently the b…

  • Resources for year 6 teachers on coding and programming

    I have been introducing some year 6 (UK) teachers to coding by showing them how to lay out a simple web page by writing HTML. I promised I would find some links to resources for them, so here it is: HTML and JavaScript My examples of how to write HTML …

  • Debugging AWS Lambda functions locally using VS Code and lambda-local

    I’ve just started using AWS Lambda with node.js. I was able to develop these locally using the lambda-local npm package, e.g. with node.js installed (via brew) and lambda-local installed (using npm) then the following “hello, world” example i…

  • Debugging AWS Lambda functions locally using VS Code and lambda-local

    I’ve just started using AWS Lambda with node.js. I was able to develop these locally using the lambda-local npm package, e.g. with node.js installed (via brew) and lambda-local installed (using npm) then the following “hello, world” example i…

  • Setting up a sane Maven project

    Today I have spent hours trying to get wrangle Maven into letting me set up a sane Java project. The hardest parts were enforcing warnings-as-errors, and getting Maven to shut up a bit. Some code that warns My first problem was writing some Java code t…

  • the design and implementation of cyber-dojo

    At the excellent Agile on the Beach conference in Cornwall I did a presentation outlining some of the history, design and implementation of cyber-dojo. The video has just gone live on youtube.

  • the design and implementation of cyber-dojo

    At the excellent Agile on the Beach conference in Cornwall I did a presentation outlining some of the history, design and implementation of cyber-dojo. The video has just gone live on youtube.

  • Writing a unit test in Elm

    Series: Snake in Elm, Elm makes me happy, Elm Basics, Elm Unit Test, Elm JSON I’ve been having fun with Elm programming recently. Elm is a replacement for JavaScript that is pure functional and highly practical. Here’s how to go from nothing installed …

  • Speaking: ADC 2016

    I’ll be speaking at ADC 2016 (Audio Developer Conference), the successor to 2015’s JUCE Summit in London on the 4th November. My talk is called The Golden Rules of audio programming (and how to break them). The synopsis is: Audio programming req…

  • Speaking: ADC 2016

    I’ll be speaking at ADC 2016 (Audio Developer Conference), the successor to 2015’s JUCE Summit in London on the 4th November. My talk is called The Golden Rules of audio programming (and how to break them). The synopsis is: Audio programming req…

  • Continuous Delivery

    Is an excellent book by Jez Humble and Dave Farley. As usual I’m going to quote from a few pages… Software delivers no value until it is in the hands of its users. The pattern that is central to this book is the deployment pipeline. It sho…

  • Continuous Delivery

    Is an excellent book by Jez Humble and Dave Farley. As usual I’m going to quote from a few pages… Software delivers no value until it is in the hands of its users. The pattern that is central to this book is the deployment pipeline. It sho…

  • Building Microservices

    Is an excellent book by Sam Newman. As usual I’m going to quote from a few pages… Because microservices are primarily modeled around business domains, they avoid the problems of traditional tiered architectures. Microservices should cleanl…

  • Building Microservices

    Is an excellent book by Sam Newman. As usual I’m going to quote from a few pages… Because microservices are primarily modeled around business domains, they avoid the problems of traditional tiered architectures. Microservices should cleanl…

  • How to write a programming language – Part 3, The Evaluator

    Series: Lexer, Parser, Evaluator. Finally, we get onto the actual magic of the little language I wrote (Cell) – the evaluator, which takes in syntax trees and finds their real value, in the context of the “environment”: the symbols that are defined aro…

  • Basic Haskell project setup (unit tests, code, formatting)

    To start a programming project, we need to be able to build, format code, and run unit tests. Here’s what I have found makes a sensible starting point for a Haskell project. Full code: hunit-example. To build and run tests, just do:make setup make test…

  • How to write a programming language – Part 2, The Parser

    Series: Lexer, Parser, Evaluator My little programming language, Cell (Cell Elementary Learning Language) is designed to be simple. I want to use it to explain how to write a programming language. The parser is only 81 lines long, so hopefully it’s not…

  • Mousedown events delayed or sluggish on mobile

    I am learning about Elm and web apps by writing a little game called sootl. It’s all SVGs animated with requestAnimationFrame(), and you control your player by clicking or touch the screen. Everything seemed good on desktop browsers, but on mobile it t…

  • How to write a programming language – Part 1, The Lexer

    Series: Lexer, Parser, Evaluator I wrote a little programming language, Cell which is supposed to be simple enough to help explain how a programming language works. Here’s the explanation of the lexer, which is the first part of a compiler or interpret…

  • Simple example of Netty 4 usage

    I feel the title of this post over-promises, since I was not able to make an example that seemed simple to me. Anyway, here is a near-minimal example of how to use Netty to make a server that shouts back at you whatever you say: NettyExample.java:impor…

  • Interview: Make Software Better Magazine

    Fog Creek’s Make Software Better Magazine (Volume 1) includes an interview with me called “Go Beyond Code to Become a Better Programmer”.” You can download it for free from https://blog.fogcreek.com/make-better-software-magazine/. …

  • Interview: Make Software Better Magazine

    Fog Creek’s Make Software Better Magazine (Volume 1) includes an interview with me called “Go Beyond Code to Become a Better Programmer”.” You can download it for free from https://blog.fogcreek.com/make-better-software-magazine/. …

  • Elm resizeable SVG canvas filling the screen

    I am toying with writing an SVG-based game in (exciting-looking JavaScript-replacement) Elm, and I wanted an SVG that filled the whole screen and resized when the screen resized. I found it harder than I expected, so here is what I came up with for you…

  • Ambiguous names in Java due to non-normalised unicode – but all OK in Python

    In Java and several other languages, identifiers (e.g. method names) are allowed to contain unicode characters. Unfortunately, some combinations of unicode characters are logically identical. For example, á (one character: Latin Small Letter a with Ac…

  • Gracefully shutting down Firefox, to avoid the crash/session dialog

    I normally have several Firefox profiles open, and when I log out without closing the Firefox windows I get the “session restore” dialog on my next login. This is because of Bug 336193 which says that Firefox should shut down gracefully when it receive…

  • Snake in Python 3 + Qt 5

    Series: Groovy, Ruby, BASIC, Dart, Elm, Python3+Qt5 I’m writing the game Snake in lots of programming languages, for fun, and to try out new languages. Python 3 broke compatibility to fix some mistakes – was it worth it? Qt 5 continues to offer more an…

  • ACCU Conference 2016

    In late April we exhibited at the ACCU Conference (#accuconf), which in many ways is our conference home. The first time we went was all the way back in 2007, and believe it or not we’ve not missed a single year since then. The conference is a great ev…

  • ACCU Conference 2016

    In late April we exhibited at the ACCU Conference (#accuconf), which in many ways is our conference home. The first time we went was all the way back in 2007, and believe it or not we’ve not missed a single year since then. The conference is a great ev…