Monday, 9 November 2009

Standard Method Name Verb Semantics

Something that I’ve always taken for granted when programming is that certain verbs imply certain behaviours. I thought it would be useful to find a set of these on the web and link to it on our development wiki, as although I think it is common sense to native speakers, that is not true of team members for which English is a second language. However I’m struggling to track one down. I’ve seen plenty of posts about the format of interface, class, method and variable names, but not one that attempts to list the expected semantics of the really common verbs we use like get, create and find. To date I’ve only come across the PowerShell documentation as they’ve always made a concerted effort to try and standardise both the format of their commands:- verb-followed-by-noun, and also the semantics of the most common verbs.

One other useful resource I discovered was on Ward Cunningham's Wiki. There is a fair bit of discussion about naming conventions (across the board, not just methods) culminating in a concept know as Language Orientated Programming. The Wiki also attempts to establish a lexicon of common terms based on some existing naming conventions, such as the ‘str’ prefix used in the C runtime library for all the narrow version C-style string manipulation functions. However there is a major bias towards abbreviations in the pages I read which is not what I’m looking for.

So, until I find that resource I’m going to present my own list of common method name verbs and describe what connotations each one conjures up in my mind:-

Create & Delete

These should be an easy ones :-) Creation is about making new things, commonly objects, and are often used to implement the Factory Method or Abstract Factory patterns. The objects they create may be fully constructed, but more often they are only default initialised and the caller has to perform further actions on it. A common example would be a factory function for creating database connections, where the connection still needs to be opened after creation. Common alternatives would be Allocate and Construct.

IDatabaseConnection connection = DatabaseFactory.CreateConnection(connectionString);

If Create is how we bring objects into this world, then Delete is the Grim Reaper. Deletion is final and absolute, no trace should be left of the object afterwards. Any attempt to use something after deletion must surely be a logical error. Common alternatives are Dispose and Destroy.

directory.DeleteFile(filename);

Acquire & Release

Using Create in the name of a method, based on the above definition, could be seen to be leaking the abstraction. Acquire has more of a vagueness that could be interpreted only as “I’ll give you something you can play with, I may create it or I may reuse an existing object, either way you shouldn’t care”. The implication is that the object may be in a more complete state of initialisation. Using the previous example the database connection would already have been opened. Object pools are the prime example here.

IDatabaseConnection connection = ConnectionPool.AcquireConnection();

If you’ve acquired something, there is a feeling of only partial ownership. It’s not really yours to do with as you wish. This means that you’re not in a position to delete it, the best you can do is let go. Releasing suggests that the object may live on with another unrelated owner, or perhaps it’s going to be returned to storage to await a new owner at some point later. COM interfaces are the canonical example here as memory allocation is outside the remit of the caller.

connection.Release();

Open & Close

The use of Open and Close on an object is an incredibly common one, generally with real resources like files and database connections. They are very explicit actions, like Create and Delete, and also leak the abstraction to some degree. I find they are useful when you have a heavy resource that needs careful management, but you don’t feel you can hide that responsibility from the caller. Like Acquire and Release, they are slightly more woolly, but whereas Acquire and Release are about construction, Open and Close are actions an object performs (maybe on itself).

connection.Open();

connection.Close();

I have rarely seen these two verbs used alongside a noun in OO, even helper free functions would use overloading on type because the noun would only repeat the type.

Find & Get

When I go shopping I often have two things in mind, there is stuff I would like and stuff I need. The stuff I would like is optional, or maybe I can choose from various brands and sizes, e.g. cereal*. In contrast the stuff I need is mandatory, maybe something doesn’t work without it, e.g. petrol. Find is analogous to the first case. It says “I think you might have this, and if you don’t I can do something else”, in short, you know that it could fail and you are willing to handle that failure responsibly. One common alternative verb is Lookup.

Image image = cache.Find(url);

Get is like buying petrol from an oil refinery. You absolutely know that they must have some, and if they don’t then they better raise an exception because if the refinery is out you don’t stand much luck getting any from a petrol station either. Get is sometimes used for construction, such as in the composite verb GetOrCreate. I don’t personally like this use, to me, Acquire is far more pleasing.

String name = product.GetName();

Get has unfortunately become such an overused verb because of its association with Getters and Setters. This has the side effect of people becoming blind to it to make property accessors read more naturally, e.g. filename.getLength() would subconsciously just be read as filename.length(). I think most people these days would be surprised to find a Get method doing much more than just returning a private member.

Request, Retrieve & Locate

The word Find is so quick to read and say, and with that I feel that it often implies a quick scan rather than a long drawn out search. For remote calls I like to try and use a verb that has for more complex connotations. Retrieve and Locate both sound like more serious work is involved in the hunt. Likewise Request always feels like something a remote service will be called upon to handle.

Book book = library.RetrieveBook(title);

Unfortunately the ubiquitous nature of HTTP means that Request is probably more commonly used as a noun, such in the inseparable pairing Request/Response.

Read & Write/Send & Receive

When  it comes to I/O a very common naming convention appears to be the use of Read and Write - as least as far as file I/O goes. However when we’re talking about network I/O the old Berkley Sockets API kicks in and and we find the use of Send & Receive favoured instead. If we’re restricted to discussing the transfer of small buffers of data this is fine, but once we begin to widen the picture to the overall topic of OO data persistence a few new terms come into  play. The posh sounding pair is Serialize and Deserialize, which I find incredibly difficult to type (like all American APIs), but I tend to think of it as transport agnostic. The lower-class sounding variant is Load & Save, which evoke memories of floppy disks for me, and I usually expect it to be applied to large objects such as whole documents.

Buffer buffer = textfile.ReadLine();

uint count = socket.SendMessage(message);

Image image = document.LoadImage();

 

I readily accept that these can be seen to be very literal interpretations - I’m a very literal kind of chap - but I think that most frameworks I’ve dealt with tend to follow along similar lines and I rarely get surprised. But in application code the story is often different, especially when working in a multi-cultural team. What would be nice is to have a global programmers dictionary and thesaurus. The dictionary could ensure that you’ve not picked something contradictory, while the thesaurus would grant you some latitude without you picking esoteric words that only Shakespeare would stand a chance of understanding.

*Cereal shopping is actually a major event in our house, and as my wife (who will no doubt cast her eye over this post) will point out, does not allow for any deviation to shop own brands or other lesser substitutes…

Saturday, 7 November 2009

My New Blogging Machine

Much as I love my dear Dell XPS 1200 - it’s a lovely laptop to do development on – it’s still a little too heavy to just slip into my rucksack and carry around on the commute, even at under 2 Kg. And, given that I’m trying to make a concerted effort to do a little more blogging to improve those English skills I thought I’d check out the current range of netbooks.

As someone who stands over 6 feet tall, with hands the size of spades, and fingers fatter than some peoples forearms,I’ve never felt totally comfortable on a laptop keyboard, so I never for a moment thought a netbook would be practical (I still use an IBM Model M keyboard c1985 at home - the best keyboard ever). However the other weekend, I managed to convince my niece to let me play with her netbook just to confirm my suspicions. It’s seems I was a little too hasty in my assumptions. Putting aside the somewhat sticky keys, which I wish to point out was the result of her typing with chocolate covered fingers and not a design feature, I found it far more comfortable than I’d ever imagined.

A week or so later and here I am typing this on my new Asus Eee PC 1500HA. Leaving the plug at home it weighs in just over the Kg mark, but given that I often carry weighty tomes like the C++ IO Streams book, or Enterprise Patterns with me into work it hardly registers. The keyboard feels slightly cramped, which is to be expected but I’ve quickly got used to it. The Home and End keys are at the top-right on my Dell and I often hit Insert by mistake, whereas they are bottom-right on the Eee PC and need the Fn key as well. I didn’t think I was going like that, but I’ve already forgotten about it, in fact mapping Home,End, Page Up and Page Down on the cursor cluster seems so damn logical.

Performance is also surprisingly good. My wife bought a Toshiba laptop some years ago which was very lightweight, but it only had a 1.1 GHz processor and felt very sluggish, at least when you’re used to multi-core beasts in both workstation and laptop form. I was expecting a similar experience here, but frankly I’m gobsmacked at not only how quickly it boots up from cold, but also how responsive it is when starting applications. I may have to revisit the notion that I’m only gong to be using it for writing on.

My biggest concern is my wife though. Her Dell XPS 1310 that is her bread-and-butter, has developed another fault after only a short life – no doubt something to do with the large drop it suffered a while back :-) If she gets her hands on this little beauty I fear for it’s safety. I’m hoping it’s going to be small enough to hide at the bottom of my bag under the packets of tissues and fluff and will escape her notice. So, if a strange women comes up to you and asks if you’ve seen this netbook of mine, deny everything…

Thursday, 5 November 2009

Happy 21st/12th Anniversary

This week marks a palindromic moment in my relationship with my wife. On the one hand we have been married for 12 years, as of Monday. But we've been together for much longer, 21 years as of today. As happens each year, my wife says Happy Anniversary on the 1st, and yet I'm still waiting for the 5th because to me that is our spiritual anniversary. This of course has nothing to do with my complete inability to remember names or dates; obscure numbers like hex addresses and error codes - no problem, but birthdays and appointments - no chance.

And yet she still puts up with me... Even during my six month sabbatical I never really pulled my weight as I could have. She looks after the kids, runs the house, manages the finances and holds down a job! On top of that she still finds time to massage my ego and deal with my many insecurities. Quite frankly I really don't deserve her.

So tonight at the local annual fireworks display, even though I'll have the kids with me, and be surrounded by friends, St Judith's Field will still feel empty and the fireworks will lack a certain sparkle because you're not there with us. Happy Anniversary my love.

Monday, 2 November 2009

A Chip Off the Old Block

My eldest has a presentation to do for his English class at school which I managed to catch him practising. It's about the history of video game consoles. Naturally he has most to say about Nintendo's recent output given that even the N64 was out before he was born! Still, he starts out with the Atari 2600 which is good to see as it's my spiritual starting point in this industry, and we have one of those in the house (a "Heavy Sixer" no less). Of course I waited until he had finished his research before pointing out the copy of High Score!: The Illustrated History of Electronic Games on the bookshelf upstairs.

So, does he display any other tendencies towards following in his old man's footsteps? Obviously he's aware of what I do for a living (to a certain degree) and has shown some interest in programming in the past, starting with the time they were playing around with Logo at school during KS2. Consequently I nudged him towards my Java JLogo applet, which was inspired by my somewhat older nephew when he was learning Logo at that age. The school also promotes applications like Scratch, which I think is pretty neat as it's visual programming with a real sense of fun. These days text I/O is pretty dull even to diehards like me so why expect a child to find it interesting?

I've also downloaded Microsoft SmallBasic, which is nothing like the BASIC I grew up with, but I thought that it might be much easier to do something interesting with. He found a Pong example program which he could play around with. I'm also aware of a book aimed at children that uses Python as a first language which seems to have favourable reviews. I might invest in that myself as I've been meaning to learn Python. I guess once he studies Computer Science proper at school, it'll either rekindle his interest in programming or just reinforce a view that videogames are the only aspect of computing worth investing time in :-)

I remember one day, when he was much younger, standing behind me watching me relentlessly debugging some tricky code in Visual C++. All he could see happening on screen though was the yellow bar that marks the 'current source line' jumping around the screen as I entered into and out of functions. He remarked to his mum that all I did all day was "make a yellow line move up and down the screen". I suppose that's not that different from playing the Atari 2600 really…

Friday, 30 October 2009

Stack Overflow Dev Days – London

On Wednesday I took a day off to go to the London venue of the Stack Overflow Dev Days tour. I wasn't entirely sure what to expect even up to the moment I arrived as I signed up without the faintest idea of what anyway was speaking about, and more importantly whether any of it would be relevant to my day-to-day work as a self-confessed C++/C# server-side kind of guy. Frankly I didn't care, for me it was going to be a day of meeting new friends, old friends (from the ACCU), and generally soaking up what's new and cool in the world of Software Development -C++ and faceless servers are presumably not cool.

Opening Keynote by Joel Spolsky

The day opened with a humorous little skit on software development practices by Jeff, Joel and the Fogbugz team and was followed by Joel in person to talk about to eternal struggle between Simplicity and Power. His argument was that although simple to use software is good for the user, fundamentally what users think they want is features, and when it matters (voting with their wallets and getting the bills paid) power matters – a lot.

Python Introduction by Michael Sparks

Joel was followed by Michael Sparks from the BBC, here to give a short introduction to Python. His example was a simple piece of Python code to aid spell checking - the same code that was referenced by Joel earlier in his keynote as being elegant. Python is one of those languages I've always felt I should learn (I dabbled some years ago) and this presentation has wet my appetite again, but only when I need to do some heavy string processing.

As an aside, I agree that the code has an elegance, but where I felt it was let down was through a few classic examples of poor variable and function naming – 's', 'edit1' and 'edit2' would have been far clearer named something like 'permutations', 'generate Typos' and 'generateTyposOfTypos'. Or did I miss something obvious here?

Fogbugz by Joel Spolsky

After a cup of java during the morning break, Joel Spolsky got to do a little sales pitch about his Fogbugz products. The pitch was pretty good as it certainly looked far simpler than the bug tracking products I've been forced to use in the past. His companies latest addition is Kiln, which adds Version Control to the mix and allows tighter integration for handling code reviews etc. It's his event so I suppose a certain amount of chest-beating was to be expected.

Android by Reto Meir

The battle for the hearts and minds of the mobile platform developers was started by Reto Meir with an introduction to Android. After a brief background of supported devices and usual market growth spiel we got to see him create a simple Hello World app and run it on an emulator. Unfortunately the choice of font size didn't help and the constant scrolling around the virtual desktop made you feel quite sea-sick. However I saw enough to get a taste for what Android's about.

jQuery by Remi Sharp

To me jQuery epitomises what Joel talked about in his keynote about Simplicity and Power and also about elegant code. I have to stand back and marvel and what I feel is a truly fine piece of technology. Although I have only done a smattering of JavaScript in the last 8 or so years, jQuery clearly illustrates how far machines and, more specifically, JavaScript engines have come. Perhaps if this is your bread-and-butter it's nothing special.

Needless to say Remi's presentation was slick, providing plenty of examples of how to harness the power of the query side with the Fluent Interface (which he termed Chaining) that drives the DOM mutation. A fair amount of the audience had used jQuery already so perhaps he was preaching the converted.

Lunch

A whole paragraph devoted to lunch? I'm afraid the only thing that marred the entire day was having to wait nearly an hour to get lunch because they ran out of food! The event was sold out months ago, so someone knew exactly how many people were attending, so how can you run out of sandwiches? I missed the start of Jeff's talk due to this mishap. I'm not sure everyone got coffee earlier either.

Jeff Atwood

Unlike Joel who clearly had something to sell, Jeff seemed to be more interested in showing what makes him tick, and how that passion has driven the Stack Overflow venture. Hearing him talk about getting excited about everything right down to configuring the hardware makes him an instant soul mate. Also his plug for the book Coders at Work had the desired effect on me as it went straight on my Amazon wish list.

Qt by Pekka Kosonen

Nokia are probably the Microsoft of the mobile phone world. Whereas the new kids on the block, Android and iPhone, are cool and sexy, Nokia has the established customer base but no pizzazz. Pekka did his best to get the audience on his side by the tried and trusted means of self-deprecation. There were some interesting demos of how you can develop without needing a locally installed SDK, and the thought of remote testing, sure seems sensible given the diversity of hardware out there. Ultimately though Qt just isn't quite as sexy…

iPhone Development by Phil Nash

Phil is a fellow member of the ACCU and I was fortunate enough to go to his presentation at this years ACCU Conference about iPhone development. However this talk is a far more polished affair as he has dropped some of the more grungy details of Objective-C development in favour of putting together a demo app live on stage. Like the Android presentation earlier, it was only a simple app, but had just a little more panache than the competition. The main stumbling block I fear though is still Objective-C, the manual memory management is a real turn off.

Humanity: Epic Fail by Jon Skeet

Being new to the world of C# development, Jon Skeet is a name that I only have a passing familiarity with at present by virtue of me having only just read his book, C# In Depth. Oh, and a few Stack Overflow replies as well. The man seems to have a somewhat legendary status and doing a presentation with a hand-made sock puppet doesn't appear to have put a dent in that.

The premise of his talk was that there is a huge disconnect between the users view of the real world and how they expect the software we develop to model it. They are simply unaware of the limitations of the digital world, such as in the representation of real numbers, or the ambiguities of time-zone names, or the subtleties involved in processing text from the many different languages we speak. Quite frankly if people like him can't get it right, what chance do those of us further down the evolutionary chain stand?

How Not to Design a Scripting language by Paul Biggar

The afternoon coffee break was succeeded by Paul Biggar, a PhD student studying scripting languages. He had some interesting opinions on where their limitations lie and how they could be improved to reduce the performance gap with the traditional compiled languages. I've never read The Dragon Book about compiler design, but I'm aware of it's reputation, and someone who publicly dismisses it in favour of Engineering a Compiler by Cooper & Torczon had better know their onions. He was definitely one of the more entertaining presenters.

Yahoo! Developer Tools by Christian Heilmann

Christian Heilmann finished off the day promoting the YUI toolkit from Yahoo! I got the impression from this talk that there is fair bit of competition in the web toolkit arena, and their USP is that they use it and that they have 330 million customers to support. That customer base figure was trotted out a number of times… The demo of YQL, a SQL like query language for extracting data from web services, was certainly very interesting. I would have thought that YQL plus jQuery would be a very powerful combination.

Final Thoughts

Joel returned to the stage to close the day and asked who would come again. Most, including myself, raised their hands. At £85 it was certainly a bargain compared to what you normally pay for training – more so if the subjects were relevant to you. Me, I just enjoyed the day surrounded by geeks who are passionate about their profession. Now if we could just convince a few more to join the ACCU…

Monday, 19 October 2009

DDE Is Still Alive & Kicking

Dynamic Data Exchange (DDE) is an ancient inter-process communication (IPC) mechanism carried over from the 16-bit Windows days. Post millennium Windows programmers are probably more used to a diet of COM, but there still seems to be life in the old dog yet. Maybe there are less people around to answer questions on DDE, or perhaps the other old timers are ignoring them in the hope they'll go away because I seem to have had more emails on the subject this year than ever.

I presume the reason the questions are still coming my way is because I have a number of freeware tools on my website aimed at working with DDE Servers that are still actively supported:-

  • DDE Query is my oldest tool and is a GUI based utility for sending requests and creating advise loops on items. It was written as the main test harness for my DDE library.
  • In contrast DDE Command is my most recent addition and is the console based counterpart to DDE Query. It also provides the ability to invoke XTYP_EXECUTE transactions.
  • In between the two is my DDE COM Client - an automation compatible inproc COM component that can be used as a DDE Client for scripting scenarios, such as VBScript.
  • The final, and second oldest utility I provide, is a Network Bridge to allow DDE Servers to be accessed remotely. It is entirely transparent to the client and server, unlike the built-in Windows NetDDE service.

These all use my own C++ DDE library which in turn is based on the DDEML C-API library that Microsoft provides. Under the covers DDE is just a message based protocol that uses Windows messages to encapsulate a connection between two applications – known as a Conversation. Data is passed by allocating it with the old GlobalAlloc() API, and the format is determined by either using a standard clipboard format, such as CF_TEXT or a custom one via RegisterClipboardFormat(). The fact that it is message based is also its biggest limitation as it means you cannot share data between machines – you can't even share data across desktops on the same machine. The only book I came across on the subject was Ole 2.0 and Dde Distilled by Al Williams, but it covers the topic pretty thoroughly.

Before working in finance the only time I had come across DDE was when writing an installer back the mid 90's. Under Windows 3.x you used DDE to communicate with Program Manager (the shell that today is known as Explorer) so that you could create a "Program Group" and the icons for your application. You can still see this legacy today if you fire up DDE Query and use the "Server | Connect…" option, where you will spot a server called PROGMAN with a single topic also called PROGMAN. If you open this conversation and request the item "Accessories" you will be shown a CSV formatted text block with the programs from the Accessories Start Menu folder.

Once I started working in finance I discovered that Excel was the traders tool of choice. Excel can pull data from a number of sources, but the legacy option for real-time data was DDE. The big providers like Reuters, Telerate & Bloomberg all provided tools to allow you to feed their financial data into a spreadsheet and the in-house software we developed followed the same architecture. Although COM was probably Microsoft's promoted technology, DDE felt far simpler to implement.

These days I don't work with that kind of real-time feed, but the questions I do get on DDE always seem to have RIC's in the examples, so I guess that it's the financial industry that is keeping this prehistoric mechanism alive.

Saturday, 17 October 2009

We Don’t Use IE6 Out of Choice

Whilst on site the other day I found myself wanting to check out the NHibernate Profiler website. When I arrived at the homepage I was greeted with a modal iframe that pointed out that I was using that old legacy browser we all love to hate – Internet Explorer 6.

This distraction is nothing new, many popular sites such as Twitter also display a little message that points out the error of your ways, but what really raised my ire was the approach NHProf has taken. Instead of just warning you that your browsing experience is likely to be sub-optimal due to your choice of browser they instead hide the site behind a semi-transparent modal iframe that just includes links to download more modern browsers such as Firefox or Chrome. Nowhere was there an option to allow me to accept the consequences and soldier on, knowing full well that content may be all over the place or unreadable due to poor image handling.

When implementing this behaviour did it ever occur to the developers that I might not be using IE6 out of personal choice? Or that upgrading my browser at that moment in time might be incredibly inconvenient?

There is a very good reason why Internet Explorer 6 is still popular among the development community and it has absolutely nothing to do with laziness or some twisted superiority complex – it's Corporate Policy. Large corporations are incredibly conservative when it comes to upgrading major software components like the OS, browser or office suite. This is likely supplemented by a very strict policy controlling what additional software can be installed to reduce the possibility of conflicts. They often have a significant number of line-of-business (LOB) applications that have been developed in house that could potentially break if one of these elements is changed – a move that could cause them significant financial loss. I know of one major financial institution that didn't start rolling out Windows XP on the desktop until 2007 at which point XP was close to entering what MS calls Extended Support. The remediation process was lengthy, tiresome and provided no added value to the business.

I completely understand that website development is hard enough given that you have to test with IE, Firefox, Chrome, Safari, Opera etc and adding support for a badly broken browser like IE6 into the mix adds significant cost – especially for a non-commercial venture. But I'm suggesting they do. I just want you to recognise that we're not all in the privileged position of being able to treat our machines as we please. Some of us have to put up with our desktops, CD drives and USB ports being locked down tighter than Fort Knox.

Trust me, no one would still be using IE6, if they (or even Microsoft) had a say in the matter…