A man's got to know his limitations

I was thinking about if statements the other day, and came up with this potential Rule of Thumb: “Every time you write an if statement, you should stop and consider whether you should be creating a new class instead.” Thoughts? (Now, I’ve been around long enough to see how this might go. Before commenting, note that I did not say“Every time you use an if statement, you should create a new class”. I merely said that it is a point at which you should consider it…)

Embarcadero has made an interesting move – they have bought AnyDAC from DA-Soft. They’ve also hired Dmitry Arefiev to continue maintaining and developing the framework. Marco has more details on his blog. You can even sign up to get more information as news breaks (I guess…). This is actually a huge move – there’s quite a bit of overlap between AnyDAC and dbExpress, so it will be interesting to see how this plays out. I myself don’t know anything about AnyDAC, but you can get a trial version from their website. I for one will be curious to see how this all plays out. Database access is obviously a core function of Delphi, and this appears to be a radical shift in that area. I presume details on SKU’s, pricing, etc. will be forthcoming.

I’m currently reading Head First Design Patterns, and am finding it very useful and educational. One problem, though – it’s all in Java. So I thought that as part of the exercises, I’d translate the code to Delphi. And also as part of my learning process, I thought it would be a good idea to post an article about each of the patterns. I also encourage you to buy the book and read it for yourself.

Let me be clear – I’m not doing any more than reproducing the demos in the book. I’m very aware that there are better ways to implement the patterns than are shown here. The idea is to learn the pattern, not optimize the code.

Continuing on through HFDP, the next pattern we’ll cover is the Decorator Pattern.

One of the themes of the book is to make your code as flexible as possible at runtime, and to design your code to prefer runtime flexibility over compile time flexibility. Anytime you determine something at compile-time, you lock that feature in to your code. It can’t be changed at runtime.

Inheritance is a pillar of OOP, but it is a compile-time construct. Inheritance is powerful, but inflexible at runtime. You have the classes you have, and they can’t be altered or changed once you set them in the stone that is compiled code. If you are trying to come up with differing combinations to decorate each class, you can end up having a huge number of descendent classes which can become difficult to manage and maintain. Changes to one of the features means any number of descendants might need to change as well.

The decorator pattern is a way of circumventing these limitations, and providing the power of inheritance while at the same time providing run-time flexibility. It actually uses some simple inheritance to “wrap up” a given class and provide additional functionality without having to change the original class.

Here is the formal definition from Wikipedia: The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality. You can read more about the pattern on Wikipedia.

It’s actually pretty straight-forward. Here’s what you do:

First, you start with the notion of a class that needs to be decorated. It becomes the “base” class. The example in HFDP is that of a coffee drink. They coffee itself – a beverage – is the base class which can be any number of different coffee types. Each will be decorated with various flavorings, etc., such as milk, mocha, and cream whip.

Then you create a single descendant that will be the base decorator class. That class will take as a property an instance of the original base class. The base decorator should have a constructor that takes the original base class as a parameter.

Next, you create concrete instances of decorators that override the necessary methods and properties of the base decorator class.

From there, you can start with the base class, and then chain together as many decorators as you want.

Okay, let’s take a look at that in code. Here is the base class, TBeverage:

The base class is abstract. It has two properties, with the Cost property being read-only and having an abstract, virtual getter.

TBeverage is the base class for the beginning of the wrapping process. We create descendants that will form the base class described above. These classes override the Cost method, providing their own prices. They will be the starting point for decorating. In our case, we’ll create specific base coffee types that can be wrapped:

TBeverageDecorator does three things. One, it descends from TBeverage. Two, it gets another instance of TBeverage from its constructor in order to “wrap” itself around the starting base class. And three, the destructor ensures that the internally stored instance gets freed properly when that time comes.

Since TBeverageDecorator is itself a TBeverage, you can continue wrapping the previous result in a new one, decorating the decorator as it were. In addition, it will have the exact same interface as the base beverage class, so it can act like a beverage because, well, it is one.

As for classes that do the decorating, they will descend from TBeverageDecorator:

First, they override the getter for the Description property. They do it in an interesting way. Since they are decorating the base Beverage, they assume that they are “additive”, that is that they will be adding on to the base description. The TMocha.GetDescription method looks like this:

This will build the description and calculate the correct price, and result in:

Another way that you can create a coffee is by simply nesting each decorator in the constructor of the previous one. This method actually provides a coding representation of how each decorator wraps up the previous one:

The decorator classes both descend from and maintains a reference to that base class. This means that they will have the same interface, yet the reference will allow composition instead of inheritance.

One or more decorators can be wrapped around the base class and each other to produce a single entity.

The Decorator can augment the behavior of the class it is wrapping. We see this with the Cost and Description properties.

You can dynamically decorate objects at anytime, enabling you to create any combination of decorators without having to create a descendent class for each.

Decorators allow you to extend behavior of existing classes without needing to modify existing code.

There are some problems here – you can end up with a lot of little classes to manage; that might bother some people. Use of decorators can lead to complex code and implementations – use them with care.

However, the basic idea is to simplify and add flexibility to your code over a complex inheritance model. In addition, it makes it easier to build a single instance at run-time of complicated combinations of features or items.

I’m currently reading Head First Design Patterns, and am finding it very useful and educational. One problem, though – it’s all in Java. So I thought that as part of the exercises, I’d translate the code to Delphi. And also as part of my learning process, I thought it would be a good idea to post an article about each of the patterns. I also encourage you to buy the book and read it for yourself.

The first real pattern that the book shows is the Observer Pattern. You should use the observer pattern when you have one object that notifies other objects when events occur. Or more succinctly, use it when you have an object that needs to notify other objects about stuff that happens.

HFDP uses the example of a simple weather station that gathers data about the weather. Each time the weather station takes readings, it needs to update the views of that weather. The weather station reports on Temperature, Humidity, and Pressure. There are three views that the application provides – current conditions, statistics about the weather, a simple forecast.

The idea here is that the weather station is the subject – it is the object being observed and doing the notifying. The different displays for the information are the observers – they watch what happens on the weather station and update themselves based on the notifications that they receive from the weather station. Another way to look at it is that the weather station is a publisher of information, and the displays are subscribers.

The formal definition given for the Observer Pattern goes like this: The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

But when it comes time to implement this, the temptation is to simply embed the displays inside of a method of the weather station. You might create classes for each view, instantiate them in the weather stations constructor, and then simply update the views in a method called MeasurementsChanged.

But of course if you do this, you are breaking some of the base design rules. First, you’d be coding against an implementation instead of against an interface. Second, you’ve made it really hard to add a new data display should that become necessary. Displays are hard-coded into the weather station and can’t be added or removed at runtime. If we do want to add more displays, we’d need to modify the weather station itself. Or, put more succinctly, the weather station and its displays are tightly coupled to each other. And if you know one thing about me, I abhor tight coupling. And you should too.

In any event, there is a better way – the Observer Pattern. As noted above, observer pattern consists of a Subject that is monitored by Observers. We’ll implement a very simple version of the observer pattern. The first thing we will do of course, is declare two interfaces:

The first interface is IObserver, which the observing classes will implement. In it they’ll be updated with all the weather information that the weather station has for us. The second is ISubject, which will be implemented by the weather station. It takes three methods, two for handling the connecting and disconnecting of IObservers, and the third for doing the actual notification to the observers.

The first implementation we’ll look at is the Weather Station. Here is its implementation declaration.

The plumbing for managing the weather implementation is all what you’d expect. The interesting part, of course, is the implementation of ISubject. Internally, it uses a TList<IObserver> to manage all the observers that get registered with it. The RegisterObserver and RemoveObserver methods simply insert and remove, respectively, instances of classes that implement the IObserver interface.

The real action occurs in the NotifyObservers method. We’ll get to that in a second. First, though, let’s take a look at the observers. Since all the displays are very similar, this is a good time to use good old-fashioned inheritance to declare a base class that implements the needed functionality, and then have descendent classes that do the work of providing the specified displays. Here, then, is the interface for TWeatherDataDisplay:

TWeatherDataDisplay has fields to keep track of the current weather information. It’s descendants can do with it as they please. It also implements the IDisplay interface so that it can report out what it has to say. The Update method will allow the Subject – in this case the weather station – to update the displays. Update is a virtual method, by the way, so that descendants can do different things with the incoming information.

Okay, so let’s look under the hood. The weather station can accept and remove IObserver implementers at runtime. implements the NotifyObservers method as part of the ISubject interface. It gets called whenever the weather information changes. It is implemented as follows:

This is pretty simple – it merely enumerates over each item in the observer list and calls the Update method, passing along the new weather data. The base class stores the information, and its descendants process it.

The real “work” gets done when the weather station updates the temperature data and calls NotifyObservers:

This code doesn’t write anything to the console. All of that is done by the display objects that get registered as observers. Each observer is registered, and the code pretty much forgets about them. To the weather station, they are merely IObserver interfaces, and the only thing you can do to an IObserver is call it’s Update method. From the Weather Station’s perspective, there’s nothing else to it.

Four calls to SetWeatherInformation result in for reports from all of the updates to the temperature information.

Once you have a reference to a TWeatherStation, you can add or remove displays at runtime.

TWeatherStation doesn’t know anything about Weather displays – it only knows about IObservers. This means that you could have observers that do other things besides being Weather Displays. You could simply store the weather data, or anything else at all. For instance, you could create a TWriteWeatherInfoToDatabase class that implements the IObserver interface. The Weather Station itself neither knows nor cares. IObservers are under no obligation to do anything specific with the data passed to them.

We can change the observers anytime we want without altering the Subject. We can add new observers, too. Basically, observers and subjects are very loosely coupled, and either can be changed, altered, updated, and added to without having to worry about changing the other.

So that should be a quick rundown on how the observer pattern works. The obvious weakness here is that our IObserver interface is very specific to weather data. You can create your own interface for your specific implementation. The pattern remains the same no matter how the IObserver interface is designed. This is obviously a good place for generics to enter the picture, and in fact, the Delphi Spring framework implements a generic IObservable<T> interface and implementing class.

So in summation, the Observer pattern ensures that publishing classes (subjects) can communicate updates to their subscribing (observer) classes with very loose and flexible coupling. Observers can be updated and removed at runtime. Adding observers requires no change to subjects. Subjects don’t know much at all about what the observers are up to. It’s all very easy and elegant and loosely coupled – just like you want it.

There are a lot of cool things that an IDE could do, but it’s getting to the point where my one top feature for the IDE is the automatic addition of interface methods. If I declare a class that implements a given interface, the IDE should automatically fill those in for me. That would be really sweet. This feature is in third place in the IDE section of Delphi’s User Voice page. Feel free to vote for it.

Embarcadero has announced the coming of Delphi for iOS. I’m not an iOS guy – I’m waiting for the Android stuff. I don’t have an Apple device at all, and you need one to develop on. (There’s no iOS emulator or simulator for Windows – everything has to run on Apple hardware/software…) so it’s not of any use to me at the present. However, I’ll be keeping a close eye on this, as I’ll be developing for Android as soon as I can with Delphi, and I suspect I’ll eventually be wanting the results of that to run on iOS as well. After all, that is one of the promises of FireMonkey – to have a single codebase that runs on Windows, iOS, and Android. In any event, no one can say that Delphi isn’t alive and kicking. The new offering includes a Delphi compiler for ARM chips, which is pretty exciting if you’ve been wanting Delphi to branch out. And the best part is you can get early access to the beta if you buy XE3.

Delphi Developer Days is back this year – with two dates in Europe and just one in the US (Chicago). Cary has all the details. I’ve been to a couple of the events, and they are really fun and well worth the time. If you can make it, I strongly recommend the event. Dr. Bob is certainly a more than able replacement for Marco. With no Delphi Live in the future, this is really the only US conference where Delphi folks can gather. I’d like to see them add an East Coast date in the US. Otherwise, I’ll try to get to the Chicago event.

Now here’s a blog after my own heart: LooseCouplings.com Sadly, it hasn’t been updated in a while, and there are only a few articles, but what is there is really good. There are four or five articles about Dependency Injection (particularly about how it doesn’t necessarily mean using a DI Container…..) and we’d all do well to read and heed. Thanks to Stefan Glienke for pointing me to it.

I wanted to strengthen my SQL skills, so I decided to give Head First SQL a try. It was my first foray into the world of the Head First Series, and I was pleasantly surprised. I wasn’t quite sure what to expect, but what I got was a great review/tutorial on SQL. The examples were simple but to the point, the style a touch irreverent but enjoyable, and I actually did, and learned from, the exercises. Now I’m working on Head First Design Patterns which so far is the same: excellent, interesting, and attention-holding. I do believe that I'll seek out Head First titles in the future if I want to learn something new.

I’d like to put in another plug for the Google Plus Delphi Developers Community. We’ve been having a lot of fun over there – or at least I have, maybe the rest of the folks are sick of me. In any event, please stop by and participate.

A while back I wrote a “How Not To Code” about not using Booleans as method parameters. This line of real-world code that I ran across today -- myMonster.Run(cSourceStateLicenseWebNew, '1', '', False, False); -- is a perfect example of why this shouldn’t be done. Who the heck knows what those last two parameters mean?

Okay, I did a little more research on Arduino vs. Raspberry Pi, and I think I’m going to start with the Arduino. It seems more “science project-y” whereas the Raspberry Pi seems more like a complete computer solution. Both sound great, but I’m more interested in the “controlling something” aspect rather than the “use all that small but powerful computing power”. I think the Arduino would provide more stuff for me to do with my kids in terms of “making it all come alive”. That’s kind of what I’m interested in, really – the “Mr. Science” kind of stuff. Thanks to you all for the feedback.

One of those fun little issues in our business is trying to figure out the difference between iterating and enumerating. This StackOverflow answer does a pretty good job of explaining it. Iterating is doing something – usually a series of steps – over and over again. Enumerating is going over each item in a given collection. A subtle difference, sure. One usually iterates when enumerating.

Okay, so enumerating is going over each item in a collection. IEnumerable can enumerate over the items in a collection as we saw in my last article. But you can enumerate over other things as well. For instance, in Delphi, you can use the for…in statement to enumerate over the characters in a string.

But this makes me wonder: how does something become, well, enumeratable? How do you make something so that you can use with the for…in statement?

Well, it’s pretty easy. The rules for Delphi are simple:

To create a class or record to enumerate, it must provide a method called GetEnumerator() which in turn needs to be a function that returns a class, an interface, or a record that is an enumerator.

To be returned as an enumerator, that class, record, or implemented interface needs to have the following:

A method called MoveNext that returns a Boolean indicating whether the end as been reached or not

A read-only property called Current that indicates the item that is currently being “looked at” as the enumeration occurs.

So, at this point, a simple demo would be helpful, eh?

You can already enumerate the characters in a string, but it’s a simple example, and so the following example implements this easy to understand enumeration on a string:

This code declares two classes. The first class is the enumerator – the class that does the work of moving over each item, and which will be returned by the call to GetEnumerator. The second is the class that will be enumerated. Notice, too, that TForInDemoClassEnumerator has the read-only property Current with the reader GetCurrent and MoveNext methods. The TForInDemo class has a call to GetEnumerator that returns an instance of TForInDemoClassEnumerator.

First let’s look at TForInDemoClassEnumerator. You create it by passing the constructor the item to be enumerated – in this case a string. Hence, the constructor:

This code does two things. First, it sets the result. The function returns True if the enumerator is able to move to the next item, and False if it has reached the end of the items to be enumerated. In this case, it merely checks to see the index is before the length of the string. If the end has not yet been reached, it just increases the FIndex field. So it’s job here is merely to move the index along, and report if the end has been reached.

The actual item itself is returned by the GetCurrent method, which is self-explanatory:

And that is it for the enumerator. It’s pretty simple. But we’ll soon see that you can do some cool things with these enumerators because you have complete control over how they return the data that they are enumerating over.

The next step is to see how the actual class to be enumerated provides its enumerator to the compiler. When the compiler builds the for…in loop construct, it looks at the in part of the construct and thinks “Hey, I need an enumerator here, so I’ll call GetEnumerator”. If the item in question indeed has a method called GetEnumerator, it calls it, and all is well. If not, the compiler raises an error because the type in the in part of the for…in loop isn’t enumeratable.

But of course, our TForInDemo class has such a method, and it is quite simple:

IEnumerator<T> Interface

Now the above discussion talks a lot about specific methods that must be included as part of an enumerator, and as part of a class that wants to be enumerated. And of course, that should immediately make you think “Interfaces!”. And sure enough, there are some nice interfaces that fall out of this. (You knew I’d work interfaces into things here eventually, didn’t you. Yes, you did.)

That should look awfully familiar. It’s the exact two methods and one property needed to implement an enumerator – hence the name.

I’ve declared this IEnumerator<T> interface myself, but the Delphi RTL includes a similar one in the System.pas unit. And at its base, IEnumerable<T> is all about implementing the GetEnumerator method.

It leverages generics because the type of what is being enumerated doesn’t matter as far as the interface is concerned. And remember when I said that a call to GetEnumerator could return an interface? Well it can, and the compiler will happily use an IEnumerator<T> to implement the for…in loop.

Thus, your enumerators can implement this interface and your calls to GetEnumerator can return this interface, and you can add flexibility to how they are implemented. Here’s an example:

Notice that the call to GetEnumerator returns an IEnumerator<Char> which is actually the individual type being iterated. In this case, the generic type needs to be the same type as the variable being returned in the for part of the for…in loop.

Specialized Enumerators

The implementation of an enumerator is, as I mentioned, really simple. But what if you wanted to get a little creative in the GetCurrent method? After all, at that point you have complete control over what the enumerator returns. In our simple case with characters and strings, what if we decided to, say, always return the upper case version of the character? Or if we were iterating over integers, return the squares of the numbers in the collection? That would be super easy, right? Well, yes, it would.

This class descends from TForInDemoClassEnumerator and overrides the existing enumerator for our demo class and returns the upper case of the character in question.

If we wanted, we could return this class from our GetEnumerator call, but that would be sort of playing a trick on the user of our code. How about if we provide two different enumerators, and then make each available for enumeration in a for…in loop. Surely that is possible, right? Of course it is.

First, we’ll look at the end result and then work our way backwards to see how it was implemented, because you have to play a little trick to expose more than one enumerator for a class:

This little routine will display the string “Greetings” as “G,R,E,E,T,I,N,G,S” in the console. But note in the for…in loop that the actual class is not passed to the in clause, but a method that returns a “proxy” class that has the desired enumerator attached to it instead. This is implemented as follows:

This is just another class that can be enumerated – it has a call to GetEnumerator – and thus be returned by a method call on our “real” enumerating class. It returns an instance of an enumerator called TForInDemoClassUpperCaseEnumerator which we looked at above. So, if you want to iterate over the upper case version of the strings, you call it as we did in the DoMoreStuff method above. The trick here is that instead of iterating over the class itself, you iterate over the proxy class using ForInExtraDemo.AsUpperCase. It’s a neat little trick, eh?

Conclusion

So, that should give you a little insight into what happens with for…in loops and how you can create classes that participate automatically. I’m working towards never using the old for I := 0 to Count –1 do; construct, and making my classes enumeratable.

The new year means an updated look at the TIOBE Index! And guess what language is #1 for 2012? C. Not C++, C. It’s moved past Java as the most popular language. That’s kind of a surprise to me, anyway. Delphi continues to hold it’s spot in the “A” language at #15. They seemed to have combined “Delphi” and “Object Pascal”, but put “Pascal” in its own category. This makes no sense to me, but oh well. If you combine the numbers all up, “Delphi/Object Pascal/Pascal” ends up at number 11 ahead of Ruby. Completely respectable if you ask me. Another surprising thing to me on the index is how low Javascript ranks.

Inspired by this StackOverflow question and a thread in the newsgroups, I thought that I’d write an article about a very powerful but not so well known (apparently) feature of Spring4D – IEnumerable<T> and the accompanying container interfaces and classes.

So the StackOverflow question basically asks this: How do I find out the maximum value of an integer in TList<integer>?

Well, the first thing you might do is use a for loop to check each item, and save each one as it gets larger. Or if you were really tricky, you’d use a for…in statement to find it. That’s the “straight-up” way to do it.

Now that looks quite a bit different than the code you were thinking of, I’ll bet. There doesn’t even appear to be any looping going on at all. There is in the background, but it’s all been abstracted away for you. You want the maximum value to be found in the list? Just ask for it. Cool.

The key part above, of course, is the use of two things. First, the IList<T> – an interface to a generic list – and secondly, the IEnumerable<T>. Both of these types are provided by the Delphi Spring Framework. Both are defined in the Spring.Collections.pas unit. That unit contains a complete group of collection interfaces – IList<T>, IStack<T> ICollection<T>, etc. – as well as the definition of IEnumerable<T>.

I’d recommend that you consider using Spring.Collections.pas instead of the Generics.Collections.pas unit which comes with Delphi. First, it exposes all of the collection types as interfaces, and you should know by now that you should be coding against interfaces and not implementations. Secondly, each of the types supports the IEnumerable<T> interface, meaning you have the power of this great interface on all of your collections.

We’ll tackle those two things in order.

Spring Collections

The Spring.Collections.pas unit is all you need in your uses clause to avail yourself of all that the Spring collections library provides. The unit includes the following interfaces along with a class to provide easy access to implementations of these interfaces:

Interface

Description

ICollection<T>

A Collection is a group of items in no particular order. You can't insert items into a specific location in a collection, only add or remove them. A collection can’t be sorted because it has no order.

IList<T>

A list is a group of items in a particular order. Items can be sorted and inserted in particular locations.

IDictionary<TKey, TValue>

A dictionary is a data structure that allows you to “look up” items. Each entry takes a key and a value, and values can be looked up by asking for it via the item’s key. This is a useful data structure, as any type can be uses as the index, and any type can be stored for lookup.

IStack<T>

A stack is a First In, Last Out data structure. Think of a spring-loaded stack of plates at the cafeteria – you “push” plates onto the stack, and then “pop” them off in reverse order.

IQueue<T>

A queue is a First In, First Out data structure. Think of an ordinary line that you wait in, or a tube in which items are inserted at one end and taken out on the other.

ISet<T>

A set is a data structure involving membership. Items are either in the set or out. A set’s methods allow you to determine the intersection, union, or overlap with any other container.

All of these types should be familiar to you – if not, you can certainly read up on them via Google. The important part is that they are all generic (though there are non-generic types with store TValue as well) and they all implement IEnumerable<T>.

The unit also provides a class called TCollections which has nothing but class methods that return instances of the types listed above. These methods act as proxies for the constructors of the implementing types. You can create your own instances if you like, but for the most part, TCollections will do the job of getting an implementation of whatever container interface you want. For instance, if you want to get a hold of a dictionary, you can do the following:

The example above uses TCollections.CreateList<integer> to get an implementation of the IList<T> interface.

The implementations are all in units named Spring.Collections.Stack.pas and the like, but the Spring.Collections.pas unit exposes almost everything you need, and so as a rule, you should only need it in your uses clauses to take advantage of these powerful containers.

IEnumerable<T>

Those of you who also use .Net are familiar with IEnumerable already, but perhaps you didn't know that the same power was available to you in your Delphi code. For those of you not familiar, you are in for a treat.

The IEnumerable<T> interface is implemented by all of the classes discussed in the previous section, and so any of them can be accessed as an IEnumerable<T>.

That’s a lot of cool stuff, right? Many of the methods here are pretty clear -- it's pretty obvious what the Min and Max methods do. But some of the others are a bit trickier. You can get all of the items. You can get the First and Last items. You can get the first x number of items. You can get the items back out as a List, an Array, or a Set. And most powerfully, you can get any particular group of the items out using a predicate.

Predicates

What is a predicate? A predicate is an anonymous function (or any function, really, but in our case it is an anonymous function) that takes a single const parameter of the type in question and returns True or False.

TPredicate<T> = reference to function(const value: T): Boolean;

It is used with some of the methods of IEnumerable<T> to answer this simple question: In or out? If the predicate is true, then the individual item is “in”, or included. If it is “out”, then the predicate will return False. So if you want to get all the items in a list strings that contain the letter ‘z’, then you can do the following:

The above uses the Where method to determine items that should be returned as part of a new IEnumerable<string>. The above is saying “return to me an enumerable item where all the strings in the list have ‘z’ in them.”

You can do similar things with the TakeWhile method, which returns items from the start of the list as long as the predicate is True, and stops once the predicate is False. You can determine if a given container has or doesn’t have a given element. You can Skip over a given number of elements and take the rest. You can use a predicate to SkipWhile a certain thing is true, and then return the rest once the predicate returns True Basically, once you have a reference to a collection or any IEnumerable<T> instance, you can get out of it pretty much anything you want.

Something to consider: If you have a nicely composed class that includes a private IList<T> which gets exposed through proxy methods, then you might want to expose access to the items via a property of type IEnumerable<T> instead of exposing the actual list itself.

And the real power gets unleashed with the very powerful ForEach methods. Folks have always pined for the lovely ForEach since the days of Borland Pascal’s old TCollection object, and now it’s back in full force, leveraging the power of anonymous methods. Thus, you can have a collection and do what you please with the items. Here is a simple example of just outputting them to the console window, but you can have your TAction<T> do anything at all that you like for each (sorry) element in the container.

So, basically you have a lot of untapped power there in Spring.Collections.pas, eh? The use of IEnumerable<T> and predicates ought to transform your code and change the way you look for things in lists and collections. If you aren’t using these powerful tools yet, I strongly recommend that you add them to your tool chest.

Remember, the Delphi Spring Framework is more than a Dependency Injection container. And there’s more to it than the container classes as well. I strongly recommend that you start treating Spring4D like part of the Delphi Runtime Library. Heck, I wish Embarcadero would do just that.

Am I weird? One of the first things I do when I install Delphi is to turn off Brace Matching and Line Highlighting. I find both of these features incredibly distracting, particularly the Brace Highlighting, which makes it impossible to see where the caret is in the text.

This article by Hal Berenson should make interesting reading for Delphi folks interested in the economics of development tool vending and the business models around them. Delphi isn’t mentioned, but it does discuss the changing business model of Visual Studio from within Microsoft and how Adobe’s tool business put pressure on MS and actually changed how they did business. MS’s Interesting stuff.

I love Twitter and try to tweet pretty frequently (I’d be honored if you followed me). One of the fun part of tweeting is seeing the creative and interesting use of hashtags. One current hashtag that is going around and that is of interest to us Delphi developers is #code2012. In it, folks are putting the names of the languages that they coded in during the past year. Someone has a nice graphic that shows the relative popularity – and Delphi isn’t doing too badly. I just tweeted to help make that Delphi circle just a little bigger.

Holy cow, I feel like I did when Buffy ended – stunned and saddened. Žarko Gajić is moving on from his position as the guide for About.Com Delphi. Žarko has been doing that job for 15 years, and I’m willing to bet that his site is as common a search result as any in the community. Well done, Žarko, and good luck in your future, Delphi-related endeavors. And hey, the door is open – anyone willing to step into Žarko’s shoes?

I’ve shamelessly tweeted it a couple of times, and I’ll promote it here as well – I’ve created a Bookstore page here containing a list of books that I think are must-reads for all developers. What books would you add to the list?

Okay, I need some advice: I want to learn a functional programming language, but which one? Clojure? Haskell? F#? What?

I need some more advice: I have a good working knowledge of SQL and SQL Server. But I’m going to need to become a SQL Server 2008 expert in the coming months. Can any of you fine people recommend the best book or other resource for going from the basics to really being a guru? Again, I’m looking specifically at T-SQL and SQL Server itself.

That simple lyric holds a valuable viewpoint for leaders. The song, of course, is about a girl. But imagine you are holding a small bird in your hand. If you hold the bird too tightly, you’ll crush it. If you hold the bird too loosely, it will escape. But if you hold it just right, not too loosely and not too tightly, then the bird will stay in your hand, and maybe even feel safe. And if you focus on it, it’s probably not too hard to figure out just the right amount of pressure to keep the bird in your grasp.

It’s the same way with leadership. One of the toughest decisions leaders make is how much control to exert over their people. It’s a delicate balance. Both too much and too little can cause difficulties and cause you to lose your team. Finding just the right amount of control is a large challenge.

The tendency of many leaders is to “cling too tightly”. They tend to want to have close control over their people. They want to make sure every little detail is taken care of, setting rules, procedures, and processes for every little thing to ensure that things never get out of control. They view their people as merely cogs in machine, and thus give them little autonomy to make decision, innovate, improvise, and otherwise come up with their own solutions. They make every decision, ensuring (in their minds) that things are going perfectly.

There is a word for this – micro-management. No one ever thinks that they are being a micro-manager. In my experience, the more a leader micro-manages, the more he thinks he isn’t. Micro-managers tend to think that they are providing leadership because it’s needed, because their team can’t be trusted, or, sadly, because they think that their team is simply incompetent to do the job. Or perhaps they feel that they have to be involved in order to get the credit.

Whatever the reason, a leader who clings too tightly is being ineffective and usually has a negative effect on her team. People feel the lack of trust, and that’s demoralizing. Teams that are given little autonomy soon lose their desire to improve and find better ways to do things. When their leader has all the answers and always knows what is best, why even try?

But holding on too loosely can have a similar effect. If a team feels that their leader can’t make decisions or is wishy-washy, then they feel adrift and unsure. No one likes a ship captain who doesn’t know where the ship should be going. And a ship that is headed nowhere will surely get there. Not making any decisions is no better than making all the decisions.

The trick or course, is to hold with just the right amount of pressure. Good leaders find that perfect balance between control and chaos. They let their team decide how to accomplish tasks within general guidelines. They encourage improvisation and innovation in a search for better ways of doing things. They know that there are some things that need to be done a certain way, but that there are many things that don’t. They trust their team to get things done their own way. They know that if a team member gets credit, it reflects positively on their leadership.

In general, they hold just tightly enough to keep things in control. They let team members make decisions. They recognize that mistakes will be made and that daring to do something different is a feature, not a bug. They make decisions when the team needs a decision, and they delegate decisions as much as possible. They recognize that they have a tendency to “squeeze to tightly” and thus, when in doubt, tend to err on the side of holding too loosely. They understand that autonomy and self-direction are very satisfying, and do everything they can to provide that to their team.

Just as a good veterinarian knows how to hold a bird with the right amount of pressure, a good leader knows the precise amount of control to exert over his team.

I never cease to be amazed at how little the average developer knows about economics. I mean, I don't claim to be an expert, but I have taken a college class or two and read up on the basics. Even just understanding the basics, though, gives one surprising insight into why things happen the way they do in the marketplace.

For instance, we are in the process of hiring a new developer at my company. We figured out what qualifications we were looking for and determined about how much salary we wanted to pay. It quickly become apparent, however, that we weren't offering a high enough salary to attract the caliber of candidates we wanted. So what I did was to go on the newsgroups and start whining about not being able to find any good Delphi programmers. Okay, no, I didn't really do that. What we did, of course, was to increase the salary that we were offering. Simple supply and demand issue: There wasn't enough of a supply of good Delphi programmers at the price we wanted to pay, so the solution is to be willing to pay more – a no-brainer decision, really. Once we did that, we found that we have been able to find plenty of valuable candidates. Simple economics.

One common area that I see developers totally misunderstand is that of Delphi pricing. One thing you learn in Economics 101 is that the vast majority of companies are “price searchers”. That is, they are constantly searching for a price that will maximize their profits. (Some companies, mainly producers of commodities, are “price takers”. That is, they take whatever price is offered. Farmers are a good example. A corn farmer can only sell his corn at market price. If he asks for more, the market will simply buy corn from another farmer that will take the offered price). Borland is definitely a price searcher. They can set their prices as they please, and will do so to maximize profit. Of course, the market will respond to any particular price by demanding a certain number of units at that price. Price searchers are constantly adjusting prices to maximize the amount of money they make.

Note that they don't set price to maximize revenue, but rather profit. The cost of goods sold is a factor here as is the cost of simply having customers. Sometimes a company will actually price a product in order to limit the number of customers they have in order to maximize profits as sometimes having additional customers causes decreased profits. (That may be a bit counter-intuitive, but think of a product that has high production and support costs.) So for example, sometimes doubling your price can increase profits even though it drastically reduces sales. If doubling the price cuts the number of customers you have in half, but also cuts your production and support costs in half as well, your profit increases. (This is a very simple example, and it is actually hopelessly more complicated than that, but you hopefully get the basic idea).

So Borland, having learned from years of experience and copious sales data, is quite aware of what effect various prices have on sales. No doubt by now they have a pretty good idea what price will maximize their profits and how price changes will effect sales.

Where it gets really interesting is pricing outside of the United States. Europe, of example, is a completely different market than the US. Taxes, the demand curve, and the number of potential customers are all different. Borland clearly believes that they need to – and can – charge more in Europe than in the US. The price difference is not related to the exchange rate between the Euro and the Dollar; it has everything to do with maximizing profits. Clearly Borland believes that a higher price in Europe – again, a completely different market – will mean higher profits. That's why Delphi costs more in Europe. I suppose Europeans could view this as “price gouging”, but in reality, it's just the market signaling to Borland that it will bear a higher price than will the American market. Simple economics.

Another economic blunder that developers frequently make is ignoring economies of scale. Borland is a big company that is publicly traded. Many Delphi developers work in small, private companies. Borland has legal obligations, overhead costs, and market demands that most little-shop developers don't even know about, much less take into consideration. Borland's main competition is one of the largest corporations in the world. Borland faces investors who expect a return. Borland has to deal with major entities in the media that can write things that can have profound effects on Borland's business. All of this combines to make running Borland a complex and difficult task that most of us simply don't comprehend.

So I love it when a developer posts in the newsgroups something like this: “Borland should just hire two college students to go through and fix all the Delphi bugs in Quality Central.” Well, that sounds great, but is clearly isn't that simple. First, fixing bugs in a big product like Delphi is no small, trivial task. Finding people with the talent and skill to do Delphi bug-fixing isn't easy. And they certainly aren't going to be cheap. The notion that some college interns can do it is quite naïve. The economic blunder comes, though, in thinking that the cost of fixing all those bugs is merely the salary of a couple of developers. First, employees aren't cheap, no matter who you hire. Human capital is by far the most costly – and valuable – part of doing business. Secondly, I don't know what your development process is like, but bug fixing at Borland is more than a guy hacking out some code. Every fix has to be extensively tested for efficacy and correctness, and then the whole product has to be regression tested to ensure that any given fix doesn't actually break something else. Fixes need to be incorporated into shipping product and distributed to existing customers. The documentation needs to be updated. And who know what else needs to be done? The point is this: the costs of things that many people think are small are in fact much larger than the average developer appears to realize.

The economics of running a business like Borland isn't something about which I claim to be an expert. But I do know that I don't know enough to be able to claim to know better than Borland. Something to consider before you fire off a post in the newsgroups that starts out “Borland ought to just....”

My Book

Stuff You Can Find Here

A Pithy Quote for You

"Courage is not simply one of the virtues, but the form of every virtue at its testing point."
– C. S. Lewis

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.