Amazon.com Widgets March 2012

Using Anonymous Methods for Inversion of Control

By Nick at March 31, 2012 08:26
Filed Under: Delphi, Software Development, Unit Testing

Introduction

I’ve written an entire series of articles about Dependency Injection and the Inversion of Control.  I’ve exhorted you to decouple your code and to ask for your dependencies instead of creating them yourself.  I hope you’ve listened.

Now I’m going to discuss another way you can invert the control of your code – by using anonymous methods.

Anonymous methods were one of two major language features added in Delphi 2009 – the other being generics.  Generics are probably easier to understand and use as they have a great use case with collections.  Anonymous methods are a little harder to understand because their use and their purpose are not as easily seen.   I hope that you’ll start seeing their advantage after reading this post.

Basic Idea

The basic idea is pretty simple – anonymous methods allow you to pass code, i.e. functionality, like any other variable.  Thus, you can ask for  functionality via an anonymous method just like you can ask for a dependency via an interface.  Because you can assign code to a variable – or even pass code directly into a method – you can easily invert the control of your class by passing in code to your class instead of embedding it in the class itself.

One of the principles of Inversion of Control is “Don’t call us, we’ll call you”.  That is, if a class needs something, the class itself should ask for (call) the functionality, rather then doing that functionality itself.  If a class needs to, say, record the processing of widgets as it happens, it should ask for a widget recording class and record things using the dependency that is passed in.  A class should not create it’s own instance of a widget recording class and then use it.

Given that example, it’s not difficult to see how one could pass recording functionality into a class as an anonymous method. 

Doing it the “Normal” Way

Let’s use the above discussion in a code example.  As noted, perhaps your class needs to record the processing of widgets.  Typically, you might do something like this in order to use good dependency injection techniques:

type
  IWidgetRecorder = interface
    procedure RecordWidgets(aNumberOfWidgets: integer);
  end;

Then, you’d pass an instance of that interface into your class:

var
  MyWidgetRecorder: IWidgetRecorder;

...

MyWidgetRecorder := TWidgetRecorder.Create;
MyWidgetProcessor = TWidgetProcessor.Create(MyWidgetRecorder);

You’d store the widget recording interface and use it in your class as needed.  And that’s an excellent thing to do – your class is decoupled completely from the recorder, and you are using constructor injection to ask for your dependency. 

Again, this is a great technique, and probably preferable most of the time.  I don’t want to leave the impression that what I discuss below is always a replacement for good, sound use of interfaces. However, it may not always be what you want to do.

IOC with Anonymous Methods

As noted above, you can use anonymous methods to invert the control of your class.  Perhaps declaring an interface and instantiating a class to implement it is too heavy.  Perhaps the dependency is really simple and straightforward.  In those cases, using a simple anonymous method to inject your dependency might be a better solution for decoupling your code.

For instance, you can declare an anonymous method type:

type
  TWidgetRecorderProc = reference to procedure(const aCount: integer);

This will allow you to declare code that takes an integer – presumably the count of widgets being recorded – and does whatever you need it to without bothering the class that uses it.

From there, you can use this type in your classes:

type
  TWidgetProcessor = class
  private
    FWidgetRecorder: TWidgetRecorderProc;
  public
    constructor Create(aWidgetRecorder: TWidgetRecorderProc);
    procedure ProcessWidgets(aNumberToProcess: integer);
    property WidgetRecorder: TWidgetRecorderProc read FWidgetRecorder write FWidgetRecorder;
  end;

This simple class declaration takes an anonymous method as a parameter to its constructor, and then exposes that function as a property. That’s a bit of a commitment – you may not always want to do widget recording.  If you wanted, you could not pass the anonymous method in the constructor and simply assign it to the property as desired. In any event, the widget recording functionality is implemented externally, and your class merely depends on the anonymous method type. 

Then, you can implement the class as follows:

{ TWidgetProcessor }

constructor TWidgetProcessor.Create(aWidgetRecorder: TWidgetRecorderProc);
begin
  inherited Create;
  FWidgetRecorder := aWidgetRecorder;
end;

procedure TWidgetProcessor.ProcessWidgets(aNumberToProcess: integer);
begin
  WriteLn('Processing ', aNumberToProcess, ' widgets.');
  WidgetRecorder(aNumberToProcess);
end;

Now, you have a class that can record widgets any way you want to – to the console, to a file, to email, a database -- whatever.  And you don’t have to know anything about the implementation of how the widgets are recorded. You just have a variable that refers to the code, which you can easily call in your code. 

Using Your New Widget Recording Tool

So, now we have a TWidgetProcessor that can record widgets with an anonymous method.  Cool – but how?  Well, you simply declare an anonymous method and pass it in.  Here’s an example which just writes out to the console:

procedure ProcessSomeWidgetsAndRecordToConsole;
var
  WidgetProcessor: TWidgetProcessor;
  RecorderProc: TWidgetRecorderProc;
begin
  RecorderProc := procedure(const aCount: integer)
                  begin
                    Writeln('The Widget Recorder recorded ', aCount, ' widgets');
                  end;


  WidgetProcessor := TWidgetProcessor.Create(RecorderProc);
  try
    WidgetProcessor.ProcessWidgets(Random(100));
  finally
    WidgetProcessor.Free;
  end;
end;

All this code does is declare an anonymous method that matches the declaration of TWidgetRecorderProc and writes the information out to the console.  That’s pretty simple.  But what if you wanted to write it out to a file?  Easily done without changing the TWidgetProcessor class at all.

procedure ProcessSomeWidgetsAndRecordToFile;
var
  WidgetProcessor: TWidgetProcessor;
  RecorderProc: TWidgetRecorderProc;
const
  cFilename = 'WidgetRecord.txt';
begin
  RecorderProc := procedure(const aCount: integer)
                  var
                    SL: TStringList;
                    S: string;
                  begin
                    SL := TStringList.Create;
                    try
                      if TFile.Exists(cFilename) then
                      begin
                        SL.LoadFromFile(cFilename);
                      end;
                      S := Format('%s: %d widgets processed', [DateTimeToStr(Now), aCount]);
                      SL.Add(S);
                      SL.SaveToFile(cFilename);
                    finally
                      SL.Free;
                    end;
                  end;

  WidgetProcessor := TWidgetProcessor.Create(RecorderProc);
  try
    WidgetProcessor.ProcessWidgets(Random(100));
  finally
    WidgetProcessor.Free;
  end;
end;

Of course, you could write a similar anonymous method to record the information to a database, send an email, or any combination thereof. 

And just as importantly, if you want to test The TWidgetProcessor class, you might want to do so by passing in a TWidgetRecorderProc that does absolutely nothing:

  RecorderProc := procedure(const aCount: integer)
                  begin
                     // Do nothing, as this is a stub for testing purposes
                  end;

And of course if your classes are easy to test, then they are very likely well designed.  The ability to stub out functionality as above is a hallmark of well designed classes.

Conclusion

So now you have another tool in your Dependency Injection/Inversion of Control tool box.  The power here is in the ability to decouple functionality from the class that needs that functionality. Anonymous methods provide a nice way to wrap up functionality in a single variable.   Instead of injecting an implementation of an interface, with anonymous methods you can inject a specific chunk of code that will provide the functionality.  Either way, you end up with testable code that will be more maintainable in the future.

(I have included the full source for this demo, as well as other demos, available on my Demo Projects repository on BitBucket.org)

Flotsam and Jetsam #58

By Nick at March 24, 2012 11:59
Filed Under: Delphi, Flotsam and Jetsam
  • The annual RAD Studio survey is out. (UPDATE:  Apparently the link I gave was unique to me, so I've removed it.) I strongly recommend you take it if you are a Delphi/C++Builder/Prism kind of guy.  I can assure you from first hand experience that the results of this survey are very valuable and are used by Embarcadero to make decisions.  So please fill it out and let Embarcadero know what you think.
  • Awesome Quote by Nick of the Week: “The real cool part of it is that proper unit testing is a "virtuous circle". The more you write unit tests, the more you see how to write testable code. The more you write testable code, the more you tend to remove dependencies. The more you remove dependencies, the more decoupled your code is. The more decoupled your code is, the easier it is to test, and thus you write more unit tests, and start it all over again.”   I wrote that in a conversation about unit testing in the Delphi newsgroups.
  • Awesome Follow-up Quote by Dalija Prasnikar of the Week: After someone claims that unit testing can become “wheel-spinning”:  "Exactly opposite. It is quite hard to start the process rolling at the beginning. But once you get going it gets easier and easier, and you write new code faster and with less bugs and when you do write bugs, you find them in matter of seconds instead hours. And you end up with code that is easy to maintain and change. What more could you want?"
  • Sure enough, the denizens of Wikipedia have determined that this blog is “not notable”.   “Notability” is the magic word for Wikipedians, though often I think the definition that they use for it “Stuff I’m not interested in” or “a word I can use to control my little fifedom of the web’.  I will note, though, that my entry has appeared to prompt a complete reworking of the disambiguation page for “Flotsam and Jetsam”, so I’ve got that going for me, which is nice.  I can understand the need for Wikipedia to maintain a level of neutrality and objectivity, but I do think that it can get out of hand, with small-minded people enjoying their power a bit too much.  In any event, I do love Wikipedia, and use it probably more than any other site on the web.  One could even make the argument that it is mankind’s greatest achievement.  Perhaps I will in a future blog post.  Winking smile

Authoring Generics: A Simple First Step

By Nick at March 19, 2012 15:39
Filed Under: Delphi, Software Development

Consumer or Producer?

By now I suspect that most of you have heard of generics.  Perhaps you have started using them via the Generics.Collections unit, where you can find TList<T>TStack<T>, etc.  The Delphi Spring Framework contains an even more sophisticated set of collections and interfaces to those collections, including the very powerful IEnumerable<T>

These are all very useful classes, and our code is made much simpler, easier to maintain, and more type-safe because of them.  But using them merely makes us consumers of generics.  If we want to truly take advantage of generics, we need to become producers of generic classes.  It’s a big step to see the benefit of generic collections, but the truly big step is to start seeing opportunities for the use of generics in your own code.

A Contrived, Simple Example

This past weekend, some of my team members and I attended the C-Sharpen event here in Philly.  It was a valuable day, made particularly so by the presentations given by Steve Bohlen.  He gave an excellent presentation on the topic I discussed above – how we need to start thinking as producers of generics and not merely consumers.  In that presentation, he gave a simple example of how generics are powerful and can make your code simpler, more effective, and more powerful.  So, I’m going to show that example here.  It’s a bit contrived, but very illustrative of how to think about generics.

First, consider the following code:

type

  TOrderItem = class
    ID: integer;
  end;

  TOrder = class
    ID: integer;
  end;

  TCustomer = class
    ID: TGUID;
  end;

Now this code is very simple – a set of classes that might represent a simple order entry system.  But right away, something should occur to you.  All three have something in common – they are entities in your system. Down the road, you may want to act upon all the entities in your system, so you might create a superclass like so:

type

  TEntity = class  
  end;

  TOrderItem = class(TEntity)
    ID: integer;
  end;

  TOrder = class(TEntity)
    ID: integer;
  end;

  TCustomer = class(TEntity)
    ID: TGUID;
  end;

But you might be frustrated because you want your TEntity class to have an ID field that is in use by all descendants, but that pesky TCustomer class can’t oblige – it needs a GUID for its ID tag instead of an integer like the other classes.

Instead of fretting about the different types of ID tags, how about just create one that doesn’t care what type it is?  Well, this is where the power of generics comes in.   How about you give the TEntity class a parameterized type – a generic – as  it’s ID, and then just tell all the classes what type their ID tag will be?

type

  TEntity<T> = class
    ID: T; 
  end;

  TOrderItem = class(TEntity<integer>)
  end;

  TOrder = class(TEntity<integer>)
  end; 

  TCustomer = class(TEntity<TGUID>)
  end;

Now, given the above, your entities can all have ID’s, but you don’t have to have the same type for all of them.  If a TEntity descendant needs an ID of a different type, you can just descend from TEntity and pass the correct ID type in the class declaration.  

Again, the example is quite contrived, but I think it does a nice job of showing how you can starting “thinking generically” and not just accept a rigid type structure. 

In addition, it illustrates why the more formal name for generics is “parameterized types”.  The type in the brackets is passed in to the type declaration, and then used within the class, just as method parameters are passed in to functions and procedures. 

A simple, contrived example, sure.  But hopefully it illustrates how generics can be used to turn you from a consumer of generic classes to making them a common tool in your code.

 

Update:

As a number of commenters have pointed out, my original example was sub-optimal.  Rather than post a "correction" post, I've taken the liberty of updating and improving the original article.

New Blog Theme

By Nick at March 17, 2012 15:41
Filed Under: General

As you  have no doubt noticed, I updated the theme to my blog.  I was never really happy with the one I've had for about a year now, so I tweeked and existing BlogEngine.Net theme to my liking. It appears to be working and looking fine, but l can't test it on all the browsers you people have, so please let me know if you encounter any problems or oddities.  

One problem I am having is getting the lists, especially nested unordered lists, to work right.  Not sure what is going on yet, but I'm learning.  

Flotsam and Jetsam #57

By Nick at March 16, 2012 09:23
Filed Under: Flotsam and Jetsam, Delphi

How Not to Code: Passing function results directly as parameters

By Nick at March 11, 2012 12:27
Filed Under: Delphi, How Not To Code

I think I’ll start a new series, and a new blog category, called “How Not To Code”.  In it, I’ll try to highlight those little things that we’ve tended to do over the years that, well, are tempting for expediency, but probably not something we should be doing.  There are a lot of “Here’s the right way to do things”, so this series will concentrate on the “what not to do”.  That will inevitably lead, of course, to a discussion of “What to do”, but that’s ultimately the point, I suppose.

Today’s topic is “Don’t directly passing function results as parameters to other functions and procedures”. 

For instance, consider the following code:

type
  TData = record
    a, b: integer;
  end;

  TMoreData = record
    c, d: string
  end;

function GetSomeData(aInteger: integer; aString: string): TData;
function GetMoreData(aBoolean: Boolean; aInteger: integer): TMoreData;

procedure ProcessData(aData: TData; aMoreData: TMoreData);

Then, imagine that you wanted to call ProcessData with the result of  calls to GetSomeData  and GetMoreData.   It would be mighty tempting to simply call:

ProcessData(GetSomeData(aIntVariable, 'ocelot'), GetMoreData(True, AnotherIntVariable));

After all, think of all the typing you’ll save!

You should avoid that temptation, because this way of doing things presents a few problems:

  • It’s really hard to read.
    • A line of code that does more than one thing requires more brain power to read that does code where each line does one thing.  In this case, you have to convince your brain to parse all those parentheses.  Before you can figure out what the code is really doing, you have to parse two function calls inside of a procedure call.  Using your brain to parse unnecessarily complex semantics is a waste of effort.
    • You can’t be sure by merely reading the code what the types of the parameters are that are being passed to ProcessData.  This means that you have to look up the parameter types to gain full understanding.  If the variables were declared locally, then it would be easy to see their types.
  • It’s really hard to debug
    • There are no intermediate results to check in the debugger.
    • Stepping into the code requires that you step into the calls to GetSomeData and GetMoreData, when that might be something that you don’t want to have to do.

Instead of trying to compress everything into a single line of code, you probably would do something like this, instead:

var
  TempData: TData;
  TempMoreData: TMoreData;
begin
  TempData := GetSomeData(aIntVariable, 'ocelot');
  TempMoreData := GetMoreData(True, AnotherIntVariable);
  ProcessData(TempData, TempMoreData);
end;

The above code solves the aforementioned problems – it is easier to parse in your head and you can easily see the data values in the debugger before they are passed to ProcessData

Some good heuristics that fall out of this:

  • If you have to stare at the code for a moment just to parse it in your head before you even figure out what is going on, then you have a problem.
  • If you have a hard time figuring out where to put a breakpoint to get at the debugging information that you really want, then you have a problem.
  • If you feel the need to create intermediate variables to improve your ability to debug code, then you probably should have put the intermediate variables there in the first place. 
  • All sorts of bad things happen when you try to be clever and save a few keystrokes by taking a code shortcut.  Remember, the future maintainer is the person you should be writing code for, not the compiler.
  • A line of code should do one thing and one thing only – if the explanation of what a single line of code does needs the word “and” to describe it, then it probably ought to be two lines of code.

Lesson for the Day:  Always pass variables, never direct function calls, as parameters to another procedure or function. 

On Why I Think Twitter is Awesome

By Nick at March 04, 2012 11:57
Filed Under: TechBiz, General, Tech Stuff, Software Development, Delphi

I have this friend who totally doesn’t get Twitter.  He doesn’t get it so much that it actually kind of makes him angry that anyone does get – and like – Twitter.  To him, it is a total waste of time in every way. He can’t imagine why anyone would spend any time at all having anything to do with Twitter.  And that’s fine – to each his own. But I do find it amusing that someone would feel that way about a service used and enjoyed by millions of people. 

I’m a Twitter lover.  I find it entertaining, amusing, interesting, and good for my brain.  I really enjoy reading it, and I really enjoy posting tweets.  I get good news, good development information, and a good laugh when I read twitter.  I get to express my self in short bursts that  help me formulate my thoughts.  What’s not to like?

The common impression is that Twitter is for “letting you know what your friends are doing” – or at least that is how it was originally marketed.  The common misconception is that Twitter is just a bunch of people posting “Now I’m eating lunch.  Yum!”, and perhaps it was that in the very beginning.  But in the spirit of “Let a thousand flowers bloom”, Twitter became a lot more than that.  Twitter is a forum for expressing not only what you are doing, but what you are thinking, what you are watching, what you are reading, and anything things that you are up to.  It is many things.  It is a means of conducting a conversation across the world.  It is a means of sharing information with like minded people .  It can help you track your customers are thinking.  It can be a source of entertainment.  It can ensure you are up to date on the latest news, and it can even help foment a real live revolutions.  Not bad for a site that posts things  140 characters at a time.

Short and Sweet

Here’s the main reason why I like Twitter:  It forces us to express ourselves in short, concise sentences.  140 characters isn’t a lot, but it’s not nothing.  It is sort of real-world application of Strunk & White’s exhortation of “Use fewer words”.   It’s really quite amazing the amount of humor, wisdom, and pith people can cram into that little chunk of text.  Anyone who cruises around the internets knows that, while it allows people to publish openly without the barrier of a publishing house, folks – this blog included – don’t get the benefit of an editor.  Twitter is the one place where you can know that if you read it, you’ll get things in short, concise, crisp chunks.  (And I should add that I pride myself on never using ‘4’ and ‘2’ and other similar shortcuts….)

I find that pleasing as a reader, and valuable as a writer. If I can express my thought in 140 characters, then I know that I’ve really distilled it to the essence of the thought.  For instance, it took a while for me to get Hodges Law down to 140 characters but I did.  (And I also now have the added advantage of it being in a single place that I refer to my awesome idea – as well as showing that I was the first to think of it.  Winking smile  )

The other big reason I like Twitter is that it is an “easy read”.  If I have a few minutes to kill, I can pull out my Kindle and flip through the latest on my Twitter feed. I’ve knocked out more than a few pages of Twitter feeds at the Doctor’s office.  It also is perfect for solving that First World Problem of being bored while, ahem, “indisposed”.

Third reason?  It’s a wealth of information about Delphi and software development.  Many great developers tweet, and point to articles and blog posts that teach and explain about development.  Want to know what the latest Delphi articles are?  Follow DelphiFeeds.   You can’t say it is impossible to know what is going on with Embarcadero – they have a Twitter feed that updates with just about everything going on with the company.  You can tailor your feed to bring you whatever you are interested in.  I’m interested in Software Development, the NBA, specifically the Timberwolves, certain American Idol contestants, and generally funny stuff.  That’s exactly what my feed brings me. 

HashTags

Another feature that is both fun and powerful are hashtags.  As far as I know, the power and coolness of hashtags was actually an invention of the Twitter community and not an original part of the “spec” for Twitter.  According to this article – which is a great history and summary of hashtags -- the idea actually came from a guy named Chris Messina, and his idea has become part of the power of Twitter.  Hashtags are used to create groups or topics.  Sometimes they are fleeting – like a hashtag for the Superbowl – or sometimes they are ongoing, with people constantly adding to them, like the “#overheardathome” tag.  Want to see what others are saying while American Idol is on?  There’s a hashtag for that.  They have even made a difference in world events.  The valiant folks fighting for freedom in the Arab Spring used twitter hashtags to inform the world and each other about important, world-changing events.  Businesses are event starting to include hashtags in their advertisements (and of course, folks aren’t always respectful of those tags…..)  There’s even a website dedicated to tracking the use of hashtags.  From the humble beginnings of an idea from a single users, hashtags have made twitter into a useful and powerful communications medium.

Comedy

It may have started out as a site to tell your friends that you are eating lunch, but Twitter has become a great place for some quick-witted comedy and entertainment.  Heck, I tweet a lot about technology and programming, but I try hard to make a witty, funny comment every once and a while.   Some people’s sense of humor is just made for Twitter.  One of my favorites is Josh Hara.  If you are looking for a series of laugh-out-loud funny, but off-color tweets, look no further than Pauly Peligroso.    There are tons of lists of (allegedly) funny people on Twitter.  I should add that in my experience, the people that are “supposed” to be funny – that is, comedians whose names you know – aren’t really that funny. But hands down, bar none, the funniest feed on Twitter is Sh*tmydadsays.   In any event, Twitter can definitely make you LOL.  (I only use “LOL” when I, well, actually do laugh out loud. You should follow the same rule.)

Parody and History Sites

Another feature that dovetails on the straight comedy sites are some of the excellent parody sites.  There’s a whole slew of Star Wars characters on TwitterLord Voldemort of Harry Potter fame is enormously popular, on topic, and very funny.  He and Severus Snape often exchange barbs.  (Actually, there are quite a few folks tweeting as Severus Snape on Twitter….)  You can keep track of Batman, Drunk Superman, Aquaman  (Warning: he’s a little….”salty”), Spiderman, Drunk Hulk, and just (presumably sober Hulk. (Apparently there are many facets to Hulk’s personality). Want some history? You can follow Henry VIII, Calvin Coolidge,   You can follow the history of the Byzantine Empire, the first 1000 days of the JFK administration, and real-time events of World War II.  And that is just scratching the surface.  Believe me.  There is no end to the inanity, craziness, and imaginativeness of the folks on Twitter. 

In The End

Yes, Twitter would be boring if it were nothing more than people telling you what they were doing.  It may have been that at one point, but it’s become way more than that.  Shoot, a recent cover of Sports Illustrated had a hashtag for the cover article about Jeremy Lin. In the end, Twitter can me what you want it to be.  You can follow technologists, pop stars, actors, authors, characters from books and movies, business, news sites, newspapers, bloggers, family members, humorists, athletes, historical characters, and more.  You can keep up with technology, world events, politics, all manner of news and events, what your favorite authors/actors/singers are up to.  It’s really a huge, fascinating party that you can control to your heart’s content. 

Why anyone wouldn’t be interested in that, I have no idea.

Three Sentence Movie Review: Drive

By Nick at March 03, 2012 06:32
Filed Under: Three Sentence Movie Review

Drive: Hey, I’m as big a Ryan Gosling fan as the next guy, but holy cow is this movie ever boring, filled with lots of silent, forlorn staring and longing. In addition, I can’t stand a movie where the “hero” drives away, leaving a bag with a million dollars in it lying on the pavement.  Seriously?

My Book

A Pithy Quote for You

"When things go wrong in your command, start searching for the reason in increasingly larger concentric circles around your own desk."    –  General Bruce C. Clarke

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.