Flotsam and Jetsam #98

  • I’ve been whining about my difficulty in writing a book chapter about the Parallel Programming Library.  I’m getting the hang of it, though, and it is as cool as it’s been touted to be.  In fact, I’d venture to say that once you start using it, you’ll never really need to use TThread again.  The PPL is a nice abstraction of threading, with the notion of a TTask/ITask taking over the role of TThread.  You can pretty much parallelize anything you want with ease.  Very much worth the upgrade, if you are still on a pre-XE7 version.  And completely cross-platform – with nary an {$IFDEF} to be found. 
  • As many of you know, I work on my book at my local Burger King on Saturday and Sunday mornings.  As a result, I drink a lot of iced tea.  This is fine – I enjoy a good caffeine buzz – but the down side?  All that iced tea makes me cold, despite the fact that I have a heavy fleece jacket on most of the time.   And the iced tea in the container is warm, so you have to use a lot of ice to get it cold, because no one wants warm iced tea.  I wonder if I could give myself hypothermia.  I mean, I drink a lot of iced tea while I’m writing, and I am definitely lowering my body temperature.
  • Here’s a wish that I have for Delphi:  That the default behavior for many of the VCL components be changed to not include the caption in the initial component.  Does anyone want the TPanel caption to be anything other than blank?  Does anyone want “Memo1” in a TMemo? “Edit1” in an edit?  Maybe there was a time for that, but how tough can it be to change that and save us all the aggravation?  VCL team – make this happen!
  • I get the sense that Delphi folks don’t make use of environmental variables like they should. Am I right?  When I find a new library that I want to use, I put it in a directory called c:\code.  For instance, I have c:\code\duckduckdelphi.  Then, I create an environmental variable called “DUCK” that equals the source directory for DuckDuckDelphi.  Then I add $(DUCK) to my Delphi path.  That way, it keeps the path short and sweet and less awkward than a hard-coded path.  In team environments, this works great too, because then people don’t all have to have exactly the same directory structures.  Do others do this?  How do you guys handle your Delphi paths?

Flotsam and Jetsam #97

  • Well, the next release of Delphi must be getting close.  The Delphi Insider has information about Skill Sprints that will show some of the new features.  Mitov Software has an interesting screen shot that looks like it has some sort of multi-view for mobile apps.  Cool.  Here’s a community post on what it is – the Multi-device Preview.  The Code Sprint are showing off new features as well.  Marco has a video about EMS Notifications.  EMS is a very under-appreciated feature if you ask me. 
  • I endeavor to write clean code. I hope you do, too.  One nice measure of that the Embarcadero has given us is “Can Castalia properly parse your code?”.  I submit the following statement:  If Castalia has trouble parsing your code, then the first place you should look to solve the problem is in your code. Code that gives Castalia – which has a pretty good parser – a hard time is maybe just a touch over complicated or not well formatted.  Just a thought. Just my personal thought.
  • Yesterday I attended the Philly.Net Code Camp.  There were at least 500 people there, including a larger percentage of women than I’ve seen before – or at least it seemed that way to me.  I spent the entire day in the same room on the “Scripting” track, learning about node.js,  “this” in Javascript, more about what TypeScript is, and what is coming in ECMAScript 6.  It was a good time and I learned a lot.  These events occur twice a year, and the Philly.net crew do an amazing job putting the event together.  Did I mention that these events  are totally free?  I’ve spoken at the event in the past, mostly on non-technical topics.  I’ll try to do that for the next one.  In any event, it was a good event.  If you are in the area (people came from as far as New York), I’d recommend it. 
  • I’m plugging away on my next book.  Two areas that are giving me – ahem – “challenges” are the Parallel Library and MVVM.  Coming up with good examples leads the difficulty.  Just getting my head around all the stuff in the Parallel Library is proving difficult, I must confess.  I don’t want to do any code with Sleep in it, so finding a good example of code that take up time is hard.  MVVM is proving difficult to find a good example using LIve Bindings, and actually doing the “true” MVVM way as defined by Rob Eisenberg. I also have to get this chapter past Stefan Glienke, too. Hehe.   In any event, I promise by the time I publish, you’ll have a good solid chapter or two on those subjects that will make you smarter for reading them. 
  • As I mentioned above, I’d like to learn Typescript, mainly because you can apparently not have to learn many of the vagaries of Javascript while being able to achieve the same result.  However, Amazon seems a little thin on books. Anyone got any good resources for Typescript?  I found some good resources for node.js, the avenue that I want to approach Javascript from, but the resources on Typescript are a bit lacking. 

Flotsam and Jetsam #96

  • Quote of the Week: “In general, you should always strive to eliminate the passing of null rather than checking for null.” – John Sonmez
  • #DelphiWeek was fun.  I followed the hashtag on Twitter,  and saw all kinds of fun stuff, from people posting pictures of their old versions of Delphi (all the way back to floppies that held the very early versions of the beta.  I still have some of those –) to Ray Konopka’s Borcon buttons.  I was also honored to be interviewed for the event, talking about the early days of TSmiley and something I’m still proud of to this day – the fact that I was at the original launch event for Delphi.  It’s hard to believe that as I type this, that was twenty years ago today, but there you have it.  Delphi really is twenty years of continuous innovation, and it continues to prove worthy of that moniker. 
  • Rob Love has a really nice article on the Parallel Programming Library and using TTask properly.  Good example of how tricky parallel programming can be.  I’m working on that chapter for my new book and it is indeed a challenging topic, but one worth the effort.  Good reason to upgrade to XE7.
  • Andy Hausladen dog-fooded a new JSON parser for Delphi.  Worth a look, for sure.  I downloaded it, looked at the unit tests, and now I know how to use it.  See?  it really works that way.

Coding in Delphi $10 Off During #DelphiWeek

To help celebrate #DelphiWeek and 20 years of continuous innovation, my book, Coding in Delphi, is $10 off for the next week.  Just use the link below to receive the discount:

https://leanpub.com/codingindelphi/c/delphiweek

Thanks!

Flotsam and Jetsam #95

  • Last week I sang the praises of Stefan Glienke.  Well, he has done it again.  He’s released TestInsight – an IDE integration for unit testing.  This is really cool – you can run your tests automatically right in the IDE.  Give it a look – very, very nice stuff.   Plus, it works with all the major unit testing frameworks.
  • Tweet and Quote of the Week:  “As long as managers think programmers are young interchangeable pizza-fed cheaply hired commodities, buggy software will rule the world.”
  • Glad to see that this website is still alive and kicking: http://www.isdelphidead.com/ Hehe.
  • Work on my new book continues apace.  I’ve just started showing chapters to my “beta testers”.  I’m grateful for all the feedback I get.  If you are interested in reading rough drafts of my chapters, you can join the Coding in Delphi group.  It’s a private group, so I’ll have to approve your entry, but that’s usually not a problem.  I welcome and am grateful for any help in making the book better.
  • Next week is Delphi Week.  You can register to participate.   Hard to believe it’s been twenty years.  Seriously?  Great that the product is still rolling along as strong as ever.  I’ll have few thoughts, tweets, and other things to offer as we celebrate.  Keep an eye on this space and the #delphiweek hashtag, as well as the presentations from Embarcadero.  Should be fun.
  • Jim McKeeth does a nice interview with Darren Kosinski, who is a member of the FireMonkey R&D team.  Darren is a friend of mine from my days at Embarcadero and a good guy as well as a brilliant developer.  Give it a listen. 

Targets and Estimations

We’ve all been there.  “How long will this take to get done?”.  The answer they are looking for is “by this afternoon,” but most often the real answer is longer than that, often much longer.  In fact, the real answer is “I don’t know”.  But you have to give an answer.  This is where you hear tales of people rolling dice or making something up or saying “six weeks” no matter what.  In the end, you can’t know for sure because you’ve never done that project before, and so you make your best guess and it works out somehow most of the time.

But a lot of developers and managers fail to realize that there are really two different kinds of answers you can give.  If it is Monday, you can say “I’ll have that done by Friday”.   Then you work like crazy, and just before you go home on Friday, you deliver what you promised. 

The other type of answer you can give is “That will take 40 hours.”  And so if it is Monday, and you say that, then the manager will hearI’ll have that by Friday”.  So then you go and you work like crazy, and just before you go home on Friday you deliver what you promised.   But when you’re done clocking all your time, you put in 50 hours to get the project done.  That’s a 25% overrun, and your manager wants to know what happened and why you took so long.

There are a lot of things going on here – but the point I want to make is that there is a difference between an estimate and a target.  An estimate – “How many hours is this going to take?” – is very difficult to get right.  There are always unknown unknowns that enter in to make the total number of hours that something will take.  We are notoriously bad at making estimates.  There are a lot of reasons for that, but the fact remains that we are not really capable of making accurate estimates.  But “I’ll have that by Friday” is easier to say because you have flexibility in the amount of work it takes to hit that target.

But note well that an estimate is not a target.  A target is when you say “I’ll have that by Friday”.  Saying that on Monday morning is not the same thing as saying “It will take 40 hours to do”.  In fact, it’s a very, very different thing.  Saying “I’ll have that by Friday” actually means “I’ll do whatever it takes – put it however many hours it takes – to get this done by Friday.”  It might take 20 hours.  It might take 60 hours.  But you didn’t say anything about how many hours it would take, you gave the target point when it would be delivered.

So if you are a manager, recognize the difference between a target and an estimate.  If you are asking for an estimate, understand that software estimation is still something even the most seasoned developers do very poorly.  If you are asking for a target, realize you may be asking someone to put it a lot of hours to hit that target.  Or not – maybe they say “Friday” and it only takes half an hour.  Who can say for sure?  If Friday is good enough, then you shouldn’t care how many hours it ends up taking either way.

And the one thing you shouldn’t do is ask for an estimate, take it as a target, and then get upset when the developer hits the target but runs over on the hours. 

Targets are not estimates, and estimates are not targets.  Understand the difference, and you’ll have happier developers and happier managers.

Flotsam and Jetsam #94

Flotsam and Jetsam #93

  • In my post about my new book, I mentioned that I thought my outline was a little thin, and indeed it was.  I left out a large topic about which I planned on writing – “Writing SOLID Code”.  Add that in, and things seem a bit more fleshed out.  The silly thing was that I was working on that chapter when I put together the outline and wrote the blog post.  Anyway, the outline has been updated and all is well.  Thanks again for the support.  If you want to keep up with the book’s progress, help out answering my silly questions, and generally be supportive, you can sign up at the LeanPub site, or you can join the Google Group
  • Here’s some food for thought for my post about not using nilThe Null Object Pattern.  Yet another reason never to return nil.  Instead of doing that, you can return a null object that won’t cause an access violation and yet won’t do anything.  You can check if the object is a null object if you need to.  Win all around.
  • So the rumors were true – Embarcadero has bought the main products of TwoDesk Software.  Jacob Thurman has stated that while he’s not now an Embarcadero employee, he will be working on the Delphi IDE.  I guess it’s none of our business exactly what the relationship will be, but if Jacob is working to improve what the IDE can do with code and to improve developer productivity in the Code Editor, I’m very happy.  I know that Jacob has had a lot of things that he wanted to do, but found it difficult as an “outsider”.  Now that he’s an “insider”, I hope he can do them.  I think we’ll see some fun stuff coming out of this deal. Congratulations to Jacob, who I hope was well remunerated, and to Embarcadero for the wisdom to see and acquire Jacob’s skills.
  • True words tweeted by me: “There are two things that developers love to do: Make pronouncements, and point out the exceptions to other developers’ pronouncements.”  I like to make pronouncements as you’ve probably noted.  I’m always trying to learn new things and new ways of doing things, and I don’t want to be held back by the “well, we’ve always done it that way” way of thinking.  I believe that the way software is developed is evolving and improving, and that we’ve found new ways of doing things better.  I try to learn those things and blog about them.  That’s what I’m trying to do here.  If you disagree with what I say, I welcome your comments. But I ask you to consider that maybe I’m actually on to something.  I’d encourage you to take the same path I have – the path of learning these new things that developers are finding and doing.  For instance, I don’t ever intend on writing another Delphi application without utilizing MVVM.  But ten years ago, such a thought would have occurred to almost no Delphi developer.  I encourage you to study the SOLID principles, to read Clean Code, to find better ways to decouple your code, and to generally seek out new thinking about software development.  I’m a firm believer that there is always a better way, and I encourage you to think so as well.

On the Use and Acceptance of nil

Yesterday I made the following tweet:

and it started and interesting little discussion on Twitter.  (I was actually honored that the great Mark Seemann himself entered into the fray…) Naturally, the conversation tried to point out why I was wrong, and all the ways that it was fine to use nil.  That’s okay – if there it is one thing developers like better than making pronouncements, it’s finding exceptions and arguing against other developer’s pronouncements.

Well, I remain unconvinced and stand by my statement.  No surprise there, I know.

There are two parts to what I said and I’ll argue them one at a time.

First – “never pass nil to a method”.  Now people freak out about “never”, but it’s Twitter and you don’t have a lot of room for caveats.  First, sometimes I guess you have to pass nil to some methods  — ShellExecute  comes to mind —  but I’d argue that those methods are poorly designed (as I’ll talk more about in a minute), and that you should pass nil only very, very reluctantly.  Again, I’m talking about your code, not other’s code.    You should never send nil to a place where a valid object will be accepted.  Never do that to someone’s code.  Returning nil is always a bad design decision.

The Robustness Principle states, in part, that you should be very precise in what you pass, and passing nil is not precise.  It misses the mark by as much as you can miss the mark.  The target is a valid, working instance of whatever the method is asking for, and passing nil is like turning 180 degrees around and firing your arrow away from the bulls-eye.  Nil should not be used as a “signal”, leaving the class you passed it to in a state where they can’t make use of what you’ve given them.  You should avoid like the plague allowing a  class to be in a state where it can’t do what it is designed to do, and if it asks for a object in a method or constructor, you are obligated to pass a working, constructed object that it can use without error.  To do anything else is to invite an exception or worse, an access violation.

The second part is this:  “Don’t let your methods – especially your constructors — accept nil as a parameter value”.  Your classes should never let themselves get into an unusable state, and blindly accepting nil as a parameter will do that.  Instead, your classes should carefully guard against being passed nil and quickly – no, immediately – fail if passed a nil reference.  There is even a pattern – the Guard Pattern – that is employed to ensure that a program won’t continue unless things are acceptable.  Getting nil is not acceptable:

Every single time you accept an object as a method parameter, you need to use the Guard Pattern to prevent your object from being placed in a bad state where it can’t do what it is supposed to do. Fail fast and tell the user exactly what they did wrong and what they need to do to fix it. In fact, if a nil reference sneaks in, you’ll eventually get an access violation when you try to use this nil reference, right? Sure, it’s work, but it is time well spent.  Knowing that your references are always valid makes for easier code, and actually can reduce the amount of nil checking that you have to do.  Who wants to check for nil every time you use an object?

Don’t pass nil references.  Don’t accept nil references.  This seems obvious to me and I confess I don’t understand objections to this aphorism that only results in cleaner code.   Why would you ever want to accept a nil object?  Why would you want your code in a state that is begging for an access violation to occur?  Insist that your objects are valid, and never impose invalid objects – nil – on others.  Seems blatantly obvious to me.

So I am going to guess that this will not make some of you happy.  So here is my challenge:  Show me code that you have written where nil is acceptable.  Don’t show me code that calls the Win32 API or the VCL, show me code you have yourself written where nil is acceptable and useful as a valid method parameter.  I’d love to see it – and then point out the problems that it will cause.  🙂

Delphi and #Code2014

Hey, Delphi ended up really well in the #code2014 survey.  Sure, it’s self-selected and thus statistically dubious, but it definitely is nice to see Delphi in ninth position with a prominent circle.  (If you add Delphi and Pascal together, we’d be in sixth place.  Yes, I can see the comments already…)

If I were part of EMBT’s marketing team, I’d be shouting this one from the mountain tops.  I know that technically it’s not statistically significant, but the whole chart “feels” right.  The languages at the very top seem like the right ones.  And Delphi at the ninth position seems right too.  Why?  Because I think there are a lot more Delphi developers out there than people know.  Is it more popular than C/C++?  Maybe not, but then again, maybe it is.  No way to know. 

The part that bums me out is the community members that are so quick to point out that the survey “doesn’t mean anything”.  I most strongly disagree.  I think it means a lot.  I think it shows that the Delphi community is real, it’s bigger than folks think, and it’s willing to speak up and be heard.  All I know is the Delphi community sure came out of the woodwork and made Delphi rise into a prominent position in a poll that many developers will see. That can’t be bad.  It is good.

If you are a Delphi developer, you should be happy about this, and you should be doing what you can to show people the results.  I took a screen capture of the results in case the URL goes away (www.code2013.com is for sale for a mere $3095).  If you are a Delphi developer and are poo-pooing the results, I say “Lighten up, Francis”. 

This is good.  Enjoy it.  Use it.  Delphi is still here and going strong, almost twenty years after it launched.  We’ve had our ups and downs, but the bottom line is that you have nothing to be ashamed of when you say “I am a Delphi developer”. 

Flotsam and Jetsam #92

  • We have a vibrant .Net community here in the Eastern Pennsylvania/Philadelphia area.  Philly.Net runs events once or twice a month at the Microsoft campus, and semi-annual Code Camps that are usually attended by well over 700 people.  I attend whenever I can.  But I’ve noticed something interesting over the last year or two:  almost all the coding topics are now Javascript-based.  I see them doing very few C# – based presentations.  This event is pretty typical.  (I am going to be attending this one, by the way…..) Anyway, just an observation that I think is interesting.
  • If you aren’t satisfied with the RAD Studio IDE’s bookmarking system – and you shouldn’t be as it leaves a lot to be desired – you might be interested in the free IDE plugin called Parnassus Bookmarks from David Millington.  It works great, is totally free, and is a solid replacement for the existing system.   Download and install is recommended.
  • Well, Delphi has done really well in the #Code2014 survey.  Thanks to everyone who tweeted.  It’s nice to see Delphi up near the top in a very respectable position.  As of this writing, Delphi is only 19 tweets behind C++ – nothing to blow your nose at.    Javascript continues to dominate in a pretty big way, nearly doubling the second place Python.  (See my comment above).
  • New Project of the Week:  Another gem from the inestimable Malcolm Groves – TStateMachine.  From the README:  “TStateMachine is a framework for declaring and running state machines in Delphi. It supports generic types for states and triggers, anonymous methods for Guards and Effects (State.OnEntry? and State.OnExit?), and a Fluid interface for configuring the State Machine.”  Very interesting and worth a look.  Maybe even worth a new chapter in my book.
  • Cary and Ray have set the agenda for their Delphi Developer Days conference.  Again, this is always a high-quality event, and I try to make it every year.  Word of advice: Don’t ever miss Ray Konopka when he is speaking.  He’s very, very good.

More Coding in Delphi

First of all, I want to once again thank all of you who have purchased, read, or otherwise supported my book Coding in Delphi.  I’ve said it before and I’ll say it again  — the response has been overwhelming and humbling.  The book has been more successful than I could have ever hoped for.

It’s so successful, in fact, that I’ve decided to write another one – More Coding in Delphi.  I am once again using the LeanPub publishing platform.  LeanPub is really an interesting tool – it makes it really, really easy to produce a book. Highly recommended.  You write the book in Markdown, and they take that and turn it into PDF, MOBI, and ePUB files for you.  Easy as pie.  I’ve been using MarkdownPad for writing the book.  It does a nice job of helping you write Markdown text. 

By default, LeanPub uses DropBox.  First, I granted LeanPub access to a shared folder on Dropbox.  Then, when I go to publish a preview or the real thing, LeanPub looks in that folder for a file called “Book.txt” which describes the format of the book by pointing to *.md files.  It then accesses those files in the shared folder and creates the book. 

This time around, though, they’ve added a new feature where you store the book in GitHub and they pull from the repository to get the files for the book.  Cool.  When the book is ready for proofing by any of you interested in doing so, you’ll get access to the manuscript by pulling it from the private repository on Github.  So if you want to help out, you’ll need to brush up on your Git. SmileIt also means that I get the benefits of a DVCS, and you guys can make pull requests if you have improvements for me. 

Right now, the outline for More Coding in Delphi is currently:

  • Four Thoughts on Coding Before We Start
    • Encapsulation, CQS, Postrel’s Law, Compostion over Inheritance
  • Duck Typing
  • JSON
  • Aspect-oriented Programming
  • Design Patterns
    • Observer Pattern
    • Adapter Pattern
    • Decorator Pattern
    • Another Pattern to be named later
    • Another Pattern to be named later
  • Parallel Programming
  • Model-View-ViewModel

That feels a little thin to me right now, so I am seeking more topics.  If you want to suggest anything, I’m all ears — either comment here on this post, or join the Google Community for the book.  Remember the philosophy of the book, though – it’s all about the code.  I’ll write about code frameworks, RTL type stuff, etc., but I don’t want too many screen shots of forms in the book.  There will be some in the MVVM chapter, but the idea is that the book covers code and how to write good code.   That’s what I want to focus on.  I’m also open to turning “Four Things” into five or six or seven things, so if you have small topics – a page or two, not enough for a full chapter — I’d love to hear those as well.

Okay, so now the real work begins.  It’s a lot of work to write a book. My hope is to have the book published by the end of this year.  I know that I can’t do it without your help – you guys made the first book possible.  Again, I’m grateful to all you readers and supporters. 

Flotsam and Jetsam #91

  • It’s #Code2014 time again! Time to tweet out what languages you used for the year.  Just list your languages and include the hashtag #code2014, and they’ll do the rest.  Of course, you can include Delphi all you want.  I won’t mind.
  • Looks like Ray Konopka will be replacing Dr. Bob this coming year for Delphi Developer Days.  If you haven’t heard Ray speak, he’s excellent.  Really excellent. I’ve been to DDD three or four times, and it’s always great.  Adding Ray this year will maintain the high standards that it has always had.  Looks like Dr. Bob is just taking some time off from traveling, and Ray is stepping in.  Sounds great.  And as Cary notes in his blog post, you can get a reduced rate if you register early!  Smile
  • In a recent post, I talked about IncludeTrailingPathDelimiter and why you should always use it with your path strings.  I should have mentioned that there is also a ExcludeTrailingPathDelimiter that is part of the RTL, too, which does what it says – takes off the trailing path delimiter if it is there.  I’m not sure why you’d want to do that, but hey, there it is. 
  • Happy New Year, everyone.  I hope that 2015 has everything in it that you want and hope for.  In case you were wondering, my New Years Resolutions are to finish my new book and 1920×1080.

Never Assume Your Paths Have Ending Delimiters

I think I’ve mentioned that I have a “challenging” codebase that I deal with in my day job.  It’s a classic Delphi legacy app, worked on by numerous different people over the years with multiple different styles and techniques. Part of the product includes the use of an Address Engine – a third-party utility that “scrubs” addresses and ensures that they exist and that they are in a Post Office acceptable form.

Recently, we’ve had to change Address Engine providers.  It should have been easy – I had created an interface to isolate the engine before the switch.  So I got the new engine all plugged in, ready to go, and it all should have worked.  But try as I might, I couldn’t get anything but garbage data out of the engine.  Argh.  It simply wouldn’t return any data.  Now mind you, the DLL in question was written in C, and I had a translation of the *.h file that I was pretty confident in.  It all should have worked.

But the problem was much simpler than that – the *.ini file that had an entry for the path to the postal data was missing an ending backslash.  That was it.  I put the trailing backslash on the entry (why didn’t the installer do that?) and it all worked.

Which brings me to the point of this blog post:  Always assume that your paths don’t have that trailing delimiter, and that it is your responsibility to put it there.

In fact, the RTL provides a routine that allows you to do that very thing:

IncludeTrailingPathDelimeter will place either a backslash or a forward slash on the end of a path, depending on the operating system’s definition of a path delimiter if there isn’t one there.  If there is, it will do nothing.   You should use it to ensure that every path string you use has a delimiter on the end of it.  Your code should thus assume that all paths have that trailing backslash on it.  If you have code that looks like this:

this should be changed to

The former code can be buggy – what if SomePath already has a trailing delimiter?  You’ll end up with an invalid path.  The latter code has no such problem.  It is safe both ways – with and without the trailing delimiter.  This is especially necessary when your paths come as a result of user input, such as that *.ini file above.

The moral of the story:  Never assume that your path variables have a trailing delimiter, and always wrap them up with IncludeTrailingPathDelimiter to ensure that they do.

Flotsam and Jetsam #90

  • I mentioned this video before, but it is so good I’m going to mention it again:  Parallel Programming Library: Create Responsive Object Pascal Apps.   Danny’s blog is in Dutch, but he has an English entry that includes the source code to his session.
  • Something I’m surprised by:  The number of questions on the Delphi StackOverflow tag that deal with integrating with Excel.  Also, tons of Indy questions.
  • This is interesting: Jon Aasenden is creating DelphiArmy – a real, no kidding jobsite for Delphi developers.  I’ll be interested to see how that goes.  It appears to be alive and running, so make an entry if you need to.
  • I’ve mentioned free this tool before, but its usefulness is so awesome that I wanted to point it out again.  It’s called “Everything”, and it allows you to search for any file by name on your entire system.  It’s lightening fast, and I use it probably twenty times a day to find things I’m looking for.  It’s one of the first things I install on a new system.  Truly outstanding and amazingly useful.  Highly recommended. 
  • While I’m at this “mentioning before” thing, I’ll give a strong endorsement to the Delphi-built Clipmate. Again, I use this thing about 25 times a day.  It’s a clipboard cache that remembers what you’ve put on the clipboard.  It’s not free – but it’s well worth the price.  Saved my butt a thousand times, too, when I overwrite something on the clipboard that I didn’t want to. 

Flotsam and Jetsam #89

  • A little while ago, I wrote an article on VSoft’s command line arguments library.  Since then, I’ve discovered a couple of other solutions that might be of interest.  First is from John Kaster, TCommandParser, which has an EDN article (it’s mentioned in there, don’t worry) and a CodeCentral entryPrimož Gabrijelčič has created one that uses attributes.  And this StackOverflow question has a number of other solutions as well. 
  • Speaking of command line parameters, how about someone create a default Console Application that has command line processing built right into it.  You could go “File|New|Console Application” and have a new console application with command-line options.  Maybe there could even be a wizard to define the command line parameters that your console application would have.  Just and idea – I don’t have the time to do it right now.  🙂
  • A while back, Marco posted about the “TurboPack”, a set of open source libraries over which Embarcadero appears to be taking ownership.  I was glad to see SynEdit on that list, as I use that in an app I built, and have always found its varying versions confusing.  I hope EMBT is able to tighten that up.  Anyway, Marco now has a short video on his blog that demonstrates some of these components working.  Nothing big, just a quick look.  I think this is a good initiative on EMBT’s part, and so it would be good for those of you that agree to show support as well.  You can find links to the code on Roman Kassebaum’s blog. I guess we owe Roman a Thank You as I bet he did most of the work.
  • Clearly the focus of the last few releases of RAD Studio have been on mobile development. Some folks have complained that the VCL developer has been left behind.  It seems that EMBT has been aware of this feeling, and has been emphasizing that it isn’t true – that there have been quite a few developments for VCL developers, including REST client components (which are remarkably easy to use), app tethering, taskbar components, the Parallel Library, and more.  They also have a webinar coming up entitled “Modernize Your VCL Applications Today”.  Yes, the focus hasn’t been 100% on the VCL as in days gone by, but the VCL hasn’t been ignored by any means.  Quite the contrary.
  • Book I’m ReadingObject Thinking by David West.  The idea here is that even though we are all using OOP languages now, we are really doing procedural programming inside the world of OOP.  West discusses how we need to start thinking totally differently about our code – to think about objects.  Interesting so far – not your typical coding book.

Flotsam and Jetsam #88

  • The inestimable Malcolm Groves has a nice series going on the new Delphi Parallel Library.  Recommended reading.
  • I put a tag cloud over there on the left.  Now I just have to remember to put tags on all my posts.
  • I welcome feedback on the new blog.  As I said, my goal is to keep the blog as simple and clean as possible and the content as interesting and useful as possible.
  • I guess I should have realized that such a thing would exist, but I just found the Delphi Reddit.  Thanks to folks that post my blog entries there.
  • Another entry in the “How did I miss this?” department:  A guy named Branko Stojakovic has built a blog covering most of the Gang of Four patterns.  Maybe I did mentioned this before – I have a dim memory of it – but anyway, worth looking at and learning from either way.

Command/Query Separation

Introduction

An important step to writing Clean Code is the notion of separating “commands” and “queries” by using the Command Query Separation Principle.  The notion was first discussed by Bertrand Meyer in his book Object Oriented Software Construction.  This means that the idea is not new.  In its basic form, it means we should separate the things that read data from the system and things that write data to the system.

The Command/Query Separation Principle means that there should be a clear separation between the updating of information and status in your program and the way that you read information from the program.  Commands and queries should be separately declared (though you’ll find that commands can call queries but not vice-versa.)  It can be a complex as ensuring that reading and writing take place in completely separate object, or as simple as ensuring that commands and queries are simply done in different methods of your objects.

Of course, the first question you’ll have is “What do you mean by ‘command’ and ‘query’?”  Well, I’ll tell you.

Queries

A query is an operation that returns a result without effecting the state of the class or application.  In Object Pascal, this is typically a function.  Queries should not mutate the state of a class.  They should be idempotent.   That means “denoting an element of a set that is unchanged in value when multiplied or otherwise operated on by itself.”  (I had to look that up, by the way….)

As a general rule, queries should return a single value, and “asking a question should not change the answer”.  They should be referentially transparent; that is, they should be perfectly replaceable with their literal result without changing the meaning of the system.

What this means practically is that your functions shouldn’t change the status of the system you are working on, whether that be a class, a framework, or an application.  You should be able to run a query, i.e. a function, a hundred times in a row and get the same answer back each time.  The function, because it doesn’t change the status of the system, can be safely called at any time without repercussions.

Now this should be a general rule — there are certainly cases where your query will change the state of the system (a dataset’s Next call comes to mind).  But generally, it’s a good idea to have your queries not change state.

Commands

A command is any operation that has an observable side-effect.  It is any code that changes something in your class or application.  Typically, in Object Pascal, a command will be a procedure — that is, code that takes actions without returning a value.  Commands can call queries (but queries should never call commands, because commands change the status of the system).

Commands should not in general return values.  Thus, the use of var parameters should be discouraged if not down-right banned.

Don’t Mix the Two

All your methods and routines should be easily identifiable as either a command or a query.  Commands and queries should be separate entities in your code — with the exception that a command can call a query if need be. The use of var or out parameters in a procedure will confuse this issue, and thus should be discouraged.   If you follow this rule, your code should be more “reasonable” — it should be easier to understand and easier to modify.

CQRS also encourages you not to violate what I consider to be a bedrock of sound development technique:  Don’t try to make one thing do two things.   For instance, here is some code that does exactly that:

This method is a clear violation of CQS [NOTE:  I orginally had this as CQRS] as it obviously is trying to be a command and altering the state of the system by processing widgets, but also tries to be a query by “returning” through a var parameter the number of processed widgets.  Instead, the system should have a simple command to process widgets and a separate query to return the number of widgets that were processed.  The procedure is trying to be two things at once, and all kinds of mischief comes from making one thing do two things.

Following the CQRS principle in the design of your code will help to ensure the proper separation of concerns, resulting in cleaner, easier to read and easier to maintain code.

Obey Postel’s Law in Your Code

Jon Postel was a guy that wrote an early specification for the Transmission Control Protocol (TCP), one of the core protocols of the Internet protocol suite.  You use it every day to surf the web, send emails, etc.  One of the guiding principles that he used when writing it was this:

Be conservative in what you do, be liberal in what you accept from others.

This idea is also call the Robustness Principle, and is sometimes rephrased as “Be conservative in what you send, be liberal in what you accept.”  When applied to TCP, it means that the sender of data should be strict in what is sent, ensuring that it is accurate and precise.  It also means that the receiver of data should be forgiving and understanding of data to as large a degree as possible.  If you send data, be as clear as possible in what you send.  If you can accept the data sent, then you should.

Any application programming interface (API) should follow this principle.  Thus, the same principle should apply to your code.  The public interface of your class should be viewed as an API, and it should be conservative in what it sends, and forgiving in what it receives.  When calling another API, your code should send out data in a completely conformant way, following the rules laid down by the receiving API.  But it should be willing to receive input in a non-conformant way as long as the input can be understood.

For instance, if passed a string, you might be happy to accept strings with blank spaces on the beginning and end, and use the Trim function to clean things up for the sender.  Your classes might provide overloads for input methods, accepting both and integer and a string as input, providing a way for your class to be as forgiving as possible.

But when you call another API, your code should be strict and always send data in the correct, expected form.  You should trim your strings before they get sent along to the API you are calling.  If the system expects integers, you are going to send integers.  You should meet the specification completely.

Another example is the use of nil.  First, your code should never pass nil to a method that you are calling.  Always provide a valid instance if the API calls for one.  Second, your code should accept nil, but “fail fast” if passed nil and raise an exception.  You should never let your internals get into the state of nil, and while you should accept nil, you should immediately raise an exception at any attempt to set one of your internal references to nil.

Postel’s Law – a small but important way to write better code.

Flotsam and Jetsam #87

    • Yet again, I’d like to thank all of you who have bought my book or received it as an upgrade incentive.  Once again I’ll say that the book has been more successful than I ever imagined.  So successful, in fact, that I’m going to work on another one along the same lines.   By that I mean that it will be a book focused on code and not the building of UI’s or other such applications.  Keep your eye on this space for more information.  And thanks again – I’ve really very grateful for all the support.
    • Blog Update: I’ve added Disqus as the default commenting system here.  Seems really popular and cool, and I love to be popular and cool.  However, it may have screwed up some of the early comments.   I’ve also added a barrage of share options on each post, so share away.
    • I hope you all can see this – it’s a Facebook link and I have no idea what their rules are – but this post led to an interesting conversation.  The link about MS tools that spawned the conversation is interesting as well.
    • Malcolm Groves does a great job explaining one of the more difficult things to understand in System.Threading.pas: IFuture<T>
    • I have thoroughly enjoyed having Castalia as a free part of my IDE as a promotion with Delphi XE7.  Good news – an update is coming.  And this new feature looks, well, amazing.