Archive for the ‘ Code ’ Category

Object Oriented musings

I’ve been in software development for a long time and most of that time has been spent using object oriented languages, including C++, Java and C#. I’ve made plenty of mistakes along the way and I think I have a good guide how to and how not to use some aspects of OO.

A classic OO introductory example I’ve seen is as follows:

class Car{
    const double ACCEL = 1.5;
    double Speed;
 
    void Accelerate(){
        Speed += ACCEL;
    }
}

All makes sense, then I want to add some “real world” logic involving things external to the car. Like, what if the car is going up hill, is running into something or on a slippy surface? I would inevitably end up passing global state to the “Accelerate” method:

class Car{
    const double ACCEL = 1.5;
    double Speed;
 
    void Accelerate(World world){
        // Funky logic involving the World
    }
}

At this point, things are getting confusing because logic is spread between the World and the Car. This gets even worse if inheritance is involved. Imagine a “Vehicle” base class that “Car” inherits from, then a “Motorbike” class that has slightly different acceleration logic involving wheelies etc. This could be sold as “extensible” because I can drop in some other kind of  vehicle without tinkering with the World class. However, this is a maintainability disaster with logic spread out everywhere and logical problems with ordering of calls (think 2 cars accelerating into the path of each other). This example may seem abit contrived, but I’ve seen numerous examples of a “Save” or “Draw” method on a class that embodies the thing to be saved or drawn. In these situations it’s actually worse. What happens if I want to use a different database or rendering engine?

I’ve found that the only way to avoid madness is to ensure that logic is grouped together aggressively. So in our simple example, you’d end up with something like this:

class World{
    List<Vehicle> Vehicles;
 
    void RunWorld(double tick){
        foreach(var vehicle in Vehicles){
            // Common logic incl crash detection
            if(vehicle is a Motorbike){
                // Wheelie logic
            }
        }
    }
}

Now, you might think that this is just moving the logic around. However, I’ve noticed that all the classes like “World” (or “Database” or “RenderingEngine”) are essentially either static, singletons or contexts that are used against static / singleton type classes. These are ideal candidates for an interface and some sort of IoC framework to load in the implementation at runtime.

Heuristics

As a form of guidance, I’ve come up with a set of heuristics to follow when defining a class model. . but it’s a decent starting point.

  1. Identify if a class is one that is static, singleton or a context / wrapper (e.g: Database, Graphics System or World) / wrapper or whether it’s one that carries data (Record, Car or Game Character).
  2. If it’s the former (maybe call these “modules”, borrowed from Javascript?), this is a good place to centralise “business” logic. There is usually little scope for inheritance in these type of classes and they end up implementing a collection of interfaces.
  3. If it’s the latter,
    • Limit methods to only those that affect the data within the object. So Sort(), Validate(), AddX() should all be ok.
    • Drive behaviour from data (via the  “modules”), not methods on the objects.
    • Subclass for common data (maybe all records have a timestamp?) not to add logic in methods.

There will of course be exceptions. For example, I’ve been part of developing an expert system and validation classes. In these cases the logic was intentionally tied to the data carrying objects to that they could be built into a tree (using the composite pattern) and chained (Jquery style) respectively. These cases worked really well, and at least armed with the heuristics described, we could consciously weigh up a different approach.

 

 

Advertisements

JQuery.obj() – Converting inputs to a javascript object

For a while now I’ve been using a JQuery extension that takes selected inputs (and dropdowns and textareas) or inputs contained in the selection and converts them into a javascript object ready for submission with an Ajax post as JSON.

The need for something like this came about when we found that the data that needed to be submitted didn’t neatly fit on a form. An example is where the data was across multiple tabs and the “submit” button needed to be on the first tab.

Now, we have the ability to use the following JQuery:

var newObj = $('#tab1,#tab2,#tab3').obj();

to grab all the inputs into an object, which can then be manipulated before submission. Inputs of type “button” and anything you mark with the class “ignore” won’t be pulled into the object.

The construction of the object is based on the names of the inputs, and follows the dot and bracket notation used in naming .Net MVC, so the following inputs:

<input name="m1.Sub1.Name" value="Anne" />
<input name="m1.Sub1.Age" value="22" />
<input name="m1.Sub1.Numbers[0]" value="1" />
<input name="m1.Sub1.Numbers[1]" value="2" />

will get converted to:

{ m1: { Sub1: { Name: "Anne", Age: "22", Numbers: [ "1", "2" ] } } }

unless of course the “preserveNaming” option is passed in and set to true. In which case the object will be flat, and you’ll get names like “m1.Sub1.Numbers[0]”. Using something like json2, you can stringify this and submit it in an ajax call. It plays very nicely with .Net MVC.

It’s worth pointing out that the JQuery selector can incorporate controls and containers, so you can do something like this:

var newObj = $('#myForm1,#myForm2,#aDropdown').obj({ preserveNaming: true });

and the “newObj” will incorporate all the bits.

So, onto the code, enjoy!:


// Use this jquery extension to convert the inputs, dropdowns & textareas on the selected node(s) into a javascript object
/// options:
///     preserveNaming: default = false - whether the function preserves the names of controls, or splits on .s an []s
(function ($) {

    var _options;

    $.fn.obj = function (options) {

        _options = options || {};

        var obj = {};

        // List of control names that have been seen.
        var namesSeen = [];

        this.each(function (index) {

            var selector = $(this);

            var jqSelector;
            if (selector.is('input') || selector.is('select') || selector.is('textarea')) {
                // This is a control with no inner html
                jqSelector = selector;
            } else {
                //This is a container
                jqSelector = $('input,select,textarea', selector);
            }

            // inputs
            jqSelector.each(function (index) {
                var nodeToCopy = $(this);

                // do not process controls with the ignore class
                // do not process buttons
                if (nodeToCopy.hasClass('ignore') || nodeToCopy.attr('type') == 'button') {
                    return;
                }

                var name = nodeToCopy.attr('name');
                if (!name || name.length == 0) return; // Don't bother with inputs with no names

                // Only deal with inputs we haven't seen yet
                if (!namesSeen[name]) {

                    var value;

                    if (nodeToCopy.attr('type') == 'checkbox') {
                        if (nodeToCopy.is(':checked')) {
                            value = true;
                        } else {
                            value = false;
                        }
                    } else if (nodeToCopy.attr('type') == 'radio') {
                        if (nodeToCopy.is(':checked')) {
                            value = nodeToCopy.val();
                        } else {
                            // pretend we haven't seen un-selected radio buttons so we end up with the selected one
                            return;
                        }
                    } else {
                        value = nodeToCopy.val();
                    }

                    namesSeen[name] = true;

                    addValue(obj, name, value);
                }
            });
        }); // each selector

        return obj;
    };

    var addValue = function (obj, name, value) {

        if (_options.preserveNaming) {
            obj[name] = value;
        } else {
            var parts = name.split('.');
            parts.reverse(); // must reverse to use the pop() as we will be going root to leaf.

            add(obj, parts, value); // recursevely add name parts to existing object
        }
    }

    var add = function (curObj, remainingNames, value) {

        var curName = remainingNames.pop();
        if (!curName || curName.length == 0) return; // Don't bother with blank name

        var arrayData = null;

        // see if the name is a list in the form of AAA[NNN]
        var match = new RegExp("(.+)\\[([0-9]*)\\]").exec(curName);
        if ((match !== null) && (match.length == 3)) {
            var arrayData = { arrName: match[1], arrIndex: match[2] };

            // Make the current object and name be the array and the index of the array respectively
            // Equivalent to calling curObj[arrayData.arrName][arrIndex] in the section below
            if (curObj[arrayData.arrName] === undefined) curObj[arrayData.arrName] = [];
            curObj = curObj[arrayData.arrName];
            curName = arrayData.arrIndex;
        }

        if (remainingNames.length == 0) {
            // This is the leaf node
            // If not an array value, just place it on the leaf object.
            curObj[curName] = value;
        } else {
            // Not the leaf, have to extend existing object
            if (curObj[curName] === undefined) curObj[curName] = {};
            add(curObj[curName], remainingNames, value);
        }
    }

})(jQuery);

Go programming language – a first impression – 1

I’ve been feeling I should try a new software development language for a while now, to see what life is like outside C++, C#, Java and Javascript. I had a toss up between Clojure, F# and Go. I discounted Clojure because it compiles to Java byte code and I want to stay out of the Oracle ecosystem. I slipped into Go over F# because I could do the Go example without having to get a Visual Studio add on (I know I could do F# from the command line, but I couldn’t be bothered) and the first example worked first time.

I’ve run though the tour and had a play with a few examples. I’m going to reserve judgement on the language itself until I’ve run though Effective Go and fully understood some of the concepts I think are important. In general the language seems very clean and concise (especially compared to Java). The usual problem exists that the main work would be learning all the new libraries and ways of doing things, if I actually had to do something complex, I’d fall back on a language where I knew where to find things (maybe F# would have been better in this regard) because the risk would be much lower.

Something that I think will limit the adoption of Go is the fact that it’s really hard to search for jobs in it (even on Google). I was having a look to see if there is any uptake of it, but trying to search for “go” on JobServe gets you a load of posts requiring “go getters” which is really not what I’m after. If you use “go language” or even “go programming language” then your targeted as a go getting translator! I don’t know if there’s some code in the industry to get round this, like calling it “Google_go”, but until I find the key, even if it’s ace, I’ll never be able to find a job or hire anyone.

Anyway, next time a real bash at the pros and cons.

Pair consulting

As a twist on pair programming, today we tried some pair consulting. We were writing a document that involved the combination of process (my colleagues area of knowledge) with data that supported the process (my area).

This actually worked really well, with us swapping the keyboard when we got stuck trying to explain a concept. The other person would then look on to make sure what the writer was writing made sense.

We really surprised the project manager in how quickly we managed to knock the document out and it was approved first time.

I think we’ll try that again. Maybe one day I’ll try it with code!

To GC or not to GC – and other programming language thoughts

Having read the following article about programming language sacred cows, I was reminded of being annoyed in the past.

I can really sympathise with points 7 and 8 (Compiled vs Interpreted. Static vs Dynamic & Garbage collection is bad).

It’s nice to be able to chuck a Java/C# “executable” to anyone and have a fairly good idea it will work, but there are many times when I know exactly where the “executable” is going.. My production environment! Why the hell can’t I just compile it there and then with all the optimisations in place. I know there are lots of people who say JIT compilers run just as quick etc, but there is inevitably that “first time” lag, why do I need to suffer that when I don’t need to.

Having spent a day twonking about with strings in C++, I can remember why everyone gave a sigh of relief when string manipulation was made so easy in Java (I know you could get the C++ boost libraries and have similar functionality, but I didn’t know about that at the time, which is kind of the point). When I want to concatenate a few strings together and write out the result, I really don’t want to have to deal with memory allocation and the fear of the impossible to find memory leak. However, if I’m making an ant simulation where there are thousands of entities being created and destroyed, I want really tight control of when they go away. I don’t want the dead ants to hang around just because I once referenced a parameter in the wrong place (JavaScript, you know who you are).

The other points, while I can see the advantage of not storing things as text, trying to get people to standardise around another format. It’s bad enough with text, with my .Net code, I feel rather locked into Windows (I know there’s Mono) because the code works so tightly with Visual Studio. I think maybe the popularity of JavaScript comes from the fact that you just throw around plain text, so you can edit it on your mac or Windows laptop with equal ease, it’s the shared execution environment that provides the unification.

 

No code!

Having started this blog, I’ve now landed myself a role that involves no code!

I am helping to develop data exchange standards for the Department for Education (and everyone involved in learning in the UK).

After the initial panic during the first few weeks that I wasn’t “producing” anything, I’m now kind of enjoying the break from design/development/testing for something more abstract.

I am glad I’ll have the day job to go back to eventually, I only hope I’m not too rusty!

In the meantime, I’ll be trying abit of HTML5 development on the train, 3G signal permitting.

Excel Array Formulas

I just found a feature of Excel that I’ve never heard of before: Array Formulas!

Essentially, you can use ranges in criteria of functions such as COUNTIF. Full details available: http://www.cpearson.com/excel/ArrayFormulas.aspx

I used it to find the number of distinct values in a column (http://www.cpearson.com/excel/Duplicates.aspx).

All you need in the formula is:

{=SUM(1/COUNTIF(B2:B11,B2:B11))}

The curly braces around the formula make this an array formula.

I reckon I could do some pretty fancy processing using this in the future.. Not sure what though.