Tuesday, June 26, 2007

K&R Slaves

Warning: anyone reading this might want to do so with a mental IMHO tag around the whole thing.

Long-suffering friends and colleagues know that I make no secret of disliking the code formatting convention known as K&R style (after Brian Kernighan & Dennis Ritchie and the code layout style first used in their seminal book The C Programming Language). However, although I personally believe that this:

function changeTarget(source){
if (source === Targets.localTarget){
var target = this._get_target(source);

for(i = 0; i < this._log.ops; i++){
if(this._log.ops[i].value === target){
this._logs.selectedindex = i;
}
}
}else{
this._log.selectedIndex = -1;
}

if(this.get_mode() === SourceMode.Extended){
this.addCssClass(this._popupElement, "Extended");
}else{
this.removeCssClass(this._popupElement, "Extended");
}
}


...is much less readable and understandable than this:

function changeTarget(source)
{
if (source === Targets.localTarget)
{
var target = this._get_target(source);

for(i = 0; i < this._log.ops; i++)
{
if(this._log.ops[i].value === target)
{
this._log.selectedindex = i;
}
}
}
else
{
this._log.selectedIndex = -1;
}

if(this.get_mode() === SourceMode.Extended)
{
this.addCssClass(this._popupElement, "Extended");
}
else
{
this.removeCssClass(this._popupElement, "Extended");
}
}

...I know that these things are a matter of preference and project/company standards.


No, what really annoys me are the reasons some people cite for preferring K&R over BSD/Allman code layout and the actual origins of the style itself.


There seem to be two main reasons people go for it - firstly they think it looks cool; as if making code look complicated and involved imparts some sort of geeky kudos - "look at that heavy-duty code! Must be pretty hairy stuff going on in there, best not to touch it or try to maintain it, best just to marvel at it" - however, as in the above examples, I'd go for clarity and readability any day because code shouldn't be "write-only" and needs to be comprehensible to others to allow for maintainability.


The second reason seems to be born of a "be like the big boys" motivation - "if its good enough for the giants of software like Kernighan and Ritchie, then who are we to argue?" and "all the code that comes out of the big guys at Microsoft is formatted that way", but hang on - a few issues:



  • The compacted style only emerged as a practicality of only having 80 column x 25 line displays and trying to get as much readable code into each screen or printed page as possible - we don't have that constraint anymore and who prints code listings these days anyway?

  • Kernighan and Ritchie never mandated or recommended that style - they were quite neutral in the original book about it:


"The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently."


Yet somehow the style has become a sort of holy gourd.



  • Kernighan and Ritchie's original use of the style was inconsistent, (again because of constraints); the original C language didn't allow for the compacted braces style on functions that took arguments and K&R were quite happy to be pragmatic about things and adopt a BSD/Allman style for these cases

  • Microsoft's big boys don't always manage consistency either; whilst they ship the AjaxControlToolkit with lots of K&R style code in the JavaScript, their internal style and code review tools warn against elements of K&R styling when they appear in language files that the tools process (main example C#) and it is possible to fall foul of check-in policies for compliance with these code review tools on readability/maintainability grounds

Ultimately though, my point is that to go with K&R for reasons of emulation or hero-worship is spurious and slavish, and readability and comprehensibility are much better criteria by which to select a code formatting style and I will "take the Pepsi challenge" any day that BSD/Allman wins on that score - I might just have to wait for a few others to cast off their chains.

The fight continues...

The Guardian say that they are going to publish a piece I wrote for their Technobile column which is published each Thursday in the Technology supplement. The article is an extended version of my rant about big corporations misspelling my surname in correspondence, which I previously posted here. My main motivation in sending it to them is the hope that wider exposure might result in someone identifying the makers of the CRM software that seems to be responsible for propagating the spelling error to so many companies. Then I can write to them and direct my bile more effectively.

Wednesday, May 02, 2007

(Active)ActiveSync

Update on syncing my Treo 750 PDA phone:

There is at least additional software on the install CD to enable synching via Bluetooth - yeah right, like the Bluetooth stack is renowned for its rock-solid reliability and compatibility...

Well I wasn't too hopeful, but after the usual multitude of notifications about this, that and the other Bluetooth device all with individual (uncertified - of course) drivers, I got everything installed; and it all works!

Now, with only the occasional hiccup/lockup/Task Manager kill off (it is Bluetooth after all), I have a way of syncing and transferring stuff, albeit at modem speeds (well it is Bluetooth after all).

So although I won't be moving too many large files over to use in Picsel's dinky PDF viewer or ripping any DVDs to its miniSD card, I do at least have a way of getting stuff on and off the thing and a way of backing it up.

Tuesday, April 17, 2007

(in)ActiveSync

Over the years I have owned one or two PDA-type mobile devices at various times, not really using them as the workhorses of office productivity that they are often portrayed as being, but more out of sporadic curiosity and out of an interest in their programmability.

Recently I got a Treo 750 as a replacement for my mobile phone and as it also runs Windows Mobile 5.0, I find myself effectively with another PDA. This time there is more of a chance of it becoming a real everyday tool for me as it pretty successfully combines a mobile phone with PDA Pocket PC functionality.

But, and here finally is my point, over the years ActiveSync has always been a bugbear in terms of reliability and stability of configuration and use - AND IT IS STILL NO BETTER IN ITS LATEST INCARNATION! Connected once, synched, never recognised again except as an USB device error. So now I am stuck trawling the forums looking for help in resolving the issue, un-installing/re-installing (didn't work), upgrading ActiveSync from 4.2 to 4.5 (didn't work), swapping to other USB ports and other machines (you've guessed it - didn't work)...

...frustrating.

Monday, April 02, 2007

Ah! Good old .net remoting...

Looking at some .net remoting code recently reminded me of just how confusing and frustrating using it can be.

We were trying to diagnose why remoted events hooked up to a remoted object were failing after the standard 5 minutes initial lease time despite the fact that the remoted object had an overridden InitializeLifetimeService method that returned null - the standard way to setup an infinite lease on a remoted object.

Using debug tracing and explicit lease management with a sponsor class, we could prove that the remoted object was not dying, but nevertheless the events that it was firing seemed to be disconnected after the initial 5 minutes and we were getting a standard remoting infrastructure exception stating that the remote object didn't exist or was disconnected. How could it be that the remote object had an infinite lease but the events it was firing didn't?

The answer, as always with remoting, lay in understanding the hoops that the remoting infrastructure goes through in supporting cross-domain marshaling of calls, i.e. how it manages to make each side of the remoting relationship behave like it is communicating with a local instance of what is to either side, the remote object.

The curious thing is that even when a object that is remotable (i.e. derives from MarshalByRefObject) is started by a client that is not itself remotable, if the remoted object calls back to the client (as it must in order to fire an event back), then the remoted object must do so via the remoting infrastructure by communicating with a transparent proxy/real proxy local to itself which then forward the call via remoting back to the client.

In other words the client and server roles are reversed for this callback and there is effectively a remoted instance at the client to receive the call and it was this that was being created with the default 5 minute initial lease time.

This of course begs a couple of questions - firstly: what is being created on the client side as the receiver of the events? It can't be the client itself because it already exists, stays alive after the 5 minutes are up and doesn't derive from MarshalByRefObject and so cannot have a leased lifetime anyway. Secondly: how could we avoid whatever it was from dying after its 5 minute lease expired?

As it turned out the second question was easier to answer than the first, albeit with a somewhat inelegant solution.

A simple call to set the LifetimeServices.LeaseTime static property to a very large figure (say 1000 days) within the client app's initialization, sets the initial lease time for any MarshalByRefObject subsequently created in its AppDomain (including the dynamically created proxy that was previously timing out at the default lease time of 5 minutes) to what is effectively an infinite lease (unless you want to go 27 years without shutting the client app down!)

Of course a more elegant solution would be to actually have created our own client side MarshalByRefObject derived class to serve up the events to the client app and then to have overriden the InitializeLifetimeService method to return null as we do on the server side, but that really wasn't necessary as the only remoted functionality on the client end was the servicing of these events and we could safety define a long default lease for all remoted objects created in the AppDomain and achieve the same effect without another layer of indirection and the effort of creating and testing more code.

As for the answer to the first question...that's more difficult to answer; from debugging, it is clear that there is a TransparentProxy created on the server side which is used to fire events back to the client side, but what it is connected to, through the Remoting framework, down at the client side is difficult to establish (although I must admit I didn't spend too much time trying, after establishing the easy fix solution) - all the client is attached to, is an event that may or may not fire depending on whether it is connected to a valid source or not.

Perhaps someone more familiar with the Remoting framework knows more about the mechanics that go on under the hood when "doing events" on remotable objects and how non-remotable objects can effectively work as remote servers when the remote objects they create need to fire events back to them; it would be interesting to know...

Monday, December 11, 2006

Retro

How weird to be back in the world of WinForms and ASP.NET control development, after so long in the realms of WPF betas and CTPs. Working on Windows and Web controls and components has a familiar and old-fashioned feel - like I know how to do everything that the spec requires, but that the results will be rather plain and rigid in appearance and behaviour.

Still there are compensations - not feeling that every surface will inevitably end up with a gradient fill; not having animations just because you can; having an infinitely higher level of confidence in the dev tools and the base class libraries which allows you to know that if things are going wrong it's definitely your own fault and not a buggy set of fundamental building blocks.

But it is also amazing how rusty you can get - leaving a branch of dev technology for a 12-18 month period brings on, for me at least, a Homer Simpson like phenomenon of the newer stuff pushing the old stuff out of the brain to make room; the shelf above my desk is currently groaning under the weight of tech books that I have had to bring to work as reference material.

And this is before taking into account the newer VS2005/CLR 2.0 stuff that I didn't really get to grips with as it was released - ASP.NET 2.0 is so different from 1.0/1.1 and because of the timing of its release, I never got the chance to enjoy the delights of Master Pages, Personalisation, the Provider model etc., etc.

The worry of course is that I will use older techniques or approaches to implement features and miss the opportunity to do things better by exploiting newer aspects of the technology - so rather than just using the tech books as reference material, I am carting them back and forth to and from work and trying to read them a bit more sequentially in order to get coverage of more than just the stuff I think of and go look up. So it's 'back to the classroom' so I can push all that WPF/XAML out of my brain again...ho hum.

Wednesday, October 25, 2006

CodeTidy Update

Listening in catch-up mode to past DotNetRocks podcast shows as I commute into work in the car (Milton Keynes to TVP takes about 1.5 hours each way each day), I came across a recent episode with Mark Miller of Developer Express in which they referred to a DotNetRocks TV episode he did showing off DevExpress's DXCore plugin framework for Visual Studio.

I didn't even know they did the DNR TV , but it sounded like it might contain something useful on doing tools for the VS IDE, so I took a look at the show and was amazed to watch as they used the DXCore framework to basically build a first-cut of CodeTidy! The DXCore basically contains a whole bunch of classes that wrap the IDE and provide access to code and code windows in a nice, comprehensive and logical way. Mark took less than an hour to put together an add-in that could sort the members of the current class/type in the editor window by visibility (private, public etc.) and type (properties, mem vars etc.) and a bit of sub-sorting of one category within another.

The design approach he took wasn't quite how I would have done it, but that is not important; what was important was how easy the DXCore framework made it to do things like grab a method and all its attached XML comments and queue up a delete/move operation on it along with all the others to make the sort operation consistent and undoable - all courtesy of calls to DXCore. Incredible.

So...I have grabbed the sample code that they thoughtfully made available and have gotten hold of a copy of the DXCore install (it is free) and plan to refactor/build on it to make a CodeTidy I can use in daily coding.

The session also allowed Mark to show off the tools that DevExpress actually charge for - Refactor and CodeRush - which looked pretty impressive too. Refactor does what it says on the tin and CodeRush is like intellisense on steroids with masses of customisable keyboard shortcuts for frequently used actions like newing up class and vars, creating if, while, for/foreach blocks etc. Could be a purchase coming on...

Essential WPF - Chris Anderson

I have been looking at draft chapters for Chris Anderson's forthcoming WPF book and it looks like it is going to be a great tech reference - lots of under-the-hood stuff and a nice logical progression through the major concepts.

More XAML-oriented than Charles Petzold's Applications = Code + Markup which I thought was (understandably) very code-behind oriented and procedural. Given that I think the most exciting thing about XAML and WPF is the declarative programming aspect, I think that books that focus on this side make more sense.

Original and Best - Chris Sells and Ian Griffiths original Programming WPF had the approach spot-on and I am really looking forward to their WPF-release update next year.

Thursday, September 28, 2006

CodeTidy Kickoff

Processing the code in a C# code file can be done in a few ways. Visual Studio has an extensibility/automation model that allows access to projects, solutions, modules, classes, code etc. as object collections; which would seem to be ideal for what I have in mind - not having to parse the stuff oneself.

However anytime I have looked at this in the past as a possible route for achieving the task of manipulating the raw code in a file I have come up against obstacles - most notably no support for locating and dealing with regions, some comments, namespace import (i.e. using) statements etc.

If I am to sort/arrange code without mucking up the containment of regions or orphaning comment lines, then I have to know about these parts of the text content of a code file and be able to manipulate them in the same way as the methods, properties etc. that are available as objects in the extensibility/automation model.

Parsing code files as raw text and recognising these 'contructs' manually seems like re-inventing the wheel and the sort of activity better done by people with more mathematical minds than mine, who thrive on lexical parser theory and and all that grammar/token recognition stuff.

So, what to do..? It would be nice to use the automation/extensibility model and fill in the gaps with a bit of manual parsing I suppose, but that leads to the need to effectively maintain my own 'meta-model' of the code being analysed that references/synchronises with the VS model but supplements it with information about the association of things like regions. Plus I need to take a fresh look at the VS model as I guess it has moved on and improved since I last looked at it (VS 2003) - though I'm pretty sure it still doesn't provide exposure of things like regions.

Further thinking required.

Tuesday, September 19, 2006

Pet Projects

I am a big fan of pet projects; by which I mean hobby code that I have developed and continually re-develop in order to learn new and newer versions of developer technology.

I have done this in the past with a Windows wallpaper changer taskbar app and a piano scale and chord finder utility. These have gone through various VB, Delphi and C# versions. Each time the familiarity with the 'requirements' means that I can use them as a comfortable 'problem-space' in which to try to utilise new features and rework code.

I am just about to start a new pet project - this time to sort code (initially C#) in code files according to configurable rules. I've always wanted a utility that would allow me to organise/group code in order of construct type (e.g. properties, ENUM, methods etc.) or access (private, protected, public etc.), taking account of regions and respecting comments and areas like namespace containment of imports (using statements) and allowing alphabetic sorting within these groupings.

Eventually I hope to make this an add-in to Visual Studio that will help me to organise my code in place and at the same time master the dark art of VS automation...so CodeTidy is born.