Monday, September 22, 2008

Darren on Flex: Overloading the Constructor - Revisted

This is just a follow up to Overloading the Constructor to elaborate on my response to a comment made by Ben. I show how to:
  • Hide the public constructor by hiding the implementation class.
  • Expose the class via an interface.
  • Provide arbitrary factory methods in a factory class.

The Interface

//example\IPerson.as
package example {
    public interface IPerson {
        function get fullName():String
    }
}

The Factory and Implementation Class

//example\PersonFactory.as
package example {
    public class PersonFactory {  
        public function newPersonWithFirstName(firstName:String):Person {
            return new Person({firstName: firstName});
        }  
        
        public function newPersonWithLastName(lastName:String):Person {
            return new Person({lastName: lastName});
        }  
        
        public function newPersonWithFirstAndLastName(firstName:String, lastName:String):Person {
            return new Person({firstName: firstName, lastName: lastName});
        }  
        
        public function someDudeWithOnlyMiddleNames(... middleNames):Person {
            return new Person({middleNames: middleNames});
        }
        
        public function andTheFullShaBang(firstName:String, lastName:String, ... middleNames):Person {
            return new Person({firstName: firstName, middleNames: middleNames, lastName: lastName});
        }
    }
}

import example.IPerson;

class Person implements IPerson {
    private var firstName:String;
    private var lastName:String;
    private var middleNames:Array;
    
    public function get fullName():String {
        return firstName + (middleNames ? " " + middleNames.join(" ") + " ": " ") + lastName;
    }
    
    public function Person(params:Object) {
        for (var property:String in params) {
            this[property] = params[property];
        }
    }
}  

The FlexUnit Test (for good measure)

//example\PersonFactoryTest .as
package example {
    import flexunit.framework.TestCase;

    public class PersonFactoryTest extends TestCase {
        public function PersonFactoryTest(methodName:String=null) {
            super(methodName);
        }
        
        public function testCreatingBenjaminNortier():void {
            var factory:PersonFactory = new PersonFactory();
            
            var ben:IPerson = factory.newPersonWithFirstAndLastName("Benjamin", "Nortier");
            
            assertEquals("Benjamin Nortier", ben.fullName);
        }
        
        public function testCreating21stCenturyCodeWorks21ccwblogspotcomBenjaminNortierWith():void {
            var factory:PersonFactory = new PersonFactory();
            
            var ben:IPerson = factory.andTheFullShaBang("Benjamin", "Nortier", "21st Century Code Works", "21ccw.blogspot.com");
            
            assertEquals("Benjamin 21st Century Code Works 21ccw.blogspot.com Nortier", ben.fullName);
        }
    }
}
... and the results snapshot: Cheers

Sunday, September 21, 2008

Darren on Flex: Overloading the Constructor

Prologue

Back on the 3rd September 2008 some of my colleagues at Zuhlke unvailed StuffPlanner at a BCS SPA evening talk. StuffPlanner is an Agile estimation and planning tool with an opinion. Recently, I found myself ramping up my involvement in the development of StuffPlanner. Consequently, I have resumed my study and assessment of the technologies involved and their corresponding conventions and recommended usage. Henceforth, I blog briefly on the topic of constructor overloading.

Wait! ActionScript Does Not Support Overloading!

No, it doesn't... but please, keep reading. Sometime this week I received a communicade from a local colleague who is doing some pretty interesting work on the continent on the Flex platform. He asked me how to, or rather can you, overload a constructor. We (the locals) had (less) recently had a debate about this after realising that AS3 (ActionScript 3) does not support overloading, so I was primed to make a suitable response.

Default Parameters

Basically, in lieu of overloading AS3 gives you default parameters
public function DefaultValueExample(required:String, andTheCommonCase:String="DEFAULT") {
    if (!required) {
        throw new ArgumentError("You must specify required arguments");
    }

    // construct something with the required value andTheCommonCase
} 
Obviously the API designer needs to know the complete set of parameters, that is, those that must be specified and those that can have a default values. So far my references to the common-case are just to the concept of it, a place holder. The common-case represents the design challenge in using this language feature while, simultaneously, it represents the design limitation; the common-case(s) is prescribed to all the API clients irrespective of client needs. However, in practice the common-case is not a difficult trade-off to figure out and tends to be only a minor inconvenience. For example, in my experience, such cases tend to crop up during unit testing, which I anticipate will be less of a problem with TDD (yes, I am still homing my skills with TDD on Flex/AS3).

Variable Arguments

It may also be useful to use varargs to replace constructor overloading.
public function VarArgExample(... args) {
    for each (var arg:* in args) {
        // process arg...
    }
    //... then do construction
}
I reckon this has less application than default parameters as it only makes-sense/works when the (signature of the) things you are using during construction have parameters of no-type (* or Object) or a common super-type. Then you can either leverage duck-typing or polymorphism, respectively, to do smart things, which I won't discuss here.

The Factory Pattern

Oh yes, that old gem! I am a growing fan of using intention revealing names for variables and methods. It is perhaps a more common/old practice for variables (although you'd be surprised, even today), where variables are named to reveal the state it represents and/or for what it could be used to achieve. With methods, on the other hand, I sense a stigma, a taboo, in using this technique in any progressive way. Thus I feel there is a general hesitance to use this practice, as if it would imply some mediocrity in the coder's skill at writing good code. I do feel TDD development has gone some way to alleviate this, specifically, where test method names describe the example situation being tested; this some how seems more socially acceptable. And, while I'm at it, I'd like to suggest that this technique encourages you to write more cohesive methods w.r.t. what an object's methods do to contribute to the object's overall task. The reason I discuss this here (I did not plan to get into it that much) is because AS3 does not allow you to reuse method names i.e. no overloading. So rather than settling for less, why not combine intention revealing names with the Factory pattern. Now I have said it, I bet you are realizing you do this all the time (I anticipate) during testing, where you might have refactored some creational code for some objects used commonly in your tests. So what if we drop the usual XxxFactory's getInstance(), newInstances() and createInstance() cruft and adopt something more revealing?
//Person.as
public class Person {
    public function Person(firstName:String="", lastName:String="", ... middleNames) {
        // do somthing
    }  
}

//PersonFactory.as
public class PersonFactory {
    public function newPersonWithFirstName(firstname:String):Person { return new Person(firstname); }
    public function newPersonWithLastName(lastname:String):Person { return new Person(null, lastname); } // A little inconvenient
    public function newPersonWithFirstAndLastName(firstname:String, lastname:String):Person { return new Person(firstname, lastname); }
}
So what's the runtime overhead? Just the extra PersonFactory class, where the would-be constructor overloads are replaced with simple methods; let's face it, negligible. And the API overhead? Well interestingly, a problem has emerged and a pattern has been used to solve it. Furthermore, our intention revealing names should improve readability of the code and identifies a good place to refactor/relocate creational code that gets used over and over again... like, for instance, in your tests. Comments welcome.

Saturday, September 20, 2008

Darren on Flex: New FlexUnit 0.9 Out!

FlexUnit-0.9 has been released by Adobe Cosulting. I believe this is the first release since the projects move from Google Code to Adobe open Source. I have browsed the source code and nothing seems to have changed; obviously, community, please can correct me if I am wrong. There is still a lingering reference to the flexunit.extensions.TestSetup class which is still nowhere to be seen. Indeed I discovered the update while trying to find the standard approach to test-suite setup and teardown; subquently deciding it is is not the solution to my problem anyway. The most significant change, if only change, is the UI. We have:
  • An active search filter that narrows down the displayed list of test methods, matching on test (method) name.
  • A combobox with three result options: All Results, Empty Tests and Failures & errors; this replaces the tabbed view in the old version.
  • A red cross or green tick indicating the obvious, with a fat red cross or green tick to indicate overall (test-suite) pass or failure; it's a sad day - we've lost our beloved red-bar-green-bar.
  • In the event of an error/failure, improved diagnostic feedback. Just the other day I was getting frustrated with the old version, scrolling through the stack trace to find what class and which line of code I wrote (as opposed to FlexUnit code) that caused the breakage; well, it seems I won't have to suffer that anymore.
Overall, it just looks a lot more charming. Check it out, literally.

Tuesday, July 08, 2008

See, Agile Isn't Just Good Sense, It's Common Sense

In my view, Agile does not claim ownership of any of it's principles, practices or techniques; rather it advocates doing certain things to help make improvements. So it follows that a lot of this stuff can be applied in situations other than cutting-code or delivering software. That said, the findings in the linked article come at no surprise. Agile treats good, continuous communication as a core axiom. The discovery of this importance in another (albeit undisclosed, yet seemingly IT related) field suggests the good sense in Agile is common sense for EVERYONE.

Sunday, July 06, 2008

Convention Over Configuration, Are We Going Round in Cirlces?

Convention-over-configuration is becoming increasingly popular as a term of reference to that which is the design or usability principle. I speculate that it is picking up momentum nowadays due to the Jedi-like Force that is Rails, a bunch of hokery-pokery, voodoo and black-magic. What strikes me is that not so long ago there was similar advocation of declaritive-over-imperative, presumably for language paradigms. It therefore seems to me that we are going in cirlces: I have seen the Ruby/Rails guys I work with wave their magic-wands and it sure as hell looks like a bunch of imperative command-line stuff to me. But perhaps, generally speaking, I just have the wrong perspective, a two-dimensional perspective. What if we look at this in three-dimensions and shift the metaphor to a cone rather than a circle. And with each iteration we move toward the apex; we move up a meta-level in search for the ultimate abstraction, whatever that maybe. So what is next? Are we due a declarative-renaissance? Kind-of feels too soon for that, ay? As well as Ruby on Rails, my colleagues and I are developing Flex apps. I mention this as Flex's MXML is the closest thing I can think of, off the top of my head, that is declarative (there is Maven, but let's not go there). If we limit the space for things to consider to UI frameworks, MXML trumps all others. In fact (or at least in my opinion) it is, by design and intent, a deliberate declarative abstraction on ActionScript. Somehow this example does not quite fit the bill. It may epitomise declaritive-over-imperative but I feel it causes too little displacement, or rather too litle attention relative to Rails. It does not really exemplify something so grand as the community chorusing an opinion [as if it really ever does]. Perhaps my exploration of this idea is going to far ahead. MXML and whatever are likely residual from the last wave-of-declarative. Incidentally, I think it is safe to say we are entrenched in a configuration mess. However, continuing with the metaphor: While rising to the top of the cone, our radius and thus space for improvement is shrinking. If what we are doing is layering abstraction on absraction to make what we have been doing (OOA/D/P) easier, maybe it is time to change what we have been doing. Perhaps get behind the functional-renaissance; perhaps adopt Erlang. Perhaps we will have a new cone for what we would be doing, thus a new base and therein a greater radius to improve the common practice of what would be done.

Epilogue

So this is what happens when I sit and explore a wild thought in isolation. What I have articualted I see is tangential in places, but I hope not (too) incoherent; it could be a bunch of BS or maybe there is some substance there. In anycase comments are welcome, validating or invalidating.

Tuesday, April 01, 2008

Darren on Flex: The Boolean Value of Objects in Logical Expressions

Here's another one for the Flex (ActionScript) programmers out there. I come from the Java world and my first encounter with ActionScript has been through Flex - well actually, I dabbled in a bit of AS back at uni when I was playing with tweening and animations. Anyway, if you are like me in that respect, then you may not be familiar with all the language constructs, keywords and semantics there in. One thing, I have just discovered, are that 'non-boolean' variables have a boolean value that are evaluated when used in a logical expression. They go something like this (assigned object values):
  • null = false
  • 0 (zero) = false
  • false = false (...really!)
  • eveything else = true (... as far as I know)
Now there are a few cool things about this: Firstly, when you build up a logical expression, each object is evaluted for its boolean value prior to application of any logical operator. Based on the rules above, the logical expression will evaluate to true or false. It is my belief that this boolean value is obtained by coersion, from evaluating the logical expression i.e. in accordance with the rules above. So you maybe wondering what it is that's being coerced and from what? It seems the value that is coerced is the last evaluated object that determined the outcome of the expression. This is best explained through examples:
  • "aaa" && "aab" && "aac" = "aac"
  • "aaa" && null && "aac" = null
  • "aaa" && "aab" && 0 = 0
  • "aab" < "aac" = true
  • "aab" < "aaa" = false
  • 1 && 2 && 3 && 4 && 5 = 5
  • 0 && 1 && 2 && 3 && 4 = 0
Notice the lexical evalution. Next, it should be obvious by now that you can use logical expressions built in this way in decision constructs (if, for, while etc.) yet still assign them to variables of non-boolean type. For example:
    public function someMethod(... params):void
    {
        someInstanceArray = params || [];
    }
Before:
    public function someMethod(... params):void
    {
        if (params != null && params.length > 0)
        {
            // You can now safely access params[0] now
            ...           
        }
    }
After:
    public function someMethod(... params):void
    {
        if (params && params.length)
        {
            // You can now safely access params[0] now
            ...
        }
    }
Even After That:
    public function someMethod(... params):void
    {
        someObject = params && params.length && params[0] || new SomeThingYouNeed();
    }
Pretty cool ay. One thing that confused me (and thus descoped from understanding) was the following tests:
    trace("a" == true, " " == true, "" == true);
    trace("a" == false, " " == false, "" == false);
    trace(" " && "a", '" " && "a"');
    trace("" && "a", '"" && "a"');
which yields
false false false
false true true
a " " && "a"
 "" && "a"
Strange uh. I suspect other languages of the dynamic variety support these semantics e.g. Python; would be nice in Java. Comments welcome.

Sunday, March 23, 2008

Darren on Flex: Binding Expression Clash With HTML Entity-Reference Delimeter

You fellow Flex programmers should know all about the handy binding notation provided as a language construct in MXML. For those that don't know, it makes short work of event-wiring; forget implementing interfaces and defining handlers - just bind it. With binding in mind, recently I tried to bind to the AND logical result but received an error in FB3. This highlights a feature of MXML, that is, the overlap of the symbol/name/token/something-space of embedded AS code and that of HTML/XML. To be clear, I am no talking about (instance) variable namespaces or scopes, Flex handles this seamlessly; what I am talking about is the names for constructs (or maybe it's syntax tokens) in those respective languages. For example see the following code:
<application mx="http://www.adobe.com/2006/mxml" model="com.zuhlke.tutorial.hibernate.model.*" creationcomplete="eventDS.fill(events, 'all.events', [])" layout="vertical">

...

</application>
In this snippet we routinely assign an expression, in this case a function call, to be evaluated in response to the creationComplete event. Notice that to pass a String (i.e. 'all.events') as an argument we have to switch between quoting characters to maintain valid XML - not adding anything new here, this trick is age old. The following example demonstrates what I was trying to do, as described above:
<mx:TextInput id="eventTitle" width="100%" />
<mx:DateField id="eventDate" width="100%" />
...

<mx:Button id="add"  label="Add..." enabled="{eventTitle.text != '' && eventDate.text != ''}" click="addHandler()" />
This code will not compile in FB3 as the && ie. logical AND operator in the binding expression for the Button.enabled property clash with the entity-reference language construct for XML notation. So with knowledge converting between different logical expressions in the same equivalance class, we can re-write the binding expression such that the compiler is kept happy:
<mx:TextInput id="eventTitle" width="100%" />
<mx:DateField id="eventDate" width="100%" />
...

<mx:Button id="add"  label="Add..." enabled="{!(eventTitle.text == '' || eventDate.text == '')}" click="addHandler()" />
Now this is really a matter of taste; you can of course use the following instead:
<mx:TextInput id="eventTitle" width="100%" />
<mx:DateField id="eventDate" width="100%" />
...

<mx:Button id="add"  label="Add..." enabled="{isEnabled(eventTitle.text, eventDate.text)}" click="addHandler()" />
where a function with the signature isEnabled(title:String, date:String):Boolean does the job. Note: it seemed necessary to pass in the text properties of the TextInput and DateField components, I suspect because these are bindable properties, where the components themselves (in their context) perhaps are not.

Thursday, March 20, 2008

What's In The Name

Well here is my long awaited maiden blog (in-joke... on me). As a blog virgin I struggled to come up with a good name for my blog. I thought I'd dedicate this first blog to my thoughts and feelings behind 'It's Not Personal... Well , Maybe Just A Little Bit'.

Firstly, why this name? Not too long ago I found myself toing-and-froing with my company's IT support centre over some (unimportant) issue. This was flagged and raised with my line-manager who gave me some advice, '...take a different stance "It's Not Personal, It's Just Business", don't get so...' blah blah or words to that effect. BTW, Zuhlke IT support are great guys and gals and a pleasure to talk and work with, especially when it that means going to Switzerland, but mainly because they are just a nice bunch. I digress.

Even though I say, '... Well, Maybe Just A Little Bit', I should actually say a 'Huge Bit' - when is it not personal? One of the reasons I decided to work for Zuhlke is it's stance on Agile development. Admittedly on finishing my MSc I knew very little about Agile, TDD or even xUnit testing. In fact my first project for the company was largely a discovery of Agile. The problems found where Agile is not, as described in various texts on the subject, resonated a lot with me. My lasting impression of Agile is that it's a people process (if I can call it a process) much in the same way that software development is a people game. I advocate Agile because in my opinion, it is more humane: I don't want the stress of a defect surfacing the week before a release, when it is way too late to do anything (safely) about it; I don't want to work through the night - I've worked with a client who has done this, literally, to the early hours of the morning - because a defect was found in UAT one day and the release 'has to go ahead' the next day, sod that for a can of beans; I rather not give up my personal time that I'd never get back - I'd much rather go home and watch the next episode of East Enders or America's Next Top Model (or, obviously if I had my way, Top Gear).

Not so long ago I agreed to lead a project that involved flying to and from some other part of the UK. I ended up doing this for what turned out to be a few months; out Monday back Friday, typically. I was able and willing to do this as I am young, free and flexible. No, I'm not single, so yes that means 4 days (or nights rather), away somewhere in the UK that would otherwise be spent with my partner. Of course, there are loads of people doing this, sacrificing time with loved ones to benefit your employer and to get the job done. There is personal sacrifice in there and even though a good employer, like mine, explicitly appreciates such commitment, it is still as much personal for the individual as it is business.

Since leaving university, I have heard various arguments and views on why Java is crap or 'broken by design' or whatever, one such coming from my boss. Now being one of those apparently unfortunate mugs to be reared on Java (I have no problem with it BTW), I used to feel a bit disheartened, perhaps even morose at times, whenever I was subjected to these opinions. Why would that be ay? Maybe due to the emotional investment inherent in my choice to study Comp Sci as a degree for 3 years of my life, learning Java as a consequence and the need and investment made to be good at it to earn my 1st, not to mention the pride therein. And then there's those that so passionately fight the 'Ruby vs. Python' fight, although I haven't heard much of this recently. Then, there's VI vs. Emacs, Windows vs. Linux, Windows vs. Mac and on and on it goes. What's the difference between any of those and a good old Spurs vs. Arsenal battle. They are all laced with passion, personal and emotional investment. I used to work at Tottenham Hotspurs on match days, for 4 years; I remember a middle-aged/elderly couple who made the long trip from Canada once a year, every year, to see their beloved team play football - to them it was a matter of tradition.

If there are any grunts out there reading this blog... have you ever had your head bitten off after touching some code that wasn't yours? Well I have, without any bitterness or resentment. People can get very protective over their code. I imagine in changing someone's code you could be saying 'this is crap', 'what was this dude thinking', 'I have a better idea' or simply 'WTF!'. These are quite subjective or opinionated motives to do something. It could just be that you picked up a different 'How to write good software' book to the original/preceding programmer, thus possibly subcribing to a different philosophy, methodology or approach. I believe my opinion on personal investment in one's choices, as expressed above, also applies here.

Then there is job-snobbery, where there is a definately a difference between snobbery and pride. I remember the conversations back at university in the labs:

Monkey A:Have you applied to Merrill Lynch yet?
Monkey B:No, I'm still on my Goldman Sachs application, but I got in my app to Deutsche Bank before the dealine though.

If it weren't finance, it weren't nothing. Perhaps this is/was some status thing, which I suspect most of us are guilty of to some degree; a display of self-worth or self-esteem maybe.

I recently attended the SPA-2008 conference, which I found on the whole grossly dissatisfying. I did find interesting some of the talks including that given by Michael Feathers of Object Mentor. His talk entitled 'Big Ball of Money, Big Ball of Mud: Economics and Legacy Code' covered various interesting things. A couple of things in particular struck me as relevant to this blog post: He spoke about professionalism and invited the audience to offer definitions for the term. He commented that to be a professional, or at least to be really good at something, you really need to love it - while we don't normally see C++ programmers running around professing their love for their compiler (in honour of the only guy to put his hand up in the 'Awesome Acceptance Testing' session by Dan North and Joe Walnes), I totally agree; Michael also commented that, while it's becoming increasingly rear, some open-source projects in the past have been driven by one-man teams, for example Ghostscript developed solely by Peter Deutsch for 10 years and Emacs by Richard Stallman, both I imagine in parallel with paying work. Michael posed the question, "What codebase would you be willing to dedicate a significant portion of your life to?". Quite a personal question, eh?

Ultimately, I have seen fit to blog about this stuff as I feel tacitly (until now) passionate about it - so how could that not be personal.

Michael: My apologies if I have misquoted you - feel free to correct me. Comments welcome.
Edited: 2010/03/19 - I re-read this and laughed a lot... but cringed a whole lot too. So I fixed a few things, but left the essence of the blog intact, with my fresh out of uni outlook; It's still my truth, for the most part, however many years on.