I posted one half baked idea a while back (find people by interest).
Here's another.
A personal, multi-accessible, cross-platform, "cloud", simultaneous-accessible scheduler.
I want to be able to access my schedule through my phone or my home computer or my work computer.
I want the option of scheduling a reminder independently of the event - so I could say I want a reminder on this date at this time, and the title of the event is XYZ. Currently, with outlook, I have to specify 2 date / time periods - first when the event is, then when I want the reminder - I'd rather do it in one.
I want the reminder to pop up on all my synced devices simultaneously, so whichever I happen to have with me / am looking at, I get the reminder - at the moment I can't schedule everything in outlook at work because sometimes I'm not in the office. I can't schedule everything on my phone because sometimes my phone is on silent (e.g. when I'm in the office). When I get my reminder, I want to be able to snooze the reminder on one device, and it will pop up again after the snooze duration on all my synced devices, and any of the devices could snooze it again.
Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts
Saturday, 17 September 2011
Saturday, 5 December 2009
Apps Hungarian vs Systems Hungarian
Hungarian Notation is a convention where a prefix is given to a name to indicate its type. There are two flavours of Hungarian, and most of the criticisms are directed at Systems Hungarian, while people don't realise that Apps Hungarian even exists.
Systems Hungarian prefixes variable names with their type. One big argument against doing this is that if the type changes, then you have to change every occurence of that name to match the new type.
Apps Hungarian prefixes variable names with semantic information about the variable.
Without the prefix, "Filename" might be a string, a text box, or something else. "Car" could be an instance of the car class, or a pointer to a car, or an index into a list of cars. "First" and "Second" could be almost meaningless, but in a spreadsheet application (for example) they could refer to rows, columns, cells, or something else.
With a semantic prefix, things become clearer. In a forms application txtFilename is now likely to be the name of a textbox which contains a file name, while strFilename is more likely to be the string itself. Note that strFilename doesn't constrain me to any particular type of string - just that it is a string of some description.
"iCar" is a sensible index into an array of cars, "pCar" is a pointer to a car, and "car" is most likely to be a concrete instance of the car class.
My favourite example comparing Apps Hungarian to Systems Hungarian is based on spreadsheet software.
Using Systems Hungarian (prefixing the type to the name), if "first" and "second" are integer indices, the assignment "iFirst = iSecond" looks alright at first glance. However, if the two variables were refering to rows and columns respectively, then the assignment was used to assign incompatible values.
If we'd used Apps Hungarian instead, the assignment now becomes "rowFirst = colSecond" and without knowing anything about the type of the data, if we saw that assignment, alarm bells would be ringing.
A colleague told me that a 'p' prefix before a pointer name was unneccessary - His arguments were:
If the variable was named m_pCurrentVehicle, then you would be able to see the answer instantly.
I used to hate seeing things in Systems Hungarian like lpszMessage (long pointer to a string which is zero terminated), but I like Apps Hungarian.
Systems Hungarian prefixes variable names with their type. One big argument against doing this is that if the type changes, then you have to change every occurence of that name to match the new type.
Apps Hungarian prefixes variable names with semantic information about the variable.
Without the prefix, "Filename" might be a string, a text box, or something else. "Car" could be an instance of the car class, or a pointer to a car, or an index into a list of cars. "First" and "Second" could be almost meaningless, but in a spreadsheet application (for example) they could refer to rows, columns, cells, or something else.
With a semantic prefix, things become clearer. In a forms application txtFilename is now likely to be the name of a textbox which contains a file name, while strFilename is more likely to be the string itself. Note that strFilename doesn't constrain me to any particular type of string - just that it is a string of some description.
"iCar" is a sensible index into an array of cars, "pCar" is a pointer to a car, and "car" is most likely to be a concrete instance of the car class.
My favourite example comparing Apps Hungarian to Systems Hungarian is based on spreadsheet software.
Using Systems Hungarian (prefixing the type to the name), if "first" and "second" are integer indices, the assignment "iFirst = iSecond" looks alright at first glance. However, if the two variables were refering to rows and columns respectively, then the assignment was used to assign incompatible values.
If we'd used Apps Hungarian instead, the assignment now becomes "rowFirst = colSecond" and without knowing anything about the type of the data, if we saw that assignment, alarm bells would be ringing.
A colleague told me that a 'p' prefix before a pointer name was unneccessary - His arguments were:
- we have strongly typed compilers which can tell us when we've tried using the variable incorrectly
- intellisense can tell us a type just by hovering the mouse
- if a name was followed by a dot '.' then it was a concrete instance
- if it was followed by an arrow '->' then it was a pointer.
- Wherever possible, I want to type code correctly in the first place - not have to wait for the compiler to tell me it's incorrect.
- Intellisense requires me to shift control-context to the mouse - which can be very disruptive during an intense coding-at-the-keyboard session
- Intellisense doesn't always get it right
- The code that has already been written isn't guaranteed to have used dots and arrows yet - explained below:
If the variable was named m_pCurrentVehicle, then you would be able to see the answer instantly.
I used to hate seeing things in Systems Hungarian like lpszMessage (long pointer to a string which is zero terminated), but I like Apps Hungarian.
Labels:
Programming
Sunday, 25 October 2009
Style sheets for IDEs
As programmers, code layout is very important to us.
If code is presented in a way we are familiar with, we can skim-read entire passages of code in very little time and find our way to the significant details very quickly. With well presented code, you can often see the general flow of the code without even having to read the fine details.
Conversely, if the code we read is layed out poorly, it can be a real struggle to read through, and can take a very long time to get even a basic understanding of the code.
Unfortunately, "well presented" is a very personal, subjective description of code.
Indent with 3 spaces or 4? Tabs or spaces? Braces on the same line as other code? Alignment of variable names? Prefix? Hungarian?
There are hundreds more examples. If you surveyed every programmer you knew, I'm sure you wouldn't find any two who agreed on every point of code layout.
The trouble is, there is no right answer - there are valid reasons for all the choices.
What we need, is a way of separating out the code from its layout - syle from substance.
When we have IDEs which can present any piece of code in your style, we'll have made a great leap in the speed of code comprehension.
If code is presented in a way we are familiar with, we can skim-read entire passages of code in very little time and find our way to the significant details very quickly. With well presented code, you can often see the general flow of the code without even having to read the fine details.
Conversely, if the code we read is layed out poorly, it can be a real struggle to read through, and can take a very long time to get even a basic understanding of the code.
Unfortunately, "well presented" is a very personal, subjective description of code.
Indent with 3 spaces or 4? Tabs or spaces? Braces on the same line as other code? Alignment of variable names? Prefix? Hungarian?
There are hundreds more examples. If you surveyed every programmer you knew, I'm sure you wouldn't find any two who agreed on every point of code layout.
The trouble is, there is no right answer - there are valid reasons for all the choices.
What we need, is a way of separating out the code from its layout - syle from substance.
When we have IDEs which can present any piece of code in your style, we'll have made a great leap in the speed of code comprehension.
Labels:
Programming
Thursday, 28 May 2009
Stuck in a rut
Don't get stuck in a rut! Don't miss the wood for the trees!
The other day, I was working out some long, convoluted workaround for dealing with the fact that vector iterators can become invalid if the vector resizes.
Then someone reminded me that you can access elements of a vector by index. D'oh!
The other day, I was working out some long, convoluted workaround for dealing with the fact that vector iterators can become invalid if the vector resizes.
Then someone reminded me that you can access elements of a vector by index. D'oh!
Labels:
Programming
Sunday, 21 December 2008
Terminology: Ensure
What's in a name? Well, quite a lot actually. At best, a poorly chosen name gives little or no insight into the nature of thing it is naming, and at worst the name can be misleading and actually send you down the wrong path entirely. Conversely, well chosen names can convey the meaning, and intent for a variable, method or project.
There's plenty of literature available on the topic, so I'm not going to belabour the point any more, other than to give a couple of examples of names that I try to use consistently in my projects. I'll add other examples as and when I remember them!
The first, I've already mentioned in a previous post, and that name is "Scaffold". To me, it means "something I've put up as a temporary structure, that isn't intended to be there when the final product is released".
The second name is used when I want to get a reference to something that may not have been created yet.
If I was going to create a foo object, I'd probably use "CreateFoo". But I can't use "Create" because the object might already exist.
If I was going to retrieve a foo object, I might use "GetFoo". But again, I can't use "Get" because the object might not have been created yet.
So the term I use in this situation is "Ensure". I think "EnsureFoo" conveys the meaning and is distinct from "Create" and "Get", and doesn't mislead.
There's plenty of literature available on the topic, so I'm not going to belabour the point any more, other than to give a couple of examples of names that I try to use consistently in my projects. I'll add other examples as and when I remember them!
The first, I've already mentioned in a previous post, and that name is "Scaffold". To me, it means "something I've put up as a temporary structure, that isn't intended to be there when the final product is released".
The second name is used when I want to get a reference to something that may not have been created yet.
If I was going to create a foo object, I'd probably use "CreateFoo". But I can't use "Create" because the object might already exist.
If I was going to retrieve a foo object, I might use "GetFoo". But again, I can't use "Get" because the object might not have been created yet.
So the term I use in this situation is "Ensure". I think "EnsureFoo" conveys the meaning and is distinct from "Create" and "Get", and doesn't mislead.
Labels:
Programming
Monday, 15 December 2008
Scaffold
Ever find yourself commenting out lines of code, or adding dummy values, or setting up variables just to test something, then once the test has finished, going back through your code removing the comments, commenting out the dummy values and changing the variables back? And then repeating that sequence when you find that you hadn't actually finished testing?
I do.
Steve McConnell calls this code "scaffolding code".
I also have a tendency to forget to remove this code once I've fixed my bug or finished my test. So I've gotten into the habit of marking the change with a comment similar to
Sometimes my scaffold comments get lost among a sea of other code, and I forget to remove it. So to group it together, I've started using a single scaffold file / class. That way there's only one place to look for the scaffold code.
That's still susceptible to me forgetting about the scaffold before publishing my program, so I think the next step might be to create a user defined scaffold file that can be edited and stored locally, so even if I turn on all my scaffold constructs, nobody else sees them.
I do.
Steve McConnell calls this code "scaffolding code".
I also have a tendency to forget to remove this code once I've fixed my bug or finished my test. So I've gotten into the habit of marking the change with a comment similar to
// Scaffold: added dummy value
int dummy = 3;
Sometimes my scaffold comments get lost among a sea of other code, and I forget to remove it. So to group it together, I've started using a single scaffold file / class. That way there's only one place to look for the scaffold code.
That's still susceptible to me forgetting about the scaffold before publishing my program, so I think the next step might be to create a user defined scaffold file that can be edited and stored locally, so even if I turn on all my scaffold constructs, nobody else sees them.
Labels:
Programming
Tuesday, 23 September 2008
I'll take two
I'm chasing those ideals again. The Right Thing to do is to separate out your business logic from you interface. I read one piece of advice which stated that if you want to know if you've succeeded in separating out those responsibilities, it's the same answer to the question "is my app skinnable?"
I sometimes find it difficult judging where the line should be drawn between the UI and the underlying data. So my idea (which is probably similar to the skinnable question) is to write two applications side by side, that each access the underlying business code. If I've done the job correctly it should be obvious (or at least easier to see) where the shared data begins and the custom UI ends.
Similarly, while I'm writing my next game engine, I'll try to write two (simple) games with the engine simultaneously. This way I can (hopefully) pull all the common code from both games into the engine. It helps me know where to draw the line.
I sometimes find it difficult judging where the line should be drawn between the UI and the underlying data. So my idea (which is probably similar to the skinnable question) is to write two applications side by side, that each access the underlying business code. If I've done the job correctly it should be obvious (or at least easier to see) where the shared data begins and the custom UI ends.
Similarly, while I'm writing my next game engine, I'll try to write two (simple) games with the engine simultaneously. This way I can (hopefully) pull all the common code from both games into the engine. It helps me know where to draw the line.
Labels:
Programming
Saturday, 20 September 2008
Set in Stone
Many years ago, when I didn't know better, I wrote some games, partly as a learning exercise, partly to put in my portfolio, partly for fun. They were a Tetris clone (Tetratim) and a breakout clone (Bounce). But it didn't matter that they were clones because the main reason I wrote them was they gave me the experience of taking a game all the way from start to finish.
Tetratim was the first complete game I ever wrote. It has a start screen, an in-game screen, a game-over screen, and a high score table. Apart from the high scores, all of the data was hard coded into the game-code. (I'll come back to this point in a minute).
Bounce took things a little bit further. It has several UI screens at the front, and included sound effects. The levels were designed in an editor that I wrote. I'd started learning to separate out my code and my data.
Even though I didn't stop programming after that, the game writing dried up. Not through lack of enthusiasm about the projects - I had plenty of exciting ideas that I wanted to implement. No, the reason the writing dried up was because I had become obsessed with ideals. I didn't want to hard-code data for another game. I didn't want to take short-cuts in my code. I wanted to do everything the Right Way.
So I spent lots and lots of time learning the correct way to do things, writing lots of little test programs, trying out new techniques and effects, and storing them all up for later. But for several years I didn't come up with anything that was as near finished as Tetratim or Bounce.
Fast-forward a few years to when I was preparing to enter the games-industry. Suddenly I had an urgent need to have demo material - something that showed that I actually did know how to program games! Urgency is an excellent motivator. Within the space of a few days I threw together a demo of a 3d car driving around on a surface.
A lot of the demo wasn't done the Right Way. The worst offence (in my eyes) was that once again, I'd hard-coded my data into my program. But it didn't matter. It was a neatly packaged, little demo. And that demo got me my job in the games industry.
At first I spent a lot of time programming in my spare time as well as at work, but I was still chasing the ideal. I wanted to do things the Right Way. Again a dearth of completed projects.
Which leads me to now. I have epiphanies from time to time. One of my most recent was "Nothing is set in stone."
It doesn't matter if it isn't written perfectly first time - get something written, and you can always change it later if it isn't correct. Make things modular, if at all possible, then if something is wrong you can "unplug" it and plug something else in in its place.
Ok, so don't dive in straight away - some planning is always good, but don't agonize over the fine details to the detriment of project. That's what I did in between my demo games and it meant I didn't get anything completed!
Tetratim was the first complete game I ever wrote. It has a start screen, an in-game screen, a game-over screen, and a high score table. Apart from the high scores, all of the data was hard coded into the game-code. (I'll come back to this point in a minute).
Bounce took things a little bit further. It has several UI screens at the front, and included sound effects. The levels were designed in an editor that I wrote. I'd started learning to separate out my code and my data.
Even though I didn't stop programming after that, the game writing dried up. Not through lack of enthusiasm about the projects - I had plenty of exciting ideas that I wanted to implement. No, the reason the writing dried up was because I had become obsessed with ideals. I didn't want to hard-code data for another game. I didn't want to take short-cuts in my code. I wanted to do everything the Right Way.
So I spent lots and lots of time learning the correct way to do things, writing lots of little test programs, trying out new techniques and effects, and storing them all up for later. But for several years I didn't come up with anything that was as near finished as Tetratim or Bounce.
Fast-forward a few years to when I was preparing to enter the games-industry. Suddenly I had an urgent need to have demo material - something that showed that I actually did know how to program games! Urgency is an excellent motivator. Within the space of a few days I threw together a demo of a 3d car driving around on a surface.
A lot of the demo wasn't done the Right Way. The worst offence (in my eyes) was that once again, I'd hard-coded my data into my program. But it didn't matter. It was a neatly packaged, little demo. And that demo got me my job in the games industry.
At first I spent a lot of time programming in my spare time as well as at work, but I was still chasing the ideal. I wanted to do things the Right Way. Again a dearth of completed projects.
Which leads me to now. I have epiphanies from time to time. One of my most recent was "Nothing is set in stone."
It doesn't matter if it isn't written perfectly first time - get something written, and you can always change it later if it isn't correct. Make things modular, if at all possible, then if something is wrong you can "unplug" it and plug something else in in its place.
Ok, so don't dive in straight away - some planning is always good, but don't agonize over the fine details to the detriment of project. That's what I did in between my demo games and it meant I didn't get anything completed!
Labels:
My Programs,
Planning,
Programming
Sunday, 7 September 2008
The tape fell off
I was getting a stream of exceptions in my output window when doing a drag-drop. They didn't seem to be affecting my program; the exceptions were in windows code (rather than my code); they weren't stopping my program running - just appearing in my debug output window.
I googled for the exception. I couldn't find what was causing them, or how to stop them occuring. But I did find a post explaining how to stop them appearing in my output window (right click the output window, untick "Exception Messages").
Obviously it would need resolving eventually, but this worked as a stop-gap solution.
Trouble is, the "solution" reminds me of an episode of the Simpsons...
Lisa: Hey dad, that light says check engine...
Homer: Uh oh... the tape must have fallen off.... there, problem solved (engine stops)
I googled for the exception. I couldn't find what was causing them, or how to stop them occuring. But I did find a post explaining how to stop them appearing in my output window (right click the output window, untick "Exception Messages").
Obviously it would need resolving eventually, but this worked as a stop-gap solution.
Trouble is, the "solution" reminds me of an episode of the Simpsons...
Lisa: Hey dad, that light says check engine...
Homer: Uh oh... the tape must have fallen off.... there, problem solved (engine stops)
Labels:
Programming
Wednesday, 20 August 2008
Cutting Edge
When working on a team project, how often should you update from source control?
Broken builds can take hours or even days to fix. On several occasions I have updated source code (sometimes even by accident) only to find that the build was broken. I would then spend the rest of the day trying (and failing) to fix the bug, go home frustrated, come in the next day, update my source code, and the bug had been fixed. On those occasions I felt like I could have just gone home when I found the build was broken and not come back until it was fixed, and that my time would have been better spent.
Of course, sometimes I'm the one who fixes the broken build - somebody has to do it. Which, if I'm honest, means I can't really justify the go-home-when-it-breaks approach.
Back to the question of "how often should I update?"
On the one hand, you could adopt the attitude of "I'm only interested on sub-component X. Therefore I'm not going to update the entire codebase unless I really have to." It's a sensible approach. It means you don't risk killing your productivity every time you update.
The trouble I've had with that approach is, whenever I found a bug in a section of the code, and asked the owner of that code about it, the first thing they would ask is "have you updated?".
On the other hand, you could get the latest code whenever it becomes available. The trouble with staying cutting edge is that not only do you get cutting-edge bugfixes - you also get cutting-edge bugs!
I guess like a lot of development issues, there is no right or wrong answer...
Broken builds can take hours or even days to fix. On several occasions I have updated source code (sometimes even by accident) only to find that the build was broken. I would then spend the rest of the day trying (and failing) to fix the bug, go home frustrated, come in the next day, update my source code, and the bug had been fixed. On those occasions I felt like I could have just gone home when I found the build was broken and not come back until it was fixed, and that my time would have been better spent.
Of course, sometimes I'm the one who fixes the broken build - somebody has to do it. Which, if I'm honest, means I can't really justify the go-home-when-it-breaks approach.
Back to the question of "how often should I update?"
On the one hand, you could adopt the attitude of "I'm only interested on sub-component X. Therefore I'm not going to update the entire codebase unless I really have to." It's a sensible approach. It means you don't risk killing your productivity every time you update.
The trouble I've had with that approach is, whenever I found a bug in a section of the code, and asked the owner of that code about it, the first thing they would ask is "have you updated?".
On the other hand, you could get the latest code whenever it becomes available. The trouble with staying cutting edge is that not only do you get cutting-edge bugfixes - you also get cutting-edge bugs!
I guess like a lot of development issues, there is no right or wrong answer...
Labels:
Programming
Saturday, 9 August 2008
Code Re-use
I've always believed re-using code is a good idea, but it's not until recently that I've felt that I'm doing it properly
When I programmed for myself (before I was hired as a programmer), I wrote in C++. I tried to make libraries (libs and dlls) for re-use in future projects. My friend / housemate / mentor Denis advised me not to bother making libraries and just copy the code into the latest project. I guess for personal projects there isn't really any point wrapping up functionality in dlls. But what about bigger projects? I'm starting to think that even with bigger projects, it's not worth the hassle...
Denis gave me some more advice, when I was trying to put an engine together to help me write games. "Write the game, not the engine". Which I suppose is correct if you want to write the game, but if the process is more of a learning exercise, then i think it's right to work on the engine. But then, I suspect that every closet games-coder is working on their own engine, and a lot of games don't end up written.
I used to write whatever kind of module I thought was necessary for my game, then, when the time came to pull all the code together, I planned to lift all the code from each of the modules and combine them to create my engine / game. Needless to say, I never got round to creating my engine, or my game...
At work, I write tools in C#. Suddenly, I have lots and lots of scope for re-use. I'm not 100% sure of the reason for this, but I feel that the C# language itself makes itself very amenable to code re-use.
Now I don't write everything with re-use in mind. If I only need to use something once, then the time spent making it more generic is wasted. The first time I need a tool to do something, I'll write a very specific tool for the job. Then if I decide I need it again, only then will I make it generic. This process seems to serve me well enough.
So far, I've written the following:
A generic options dialog that can be plugged into any app I write in future. (Currently can store options that are strings or bools - more types planned for in future).
An Argument Parser. (Pass in the args from your program, and then you can ask it for string values or if a bool option is present).
A Serializer. (Until I wrote this, every time I wanted to load or save a binary object I had to create the file reader / writer and the serializer separately, then pass my data to the serializer - now I just create my generic serializer.)
A Cascading Checkbox Tree. (Out of the box, the treeview doesn't propogate ticks up or down the tree. My cascading checkbox tree does.)
A class to convert absolute to relative paths and vice versa.
A class to handle File Operations. (Typically, things like "Close" go through a process of checking if the file needs saving; asking the user if they want to save it; save the file; if the file doesn't have a name present the user with a save dialog; if the user wants to open a file, check that their current file is saved; and so on. My File Operations class handles all of this for me.
And even an OK-Cancel form. (I always seem to be writing dialog boxes that have OK and Cancel buttons on them. And I always have to change the text on the buttons, change the names of the buttons, set up the accept and cancel properties of the form, tell the form to close when either button is pressed. Now I just re-use my OK-Cancel form.
Re-use rocks!
When I programmed for myself (before I was hired as a programmer), I wrote in C++. I tried to make libraries (libs and dlls) for re-use in future projects. My friend / housemate / mentor Denis advised me not to bother making libraries and just copy the code into the latest project. I guess for personal projects there isn't really any point wrapping up functionality in dlls. But what about bigger projects? I'm starting to think that even with bigger projects, it's not worth the hassle...
Denis gave me some more advice, when I was trying to put an engine together to help me write games. "Write the game, not the engine". Which I suppose is correct if you want to write the game, but if the process is more of a learning exercise, then i think it's right to work on the engine. But then, I suspect that every closet games-coder is working on their own engine, and a lot of games don't end up written.
I used to write whatever kind of module I thought was necessary for my game, then, when the time came to pull all the code together, I planned to lift all the code from each of the modules and combine them to create my engine / game. Needless to say, I never got round to creating my engine, or my game...
At work, I write tools in C#. Suddenly, I have lots and lots of scope for re-use. I'm not 100% sure of the reason for this, but I feel that the C# language itself makes itself very amenable to code re-use.
Now I don't write everything with re-use in mind. If I only need to use something once, then the time spent making it more generic is wasted. The first time I need a tool to do something, I'll write a very specific tool for the job. Then if I decide I need it again, only then will I make it generic. This process seems to serve me well enough.
So far, I've written the following:
A generic options dialog that can be plugged into any app I write in future. (Currently can store options that are strings or bools - more types planned for in future).
An Argument Parser. (Pass in the args from your program, and then you can ask it for string values or if a bool option is present).
A Serializer. (Until I wrote this, every time I wanted to load or save a binary object I had to create the file reader / writer and the serializer separately, then pass my data to the serializer - now I just create my generic serializer.)
A Cascading Checkbox Tree. (Out of the box, the treeview doesn't propogate ticks up or down the tree. My cascading checkbox tree does.)
A class to convert absolute to relative paths and vice versa.
A class to handle File Operations. (Typically, things like "Close" go through a process of checking if the file needs saving; asking the user if they want to save it; save the file; if the file doesn't have a name present the user with a save dialog; if the user wants to open a file, check that their current file is saved; and so on. My File Operations class handles all of this for me.
And even an OK-Cancel form. (I always seem to be writing dialog boxes that have OK and Cancel buttons on them. And I always have to change the text on the buttons, change the names of the buttons, set up the accept and cancel properties of the form, tell the form to close when either button is pressed. Now I just re-use my OK-Cancel form.
Re-use rocks!
Labels:
C#,
Programming
Wednesday, 6 August 2008
UndoManager
Undo is more difficult to implement than it appears at first glance.
A typical implementation of an undo manager will store a list of undo data (the UndoList) and a list of redo data (the RedoList).
Undoing an action will pop the last action from the UndoList and push it onto a RedoList. Redo will perform the reverse - pop from the RedoList, push onto the UndoList.
At its simplest, undo / redo data will contain the 'before' and 'after' states of some object in the application, and the function command that will operate on that data.
So for example, if an action adds the next character 'd' to the Collection "MyCollection" (which currently contains 'a', 'b' and 'c'), the undo data might look like this:
If we ask the undo manager to undo this action, 'func' gets called with 'before = c2', and 'after = c1'. If asked to redo the action, the 'before' and 'after' are switched, so 'before = c1' and 'after = c2'.
Easy, right?
Some questions: How do we create c1 and c2? Are they each a clone of "MyCollection"? What if the collection contains something a bit more complicated than characters, say class objects? What if the objects are collections themselves? Should c1 and c2 be shallow copies or deep copies of MyCollection? How expensive is it to deep copy c1?
In adding 10 items to the collection (say 'a' through 'j'), the first undo action will consist of an empty collection, and a collection containing 'a'. The undo action for adding 'b' to the collection will contain a collection containing an 'a' and a collection containing an 'a' and a 'b'. The next action will contain {'a', 'b'} and {'a', 'b', 'c'}. By the 10th action, there will be 100 items in the undo manager (({}, {a}) + ({a},{a,b}) + ... + ({a..i},{a..j})). Not so bad with characters, but what if you have more complex classes?
And what if those class objects are registered with callbacks elsewhere in the code to have things happen to them in certain situations? Should each instance of the class object in the undo manager remain registered? Should items added to the undo manager have their callbacks revoked and reinstated when the relevant undo / redo command is called?
So instead of storing 'before' and 'after' undo data, an alternative would be to store the data and command required to change the data from the 'before' state to the 'after' state (and the command and data required to change the data back) - 'undo' data and 'redo' data respectively.
So in the character collection example above, the first undo data might look something like this:
Easy, right?
Some thoughts: The UndoCommand is essentially a "delete function", and the RedoCommand is essentially an "add function".
So when creating the "add action", let's pass the "add function" and the "delete function" as the UndoCommand and the RedoCommand respectively.
When creating a "delete action", let's pass the "delete function" and the "add function" as the UndoCommand and the RedoCommand respectively.
So what was 2 functions before the undo manager (the "add action" and the "delete action") has become 4 functions with the undo manager (the "add action", the "add function", the "delete action" and the "delete function").
Every action has been split into a "put these commands into the undo manager" function, and an "execute the action" function. That's a whole lotta work to retro-fit the undomanager into an existing app.
Final situation to think about. How do you undo continuous changes? I use the mouse to drag a UI object from point A to point Z, but before I release the mouse button I've dragged the UI object through every point in between. Do we store every intermediate point in the undo manager, or just the start and end points?
It's a rhetorical question; of course I'm only going to store the start and end points. How?
Without an undo manager, every mouse-move event could simply set the UI object's x and y co-ordinates.
How do we make moving a UI object undoable? We're going to need to split the action up into distinct parts.
While we're dragging the object, we would like to see it being displayed in its current location, so the X and Y values will still need to be changing continuously. What we'll need to do is remember the start location when we begin dragging, and the end location when we finish dragging, then add those locations to the undo manager, along with appropriate functions for setting them.
We end up with something like this:
So what seems like it should be a simple enough mechanism, actually turns out to be pretty darn complicated...
A typical implementation of an undo manager will store a list of undo data (the UndoList) and a list of redo data (the RedoList).
Undoing an action will pop the last action from the UndoList and push it onto a RedoList. Redo will perform the reverse - pop from the RedoList, push onto the UndoList.
At its simplest, undo / redo data will contain the 'before' and 'after' states of some object in the application, and the function command that will operate on that data.
So for example, if an action adds the next character 'd' to the Collection "MyCollection" (which currently contains 'a', 'b' and 'c'), the undo data might look like this:
Before: Collection c1 = "a, b, c"
After: Collection c2 = "a, b, c, d"
Command: func(Collection before, Collection after)
{
MyCollection = after;
}
If we ask the undo manager to undo this action, 'func' gets called with 'before = c2', and 'after = c1'. If asked to redo the action, the 'before' and 'after' are switched, so 'before = c1' and 'after = c2'.
Easy, right?
Some questions: How do we create c1 and c2? Are they each a clone of "MyCollection"? What if the collection contains something a bit more complicated than characters, say class objects? What if the objects are collections themselves? Should c1 and c2 be shallow copies or deep copies of MyCollection? How expensive is it to deep copy c1?
In adding 10 items to the collection (say 'a' through 'j'), the first undo action will consist of an empty collection, and a collection containing 'a'. The undo action for adding 'b' to the collection will contain a collection containing an 'a' and a collection containing an 'a' and a 'b'. The next action will contain {'a', 'b'} and {'a', 'b', 'c'}. By the 10th action, there will be 100 items in the undo manager (({}, {a}) + ({a},{a,b}) + ... + ({a..i},{a..j})). Not so bad with characters, but what if you have more complex classes?
And what if those class objects are registered with callbacks elsewhere in the code to have things happen to them in certain situations? Should each instance of the class object in the undo manager remain registered? Should items added to the undo manager have their callbacks revoked and reinstated when the relevant undo / redo command is called?
So instead of storing 'before' and 'after' undo data, an alternative would be to store the data and command required to change the data from the 'before' state to the 'after' state (and the command and data required to change the data back) - 'undo' data and 'redo' data respectively.
So in the character collection example above, the first undo data might look something like this:
UndoData: Item index = 4
RedoData: Character chr = 'd'
UndoCommand: func(UndoData und)
{
MyCollection.Remove(und.index)
}
RedoCommand: func(RedoData red)
{
MyCollection.Add(red.chr)
}
Easy, right?
Some thoughts: The UndoCommand is essentially a "delete function", and the RedoCommand is essentially an "add function".
So when creating the "add action", let's pass the "add function" and the "delete function" as the UndoCommand and the RedoCommand respectively.
When creating a "delete action", let's pass the "delete function" and the "add function" as the UndoCommand and the RedoCommand respectively.
So what was 2 functions before the undo manager (the "add action" and the "delete action") has become 4 functions with the undo manager (the "add action", the "add function", the "delete action" and the "delete function").
Every action has been split into a "put these commands into the undo manager" function, and an "execute the action" function. That's a whole lotta work to retro-fit the undomanager into an existing app.
Final situation to think about. How do you undo continuous changes? I use the mouse to drag a UI object from point A to point Z, but before I release the mouse button I've dragged the UI object through every point in between. Do we store every intermediate point in the undo manager, or just the start and end points?
It's a rhetorical question; of course I'm only going to store the start and end points. How?
Without an undo manager, every mouse-move event could simply set the UI object's x and y co-ordinates.
Mouse::Move(int x, int y)
{
ui_object.SetPosition(x, y);
}
UIObject::SetPosition(int x, int y)
{
this.X = x;
this.Y = y;
}
How do we make moving a UI object undoable? We're going to need to split the action up into distinct parts.
While we're dragging the object, we would like to see it being displayed in its current location, so the X and Y values will still need to be changing continuously. What we'll need to do is remember the start location when we begin dragging, and the end location when we finish dragging, then add those locations to the undo manager, along with appropriate functions for setting them.
We end up with something like this:
Mouse::BeginDrag()
{
Point startPos = ui_object.currentPos;
}
Mouse::Move()
{
ui_object.SetPosition(x, y);
}
Mouse::EndDrag()
{
Point endPos = ui_object.currentPos;
if (startPos != endPos)
{
UndoAction act;
act.UndoData = startPos;
act.RedoData = endPos;
act.UndoCommand = UIObject::SetPosition;
act.RedoCommand = UIObject::SetPosition;
}
}
So what seems like it should be a simple enough mechanism, actually turns out to be pretty darn complicated...
Labels:
Programming
Wednesday, 18 June 2008
Early Out
A quick post on multiple return points. Some people will argue that they are a Bad Thing(TM), but I would like to post my reasons for using them in my code. First of all, what do I mean by multiple return points? I mean that a function has more than one return statement in it.
In this code, there are no less than 4 return points. The trouble happens when you have temporal coupling (requiring that things happen in a certain order).
If this code was written with the requirement that doSomeStuff() was called before exiting, and then the precondition / return 0 code was written afterwards, then the requirement is not met. So yes, in this case, it was wrong to have the multiple exit points.
But I would argue that there are good reasons to write code with multiple exit points.
Yesterday's post recommended that a function should only do one thing. If when calling the quiteMessy() function we expect to calculate a value and call doSomeStuff then that's two things, not one. If we put the two things into separate functions, we would remove the temporal coupling within the quiteMessy() function.
Ok, so reducing the amount we do in one function makes it easier for us to return early on in the function, but I still haven't given you my reason for multiple exit points in a function.
My reason is to improve readability of the function. I tend to base my functions on two possible patterns.
The first is that the entire function's purpose happens at the end of the function. I see the rest of the function as a crescendo, leading up to the one thing that the function does.
If I was going to return early from a function, I'd try to do it as early as possible. So I end up with some kind of precondition at the top of the function (check if it has already been done, check if it's valid to do this now, etc), followed by any setup code which is necessary for the build up to the final action of whatever it is that I want the function to do.
In the code sample above, even though there are three return points in the function, I've kept within the guidelines of the pattern. The first two return points are within the first two statements of the function - the preconditions, there are no return points during the setup of the result, and the main return point is on the last line of the function.
If that sample was written without multiple return points, I would have to nest the calculation within both preconditions.
It no longer feels as though calculating the result is the important thing. I prefer to keep my focus at the top level of the function, rather than nesting several layers in. Nested code is a deviation from the straightforward path of the function, and makes the code more difficult to understand.
The second pattern I base my functions on is doing the thing that I called the function for at the first opportune moment.
One possible example of this would be finding a value.
Searching through the items in this code sample, I would like to return the result as soon as I find it, but I also have a return point at the end of the function in case the item wasn't found. Without multiple return points, I would have to store the result in a temporary value before returning it - what a waste of time that would be!
Another example of this pattern would be if I had a cached value, or both quick and slow methods of getting the result. (Presumably the quick method has drawbacks, otherwise you'd never use the slow method!).
I dread to think what the single return point version of this code would look like!
Earlying out of a function is fine, as long as it makes the code easier to read and understand.
function quiteMessy(param1, param2, param3)
{
if (precondition)
return 0;
for (i = 1 to 10)
{
if (something(i))
return i * param1;
}
doSomeStuff();
doSomeMoreStuff();
if (condition(param2))
return param2 * param3;
doEvenMoreStuff();
andMoreStuff();
val = doSomethingWith(param3);
return val;
}
In this code, there are no less than 4 return points. The trouble happens when you have temporal coupling (requiring that things happen in a certain order).
If this code was written with the requirement that doSomeStuff() was called before exiting, and then the precondition / return 0 code was written afterwards, then the requirement is not met. So yes, in this case, it was wrong to have the multiple exit points.
But I would argue that there are good reasons to write code with multiple exit points.
Yesterday's post recommended that a function should only do one thing. If when calling the quiteMessy() function we expect to calculate a value and call doSomeStuff then that's two things, not one. If we put the two things into separate functions, we would remove the temporal coupling within the quiteMessy() function.
Ok, so reducing the amount we do in one function makes it easier for us to return early on in the function, but I still haven't given you my reason for multiple exit points in a function.
My reason is to improve readability of the function. I tend to base my functions on two possible patterns.
The first is that the entire function's purpose happens at the end of the function. I see the rest of the function as a crescendo, leading up to the one thing that the function does.
If I was going to return early from a function, I'd try to do it as early as possible. So I end up with some kind of precondition at the top of the function (check if it has already been done, check if it's valid to do this now, etc), followed by any setup code which is necessary for the build up to the final action of whatever it is that I want the function to do.
function calculateSomething(param1)
{
// preconditions
if (nonExistent)
return null;
if (invalidParam(param1)
return null;
// setup result
foo = preprocess(param1);
bar = barify(foo);
baz = bar.getBaz();
// return result
result = baz.getValue();
return result;
}
In the code sample above, even though there are three return points in the function, I've kept within the guidelines of the pattern. The first two return points are within the first two statements of the function - the preconditions, there are no return points during the setup of the result, and the main return point is on the last line of the function.
If that sample was written without multiple return points, I would have to nest the calculation within both preconditions.
function calculateSomething(param1)
{
result = null;
if (exists)
{
if (validParam(param1)
{
foo = preprocess(param1);
bar = barify(foo);
baz = bar.getBaz();
result = baz.getValue();
}
}
return result;
}
It no longer feels as though calculating the result is the important thing. I prefer to keep my focus at the top level of the function, rather than nesting several layers in. Nested code is a deviation from the straightforward path of the function, and makes the code more difficult to understand.
The second pattern I base my functions on is doing the thing that I called the function for at the first opportune moment.
One possible example of this would be finding a value.
function findThing(param1)
{
for (ix = 1 to itemCount)
{
candidate = item[ix];
if (candidate.name == param1)
return candidate;
}
return Not_found;
}
Searching through the items in this code sample, I would like to return the result as soon as I find it, but I also have a return point at the end of the function in case the item wasn't found. Without multiple return points, I would have to store the result in a temporary value before returning it - what a waste of time that would be!
Another example of this pattern would be if I had a cached value, or both quick and slow methods of getting the result. (Presumably the quick method has drawbacks, otherwise you'd never use the slow method!).
function calculateOptimal(param1)
{
cachedResult = cached(param1);
if (cachedResult != null)
return cachedResult;
if (canCalcQuickly(param1))
return calcQuickly(param1);
// otherwise
return calcSlowly(param1);
}
I dread to think what the single return point version of this code would look like!
Earlying out of a function is fine, as long as it makes the code easier to read and understand.
Labels:
Programming
One task, One place
Today's advice is nicely summed up by the saying "A place for everything, and everything in it's place." Like any of my advice, you can choose to ignore it, or even contradict it. If anyone has advice I like better, I'll follow their advice instead.
The DRY principal (don't repeat yourself) says that any complex task should only be carried out in one place.
Why? The end user doesn't care if you repeat yourself. The computer certainly doesn't care if you repeat yourself. In the end, it turns out that the people who care whether you repeat yourself are the developers of your code (including yourself). Again, it boils down to programming for people.
Duplication is a Bad Thing(TM) for several reasons. The most obvious reason is that if you have some duplicate code, and discover a bug in that code, you could fix it in one of the places and completely forget about the other places. So in fact, the bug isn't fixed. Now if the duplicate code had been written as one function that was called from the places where that code was needed, instead of duplicated, the bug fix would only need to go in one place.
(I'm going to ignore the advice and repeat myself here because this is important!) The bug fix would only need to go in one place! When you've come up with a fix, there's no need to trawl through the codebase looking for all the places that the fix needs applying because the places that need this code all pass through the single place that you have applied the fix.
The second reason to avoid duplication is that duplication makes code more difficult to read, and comprehend. Which is easier to understand - 10 lines of code, or 20 lines of code? For the sake of argument, let's assume that each of the individual lines is as understandable (or obtuse!) as each other line.
Less lines of code means less to understand, means less to misunderstand! Sure, if someone takes the time to pick apart the code line by line, they might eventually understand it. But first glance isn't going to give us as quick an overview if there is twice as much code there than is really necessary. Also, if you wrap the duplicate code up into a single function, even the function name can help comprehension. Compare
Sample1:
vs Sample2:
Now the arrangeMeeting() function may still not make much sense, but at least we now know that this chunk of code is meant to arrange a meeting between people. If we are interested in the details of what the bigFunc() does, we only have to read through the horrible mess of bar(), baz() and abc_def() once (if at all). And of course, any mistakes in the meeting code will only need to be corrected once in the arrangeMeeting function.
The two samples lead quite nicely to my second point today, which is:
In any one place, only one task should be carried out.
Instead of having to digest the entirety of the bigFunc() in sample1, (and possibly getting indigestion), the code in bigFunc() in sample2 is much easier to digest. The code that deals with arranging meetings has been moved off into its own function, and we are left with much smaller, bite-size chunks of code to deal with.
If you find that you're writing one comment about several lines of code, several times in a function, then each of those chunks of code could well be ripe for turning into a function of its own.
A program should be like a well structured document, with an overall view, chapters (modules), headings (classes), and sub headings (functions), and it should be easy for a reader to drill down to the place that they're interested in. You can go a long way towards achieving this by having a place for everything, and keeping everything in it's place.
The DRY principal (don't repeat yourself) says that any complex task should only be carried out in one place.
Why? The end user doesn't care if you repeat yourself. The computer certainly doesn't care if you repeat yourself. In the end, it turns out that the people who care whether you repeat yourself are the developers of your code (including yourself). Again, it boils down to programming for people.
Duplication is a Bad Thing(TM) for several reasons. The most obvious reason is that if you have some duplicate code, and discover a bug in that code, you could fix it in one of the places and completely forget about the other places. So in fact, the bug isn't fixed. Now if the duplicate code had been written as one function that was called from the places where that code was needed, instead of duplicated, the bug fix would only need to go in one place.
(I'm going to ignore the advice and repeat myself here because this is important!) The bug fix would only need to go in one place! When you've come up with a fix, there's no need to trawl through the codebase looking for all the places that the fix needs applying because the places that need this code all pass through the single place that you have applied the fix.
The second reason to avoid duplication is that duplication makes code more difficult to read, and comprehend. Which is easier to understand - 10 lines of code, or 20 lines of code? For the sake of argument, let's assume that each of the individual lines is as understandable (or obtuse!) as each other line.
Less lines of code means less to understand, means less to misunderstand! Sure, if someone takes the time to pick apart the code line by line, they might eventually understand it. But first glance isn't going to give us as quick an overview if there is twice as much code there than is really necessary. Also, if you wrap the duplicate code up into a single function, even the function name can help comprehension. Compare
Sample1:
function bigFunc()
{
setDay(15);
bar(fred.location.x, fred.holiday.x);
baz(bob.foobar(X, Y, Z));
abc_def(fred, bob, saz.ABC);
setDay(25);
bar(sam.location.x, sam.holiday.x);
baz(jane.foobar(X, Y, Z));
abc_def(sam, jane, saz.ABC);
}
vs Sample2:
function bigFunc()
{
setDay(15);
arrangeMeeting(fred, bob);
setDay(25);
arrangeMeeting(sam, jane);
}
function arrangeMeeting(Person p1, Person p2)
{
bar(p1.location.x, p1.holiday.x);
baz(p2.foobar(X, Y, Z));
abc_def(p1, p2, saz.ABC);
}
Now the arrangeMeeting() function may still not make much sense, but at least we now know that this chunk of code is meant to arrange a meeting between people. If we are interested in the details of what the bigFunc() does, we only have to read through the horrible mess of bar(), baz() and abc_def() once (if at all). And of course, any mistakes in the meeting code will only need to be corrected once in the arrangeMeeting function.
The two samples lead quite nicely to my second point today, which is:
In any one place, only one task should be carried out.
Instead of having to digest the entirety of the bigFunc() in sample1, (and possibly getting indigestion), the code in bigFunc() in sample2 is much easier to digest. The code that deals with arranging meetings has been moved off into its own function, and we are left with much smaller, bite-size chunks of code to deal with.
If you find that you're writing one comment about several lines of code, several times in a function, then each of those chunks of code could well be ripe for turning into a function of its own.
A program should be like a well structured document, with an overall view, chapters (modules), headings (classes), and sub headings (functions), and it should be easy for a reader to drill down to the place that they're interested in. You can go a long way towards achieving this by having a place for everything, and keeping everything in it's place.
Labels:
Programming
Friday, 6 June 2008
C# Attributes
Just a short post today. Though I'll try to stick to generally applicable programming techniques / articles / entries, I'll occasionally go language or technology specific.
I'm loving working in C# - I only really started C# programming about a year ago and I'm learning more and more about it and really enjoying it.
When I discovered the Property Grid, I thought it was fantastic. The property grid is used to expose properties to the user. The user can view or edit these properties, depending on whether get and set methods are defined. You can do a whole host of things with the property grid, such as putting properties into categories with the Category attribute, specifying default values with the DefaultValue attribute, and you can even specify that a property isn't shown in the grid with the Browsable attribute.
Pretty soon after learning about the property grid, I was using it for everything. Then one day I decided that it would be useful if I could dynamically change what was shown in the property grid at runtime.
I spent a whole day looking for information on how to change attributes at run time. I learned about reflection, I learned about creating attributes, I learned about applying attributes. But I couldn't find out how to change attributes dynamically.
I could have saved a whole day if I'd learned at the start that attributes are compiled into the executable and can't be changed on the fly.
So I'm posting this so that there's a million to one chance that if somebody else is searching for how to change attributes dynamically, they get to read this early on and don't waste the amount of time I did.
Update: 5th July 2008
I've posted some more information on dynamic property grids, in case you were looking for it.
I'm loving working in C# - I only really started C# programming about a year ago and I'm learning more and more about it and really enjoying it.
When I discovered the Property Grid, I thought it was fantastic. The property grid is used to expose properties to the user. The user can view or edit these properties, depending on whether get and set methods are defined. You can do a whole host of things with the property grid, such as putting properties into categories with the Category attribute, specifying default values with the DefaultValue attribute, and you can even specify that a property isn't shown in the grid with the Browsable attribute.
Pretty soon after learning about the property grid, I was using it for everything. Then one day I decided that it would be useful if I could dynamically change what was shown in the property grid at runtime.
I spent a whole day looking for information on how to change attributes at run time. I learned about reflection, I learned about creating attributes, I learned about applying attributes. But I couldn't find out how to change attributes dynamically.
I could have saved a whole day if I'd learned at the start that attributes are compiled into the executable and can't be changed on the fly.
So I'm posting this so that there's a million to one chance that if somebody else is searching for how to change attributes dynamically, they get to read this early on and don't waste the amount of time I did.
Update: 5th July 2008
I've posted some more information on dynamic property grids, in case you were looking for it.
Labels:
C#,
Programming
Thursday, 29 May 2008
Evolving features
Yesterday's post ended with a teaser - why store the result of a function before returning it? The answer is (unsurprisingly, given the nature of this blog) to make it easier to access for a human. Specifically, when somebody (most often myself) is debugging a function that I have written, it's much nicer to be able to see the result of a function call immediately in the debugger or watch window, than having to step into the function and see what the result will be.
Today I'd like to post a response to Abhinaba Basu's The WOW factor in software. There are quite a few blogs that I'm reading at the moment, Abhinaba's being the most recent I've added to my list, and I'm enjoying reading it.
Abhinaba talks about the "nifty" features that turn good software into great software. Then he mentions
"the other category of software which doesn't work in first place and tries to be smart on top of it. There's nothing worse than this. You look at these in disgust and head over to the dumber but working competition."
Now the end-user doesn't care about how many hours a programmer has put into a project, lovingly crafting it, starting from an empty source file, and putting not just time, but pouring their heart and soul into a piece of software. The end-user doesn't care that the software is like one of the programmer's children. No, the end-user wants a piece of software that will do what he wants it to do, and won't crash, or loose his work. And Abhinaba is right when he says that the user will look at these in disgust and head over to the working competition. But I get the impression that the message is "get the thing working before adding the polish".
My point (I knew we'd get to it sooner or later) is that when a user sees this happen, they would assume that the programmer has been working on the nifty features to the detriment of the core functionality. But I don't think this is true.
Programmers don't like their creations to have bugs in them. The bugs are a poor reflection on themselves. They don't deliberately leave bugs in, add some sparkle and hope nobody notices the flaws. Software is released when the creator thinks it is ready. Unfortunately, the software isn't always ready and as we all know, bugs are always ready to rear their ugly heads, right when we least expect it.
In an ideal world, maybe all the core functionality would be written and tested, and there would still be budget for the extras. In reality, what often happens is once the core functionality is in, the product is shipped and we're off onto the next task. If features aren't evolved alongside the rest of the project, then they'll often fall by the wayside.
Recently I was writing a tool for drawing flow diagrams. Now basic functionality was there - lines could be drawn from one shape to the next. Straight lines. No routing. If you wanted to go around corners, you could add nodes - one at a time - to the line, and drag these nodes into the correct place. This was painstakingly slow, but it was functional - it provided all the functionality required to describe flows.
But then in my own time I spent a whole day putting in automatic routing for lines. Now lines will have a sensible number of nodes, in sensible positions, by default. This makes the tool a lot more natural to use. Is it required for core functionality? No - it's a feature. Is the software finished? No - there are still plenty of bugs to be ironed out and core work to be done. It's constantly being updated. But before I added automatic routing, it took ages to draw a flow. Now it takes minutes.
Shock! Horror! Working on features when there's still core work to be done! But if I hadn't written these features before the core work was finished, then they wouldn't have been added at all - it would have been time to move on.
If you want your software to stand out from the rest, you need the wow factor. If you want the features for wow factor, then you need to be working on them NOW. Otherwise, they'll be left behind - as will your software.
Today I'd like to post a response to Abhinaba Basu's The WOW factor in software. There are quite a few blogs that I'm reading at the moment, Abhinaba's being the most recent I've added to my list, and I'm enjoying reading it.
Abhinaba talks about the "nifty" features that turn good software into great software. Then he mentions
"the other category of software which doesn't work in first place and tries to be smart on top of it. There's nothing worse than this. You look at these in disgust and head over to the dumber but working competition."
Now the end-user doesn't care about how many hours a programmer has put into a project, lovingly crafting it, starting from an empty source file, and putting not just time, but pouring their heart and soul into a piece of software. The end-user doesn't care that the software is like one of the programmer's children. No, the end-user wants a piece of software that will do what he wants it to do, and won't crash, or loose his work. And Abhinaba is right when he says that the user will look at these in disgust and head over to the working competition. But I get the impression that the message is "get the thing working before adding the polish".
My point (I knew we'd get to it sooner or later) is that when a user sees this happen, they would assume that the programmer has been working on the nifty features to the detriment of the core functionality. But I don't think this is true.
Programmers don't like their creations to have bugs in them. The bugs are a poor reflection on themselves. They don't deliberately leave bugs in, add some sparkle and hope nobody notices the flaws. Software is released when the creator thinks it is ready. Unfortunately, the software isn't always ready and as we all know, bugs are always ready to rear their ugly heads, right when we least expect it.
In an ideal world, maybe all the core functionality would be written and tested, and there would still be budget for the extras. In reality, what often happens is once the core functionality is in, the product is shipped and we're off onto the next task. If features aren't evolved alongside the rest of the project, then they'll often fall by the wayside.
Recently I was writing a tool for drawing flow diagrams. Now basic functionality was there - lines could be drawn from one shape to the next. Straight lines. No routing. If you wanted to go around corners, you could add nodes - one at a time - to the line, and drag these nodes into the correct place. This was painstakingly slow, but it was functional - it provided all the functionality required to describe flows.
But then in my own time I spent a whole day putting in automatic routing for lines. Now lines will have a sensible number of nodes, in sensible positions, by default. This makes the tool a lot more natural to use. Is it required for core functionality? No - it's a feature. Is the software finished? No - there are still plenty of bugs to be ironed out and core work to be done. It's constantly being updated. But before I added automatic routing, it took ages to draw a flow. Now it takes minutes.
Shock! Horror! Working on features when there's still core work to be done! But if I hadn't written these features before the core work was finished, then they wouldn't have been added at all - it would have been time to move on.
If you want your software to stand out from the rest, you need the wow factor. If you want the features for wow factor, then you need to be working on them NOW. Otherwise, they'll be left behind - as will your software.
Labels:
Programming
Wednesday, 28 May 2008
Dots and Double Dots
I love the phrase "train wreck". To clarify, I'm not talking about real life transport accidents here. I'm talking about the phrase used to describe code.
I think I first discovered the phrase in Code Complete, though I can't pin down the exact quote.
Basically it refers to code that refers to members of members of members of members... so for example
(I guess the dots "." are the coupling between carriages and the method names are the carriages. Or something).
The phrase seems to say "some terrible disaster has happened here". When there are that many decompositions in a single line of code, if the disaster hasn't already happened yet, it soon will.
One accident (or several) waiting to happen here is - one of the functions along the way could return a null pointer. If any of the intermediate elements is an invalid value then this piece of code is going to crash.
So at the very least, we should be testing for null values. Now, say we wanted the inventory of player 1, and assuming we know that the PlayerManager is valid, one way of writing this (with null value testing included) is:
However, I'm not happy with that piece of code. I'm an advocate of Programming for People. But a person reading that code sample would have to do more mental decomposition than necessary. Which I would find impolite. Here's what I mean by mental decomposition:
First we read "PlayerManager" (right, so I've got this player manager), then we read ".GetPlayer(1)" (right so we've got player 1 of the player manager). Then we test this for null with " != null". (Ok, test if the player manager's player 1 is null).
Once we've got past this line of code, it would be nice to assume we could throw away our mental stack, and start with a clean slate, if you will. So we've passed the test in the "if" statement. Then we're going to assign to our inv variable. We'll take the playerManager, we'll get player 1 of the player manager, then we'll take the inventory of player 1 of the player manager. Ouch - my head hurts.
I would nearly always write that previous code sample as the following:
Now, when I read that code, I see that Player 1 of the player manager is being assigned to a local variable - so I know this player is of interest. So I'll keep this player in my mental stack. Then I'll test that "this player" is not null. Then if I pass the test, I'll get the inventory of "this player". And this time, I had less mental decomposition.
And if nothing else, we've given the code more room to breathe! The train wrecks of the first example are hard on the eyes - it's hard to see where one element ends and the next begins. With the rewrite, the test and assignments are in much smaller and easier-to-digest chunks.
Rewriting the entire example, I would almost always write out the original train wreck as follows:
The Law of Demeter says that you're only allowed to talk to your immediate neighbours. Strictly in the example above, I think I am allowed to ask the PlayerManager to do something, but I'm not allowed to ask the player to do something. Or the inventory. Or the weapons. And so on. But there are always exceptions to rules.
In this case, I think that if the GetCurrentAmmo function is in a class that made the most sense to know about getting the current player's ammo, then I'm fine with the multiple levels of indirection here. Otherwise each of the intermediate classes between this class and the Weapon class would need a "GetCurrentAmmo" forwarding function, which I feel would be a lot of extra code for little gain.
One last note on the code example - I've stored the result of the final "GetAmmo" function call before returning it. I'll explain why next time :)
Whenever I see the same "dot" phrase being used more than once in a function, I cringe. If the dot phrase happens to be a "double dot" phrase, I'll cringe even more. If a phrase repeats when it has more than 2 dots in it then I'll be sad that the person who wrote that code wasn't Programming for People.
I think I first discovered the phrase in Code Complete, though I can't pin down the exact quote.
Basically it refers to code that refers to members of members of members of members... so for example
Ammo GetCurrentAmmo()
{
PlayerManager.GetPlayer(1).GetInventory().GetWeapons()[0].GetAmmo();
}
(I guess the dots "." are the coupling between carriages and the method names are the carriages. Or something).
The phrase seems to say "some terrible disaster has happened here". When there are that many decompositions in a single line of code, if the disaster hasn't already happened yet, it soon will.
One accident (or several) waiting to happen here is - one of the functions along the way could return a null pointer. If any of the intermediate elements is an invalid value then this piece of code is going to crash.
So at the very least, we should be testing for null values. Now, say we wanted the inventory of player 1, and assuming we know that the PlayerManager is valid, one way of writing this (with null value testing included) is:
if (PlayerManager.GetPlayer(1) != null)
inv = PlayerManager.GetPlayer(1).GetInventory();
However, I'm not happy with that piece of code. I'm an advocate of Programming for People. But a person reading that code sample would have to do more mental decomposition than necessary. Which I would find impolite. Here's what I mean by mental decomposition:
First we read "PlayerManager" (right, so I've got this player manager), then we read ".GetPlayer(1)" (right so we've got player 1 of the player manager). Then we test this for null with " != null". (Ok, test if the player manager's player 1 is null).
Once we've got past this line of code, it would be nice to assume we could throw away our mental stack, and start with a clean slate, if you will. So we've passed the test in the "if" statement. Then we're going to assign to our inv variable. We'll take the playerManager, we'll get player 1 of the player manager, then we'll take the inventory of player 1 of the player manager. Ouch - my head hurts.
I would nearly always write that previous code sample as the following:
Player player = PlayerManager.GetPlayer(1);
if (player != null)
inv = player.GetInventory();
Now, when I read that code, I see that Player 1 of the player manager is being assigned to a local variable - so I know this player is of interest. So I'll keep this player in my mental stack. Then I'll test that "this player" is not null. Then if I pass the test, I'll get the inventory of "this player". And this time, I had less mental decomposition.
And if nothing else, we've given the code more room to breathe! The train wrecks of the first example are hard on the eyes - it's hard to see where one element ends and the next begins. With the rewrite, the test and assignments are in much smaller and easier-to-digest chunks.
Rewriting the entire example, I would almost always write out the original train wreck as follows:
Ammo GetCurrentAmmo()
{
Player player = PlayerManager.GetPlayer(1);
if (player == null)
return null;
Inventory inv = player.GetInventory();
if (inv == null)
return null;
Weapon[] weapons = inv.GetWeapons();
if (weapons.Length == 0)
return null;
Weapon currentWeapon = weapons[0];
if (currentWeapon == null)
return null;
Ammo currentAmmo = currentWeapon.GetAmmo();
return currentAmmo;
}
The Law of Demeter says that you're only allowed to talk to your immediate neighbours. Strictly in the example above, I think I am allowed to ask the PlayerManager to do something, but I'm not allowed to ask the player to do something. Or the inventory. Or the weapons. And so on. But there are always exceptions to rules.
In this case, I think that if the GetCurrentAmmo function is in a class that made the most sense to know about getting the current player's ammo, then I'm fine with the multiple levels of indirection here. Otherwise each of the intermediate classes between this class and the Weapon class would need a "GetCurrentAmmo" forwarding function, which I feel would be a lot of extra code for little gain.
One last note on the code example - I've stored the result of the final "GetAmmo" function call before returning it. I'll explain why next time :)
Whenever I see the same "dot" phrase being used more than once in a function, I cringe. If the dot phrase happens to be a "double dot" phrase, I'll cringe even more. If a phrase repeats when it has more than 2 dots in it then I'll be sad that the person who wrote that code wasn't Programming for People.
Labels:
Programming
Sunday, 25 May 2008
Programming for People
I believe that the best piece of programming advice I ever read was "Write your code so it's easy to read."
I've been programming for about 20 years, and I've read advice like "always comment your code" and "choose sensible variable names", but it never really sunk in. I didn't understand the reason behind this advice. Now in the last couple of years I think I finally understand the reason why: Code is written once, but read many times.
It might take you a long time to write a good, solid routine that performs the exact function that you want. And it might take you even longer to write the code so another person can understand it, so you think "why bother?" But at the end of the day, the investment is worth it, because whilst you only write that function once, coders will read that function many many times. And when I say coders will read that function, I'm also including you. You will re-read that function. Whenever you need to perform some maintenance coding, when you need to make a subtle change to the effect of the function, when you need to refactor your code - even when you're just looking through the code, trying to find "that routine that I wrote last week - I know it was something to do with...", you'll appreciate the extra effort you went into to make the code easy to read.
Because I finally came to realise, that if I want to be a good programmer, then I need to write my code primarily for a person to read, and only secondarily for a computer to read!
That was probably a bit of a controversial statement there! But the way I see it, for all but the most trivial functions, if a piece of code is written without human-readability in mind, and there's a bug, it's gonna take a heck of a long time to track that bug down. But if the code was written for a person to read, then it will take a fraction of that time to find the bug, because less time is spent trying to understand the code - the code is amenable to human understanding, and so time can be spent, more effectively, hunting down that bug.
In conclusion:
I've been programming for about 20 years, and I've read advice like "always comment your code" and "choose sensible variable names", but it never really sunk in. I didn't understand the reason behind this advice. Now in the last couple of years I think I finally understand the reason why: Code is written once, but read many times.
It might take you a long time to write a good, solid routine that performs the exact function that you want. And it might take you even longer to write the code so another person can understand it, so you think "why bother?" But at the end of the day, the investment is worth it, because whilst you only write that function once, coders will read that function many many times. And when I say coders will read that function, I'm also including you. You will re-read that function. Whenever you need to perform some maintenance coding, when you need to make a subtle change to the effect of the function, when you need to refactor your code - even when you're just looking through the code, trying to find "that routine that I wrote last week - I know it was something to do with...", you'll appreciate the extra effort you went into to make the code easy to read.
Because I finally came to realise, that if I want to be a good programmer, then I need to write my code primarily for a person to read, and only secondarily for a computer to read!
That was probably a bit of a controversial statement there! But the way I see it, for all but the most trivial functions, if a piece of code is written without human-readability in mind, and there's a bug, it's gonna take a heck of a long time to track that bug down. But if the code was written for a person to read, then it will take a fraction of that time to find the bug, because less time is spent trying to understand the code - the code is amenable to human understanding, and so time can be spent, more effectively, hunting down that bug.
In conclusion:
- Code is Write Once Read Many
- Write the code so it's easy to read
- Code primarily for a person to read, and secondarily for a computer to read.
Labels:
Programming
Subscribe to:
Posts (Atom)