Archive for the ‘Code and Development’ Category
July 3rd, 2008
There is something called defensive programming http://en.wikipedia.org/wiki/Defensive_programming that is supposedly something good. I believe so too but it might have a way of hiding bugs.
In defensive programming you recieve data and inspect it for flaws. When it is possible you manipulate the data so it is correct and usable again. This is good so as much your code works.
But when you are in a project where your code is just a cog in a bigger machinery this approach is not necessarily the best; by recieving and hiding flawed data a bug somewhere else is hidden.
In the example in Wikipedia a string limited to 1000 characters is manipulated. The suggested solution is to truncate the string and keep rowing as if there wasn’t a leak in the first place. Depending on the circumstances the bug might be at the caller and by removing the very bug instead of the symptoms the very problem disappears.
According to Fail at once an error should surface as soon and close to the source as possible. The chances for data resulting of the bug to propagate, is then smaller and the bug tracking is probably faster.
In the example it would have been better to throw an exception than to just keep on with data, now faulty in another way than to start with.
Or like this: if a user writes an essay of 2000 characters he probably wants to know that it cannot be saved the very moment ctrl-S is pressed instead of 2 days later when proof reading, when the last 1000 characters are gone both from mind and binary space. Or an operator of a tube bending machine prefers to know if his machine is faulty when he is working at it instead of two weeks later when the tubes are buried inside a wall somewhere.
About 4 years after I wrote the above I found that at least one more has the same opinion (pdf); someone way more known than I.
June 29th, 2008
I have written 2 articles tagged as Fail at once without explaining what the filosophy behind the name is. Shame on me.
It is an old truth that the earlier a bug is found the cheaper it is to fix.
Automated tests tests things that can go wrong; but what if those things couldn’t even go wrong in the first place?
Code that won’t compile won’t make it into production. Ever.
It is cheapest to not write any errors at all.
Today Fail at once does two things: It stops compiling when it notices something is wrong and at all other times it tries to help the programmer do the right thing.
Typical example of the first is to always use type safe variables and the latter to name things in such a way that there is one very natural way to write the code. By using this explicitly and intelligently you get a leverage for writing better code faster.
June 18th, 2008
The default constructor
public Customer()
{
}
is seldom needed while working with business objects. Honestly – how do you need an object that is not fully populated? Do you have a Customer or do you not? A few situations comes to mind where an almost-Customer is needed but they all smell of refactoring, i.e. base class, sub class and two constructors.
To make sure I don’t have an object that is not fully populated I make sure the default constructor is not reachable. Either through creating other constructors or by making it private the times it is needed internally. Instead I create a constructor that takes all necessary parameters to fully populate itself. If there are variants I create more constructors. I am not afraid of writing code but I strongly dislike putting bugs into production. Hence Fail At Once.
Sometimes it is handy to have a “Set” method taking all parameters and calling it from the constructor but this is just a variant of the pattern above that objects that are not correctly populated are very seldom useful.
If you don’t like writing “normal” constructors them make them static and call them Create or something obvious.
Another advantage with this routine is when adding (or removing) mandatory fields. Then there is one and only one place to update to make the compiler show you all places to update.
I have noticed that it is hard to make lists in the GUI without having a default constructor but this, I presume, is just the exception that confirms the rule.
Bugs that can’t compile will not go into production.
June 16th, 2008
Avoid casting types.
Why do I write about this? What has it do do with quality and projects and architecture? Well… each thing that cannot break doesn’t have to be tested and… cannot break. Less testing, less coding, less bugs.
When working with class libraries that are dependant on the generic type one cannot avoid type casting fully. The solution then is to encapsulate and wrap the cast through inheritance or composition.
If you wrap your type cast you have 1 test case instead of a test case per call.
What about datagrids and combo boxes that have an internal Rows or Items collection or Tag attribute? How can they become type safe without having to rewrite the whole control? Unfortunately I don’t have a perfect solution but as I have seen the evil in type casts I avoid them and instead of writing test cases and tests I spend some time looking for a type safe alternative. These are typically called row.OrderTag or combobox.CustomerItems. Overriding the method or attribute is not possible since one cannot change type; but one can override and set the [Obsolete] attribute to at least get a warning. Pepper this with a Debug.Fail( ”Please use the OrderTag property instead.” ) and things will stop in any test case that runs it. Many times one can even set the compiler to fail with [Obsolete(true)] to be totally sure the call is never made.
Another problem then is when two different types really are returned. Well… write two methods then. Even overload them; as long as the compiler understands your goal.
Final thought: How should one get this type of thinking into the spine of a project? It is not something that can be ordered but has to be understood and taken to heart by the involved. If someone has an idea please drop me a line; but until then being a good example is a good beginning.
June 10th, 2008
What if you didn’t have to test your application?
What if you worked together with tools to make sure some bugs never even left the compiler? That would be less to test; faster development cycle and more stable code.
In search of better name I call this Fail At Once.
I will get back on the subject.
Update: I have not gotten back as much as I wanted.
May 13th, 2008
I like unit tests, I really do. But I have also come to realize that many tests don’t have to be done.
One can for instance code according to Fail At Once to make the compiler do the tests.
Or one can autogenerate code and hence only have to unit test a fraction of the resulting code.
Or one can do integration tests and take for granted that if the integration works the unit tests work too.
I have tried all three and believe in laziness – to get more done while working less. So I say that a thought out mix of all three above supposedly is the right way.
Patrik Löwendahl thinks approximately the same.
January 18th, 2008
This message is repeated in English below.
Allting är en bug. Eller snarare: allting är ett ärende.
Oavsett om ärendet skapar en krasch, är fel storlek på loggan eller innebär installation av en UPS är det något som skall tilldelas människa och tid.
Min åsikt är att lägga allting i samma hög. Och med allting menar jag allting. Sedan prioriterar man ärendena och plockar från toppen. Om detta liknar valfri agil metod är det inte för att Henrik Kniberg, Kent Beck och jag har kommunicerat utan för att det är ett bra tillvägagångssätt.
Varje ärende måste ha ett unikt ID. Ett ID som inte hänger ihop med ärenderubriken. Detta unika ID måste gå att säga och skriva; jag föreslår konsekutiv numrering, 1, 2, 3…
För icke-databasssystem använder jag dagens datum följt av 01, 02, ..99 (20080118.01) för att jag brukar kunna hålla antalet ärenden idag i huvudet och har ännu inte råkat ut för fler än 99 på en dag.
Det här med en och samma ärendetyp har Microsoft Team Foundation missat. När man skapar ett ärende i det kan man välja mellan olika ärendetyper och när man har valt kan man inte ändra. TFS är konfigurerbart så man kan säkert välja bort alla ärendetyper utom en, men att det överhuvudtaget finns känns konstigt för mig.
Uppdatering: 20170810: Sedan några år kan man byta typ på ärendet i TFS.
Jag önskar mig ett ärendehanteringssystem där man får en översikt av sina ärenden mer än som bara listor med rubriker. Jag önskar mig en sorts bollar med snören emellan där man smidigt kan se vad som hänger ihop och hur mycket som påverkas om man drar i en av bollarna.
Everything is a bug. Or rather: everything is an task.
Disregarding the issue creates a crash, is the wrong image size or installation and configuration and testing of a UPS it is something that will be given a human and time.
My opinion is that everything should be in the same pile. With everything I mean everything. Then the tasks are prioritised and picked off of the top. I you, dear reader, now recognises and starts looking at your books about agile project methods this is not a coincidence. I am not saying that Henrik Kniberg, Kent Beck and I have communicated but because it is a good method.
Furthermore every task must have a unique ID separated from the title of the task. It must also be short enough to say and write – I suggest just numbering them from 1 and on as they are created. In spreadsheets and other non-database systems where I cannot track the unique key I usually use the format yyyymmdd-nn because one can probably store the number of tasks that day temporarily in the head and I have never written more than 99 issues in one day.
Looking at Microsoft Team Foundation I say that they have stumbled regarding the everything-is-a-task thing since there are several task types (In TFS a task is a special kind of task/issue/item/todo item/bug/…) and once you have chosen one type there is no going back. To their defence I have to mention that TFS is configurable and one can choose to use just one of the types. But the very existence of non-changeable issue types is strange.
Update 20170810: Since a few years it is possible to change the type of an issue in TFS.
On my wish list is an task manager where the browsing and handling of taks are outstanding. I wish of something like balls interconnected with strings and when you juggle one ball you se whatever it pulls/affects.
November 8th, 2007
This message will be repeated in english further down.
Hur får man rättningar och funktionalitet så fort som möjligt genom dörren?
Hur får man så få buggar som möjligt i produktion?
Jag fick en gång kommentaren från en vän “Men du levererar väl aldrig otestad kod?”. Det var en komplimang och en kommentar till att jag just då satt i ett projekt som skulle leverera den högsta kvaliteten jag levererat hittills, dessutom rakt ut i fabrik
Mitt svar förvånade honom “Jag testar inte.” Jag lät honom hämta andan. “Rättning: jag testar så lite som möjligt och mycket kod går rakt ut i produktion otestad.”
Sedan följde en förklaring. En förklaring jag har dragit för alla i projektet:
“Använd kompilatorn för att fånga fel.”
Vanligtvis när man talar om system med hög kvalitet pratar man om testning. Massor med manuella tester med speciella konsulter man hyr in som är specialiserade på test. Dyrt. Men det blir dyrt med hög kvalitet.
Bullshit.
Manuella tester är dyrt och tar lång tid.
Modernare utveckling innehåller enhetstester.
Jag förespråkar Fail At Once för att slippa många enhetstester och manuella dito.
Det är viktigt att fånga fel så fort som möjligt. De allra bästa är att inte skriva dem alls.
Där är jag inte ännu.
How do you ship patches and functionality as fast as possible?
How do you get as few bugs as possible in production?
I once got a comment from a friend “But you never deliver untested code?” It was meant as a compliment and comment to my job then; I was working in a project that was delivering the highest quality I have ever delivered; right onto factory floor.
My answer surprised him “I don’t test.” I let him catch his breath. “Correction: I test as little as possible and as much code as possible goes into production untested.”
I had to explain, the same explanation everyone in the project had heard.
“Use the compiler to catch errors.”
Normally when one talks about high quality system one also mentions testing. Lots of manual tests with consultants specialised on testing. Expensive. But high quality is expensive.
Bullshit.
Manual tests are expensive and take lots of time.
The more modern unit testing is cheaper.
I recommend Fail At Once to get rid of many unit tests and manual ditto.
It is important to catch errors as fast as possible. The best is to not write them at all.
I am not there yet.
October 1st, 2007
Dotnet WinForm has a control called Split container. It is a nice control for making forms scale properly when the user changes their sizes.
Now there is a bug in Vsnet that surfaces when you put split containers in each other and do not change their default names. splitContainer1, splitContainer2 etc.
The remedy is easy: change the name as you create the split containers.
Update:
The bug reveals itself by stopping the designer from rendering the form; instead a text like “a control cannot be in itself” shows.
If that happens you are not totally screwed even though there is no clue to what to do.
Open the .designer file and remove a split control. I have no idea of how to find out which split control messed up. Just remove one. Open the graphical designer (possibly close and open). Repeat until you have a form like usual but the controls you have put on the split controls are gone. Don’t dispair, they are not gone – they are just not placed anywhere.
Drop a split control on the graphical designer. Add controls to it through myListbox.Controls.Add( myTextbox )…. If you do it properly – like adding the right controls to the correct new split control everything is like before. Except possibly event handlers om the split controls. At least you didn’t have to remake the whole form.
September 27th, 2007
A great amount of comments might be a sign of lack of logic in the code.
Well structured code is easy to read and hence needs less comments. What should be commented is non obvious things.
My practical workflow is often like this: I write several lines of code. I insert comments to explain, business wise, what is done, I realise I can refactor into method calls instead of comments and then my method names replace the comments.
Things to comment:
– many if statements have their origin in business rules. This is not obvious when writing/reading code deep down in the layers. Hence the need of comments.
– some coding becomes more elegant with delegates, nameless functions, pointers, inheritance or other tricks that are hard to understand for the not-so-experienced. These blocks of code or one-liners are easier to understand with some comment explaining.
– everything not visible on the screen might be unseen or forgotten. So if a piece of code has a requirement that is not visible in the close surroundings (visible or logical surroundings) a comment might help to keep the code on track.
– sidesteps from the normal path. As a sole developer or in a team one is supposed to follow a standard or normal-way-to-do-things. In those cases this standard is overruled a comment is good; the reason for sidestepping the standard.
I have true tale here:
I was working with damage control at a project and the air was sometimes a bit tense. Especially when the customer was around.
Now this customer asked us if the code was commented. This customer was a pain in the ass to work with and I didn’t feel like behaving so I answered that I thought the need for comments in code was a sigh of crappy coding. The customer didn’t share my point of view. My colleague didn’t either. He also tried to explain that comments are good. I held my fort.
Now to the fun part: My colleague didn’t write comments while I did.
And yes, I was called in because my colleagues code didn’t hold up.