Friday, November 06, 2009

Casting lists using LINQ #2

In my previous post I showed the LINQ way to cast List<SomeDeriveType> to List<SomeBaseObject>.

IEnumerable<BaseObject> baseObjects
= DerivedList.Cast<BaseObject>;
Great stuff!

As @jamiei commented this will raise an exception if the cast fails. OfType<T> will return only the elements of type T despite the fact that you have different derived types in one list. So suppose you have an Animal class and a Cat and Dog class that derive from Animal you could do something like this:
List<Animal> animalList = new List<Animal>();
new Dog("Dog1"));
new Dog("Dog2"));
new Dog("Dog3"));
new Cat("Cat1"));
new Cat("Cat2"));
new Cat("Cat3"));
//Get the dogs
IEnumerable<Dog> dogList = animalList.OfType<Dog>();
//Get the cats
IEnumerable<Cat> catList = animalList.OfType<Cat>();

LINQ makes it very easy to seperate the Dogs from the Cats!

Wednesday, November 04, 2009

Casting lists using LINQ #1

I have been doing lately much work on a .NET 3.5 application using LINQ. LINQ is a great way to manipulate data. I still consider myself a 'LINQ rookie' so I discover everyday something new.

One thing that floated around my head a while was the problem that you can't cast a List<SomeDerivedObject> to List<SomeBaseObject>.
A poorman's solution to this was to loop the objects from the one list into the other list. Not an elegant solution though.....

I discovered that you can do this easily with LINQ. When you use a IEnumerable<T> you can do this like this:

IEnumerable<BaseObject> baseObjects
= DerivedList.Cast<BaseObject>;

Where DerivedList holds objects that inherit from BaseObject.
With a List<T> you could do something like this(copy):
List<BaseObject> baseObjects =
new List<BaseObject>(DerivedList.Cast<BaseObject>());

A great LINQ resource is 101 LINQ samples on MSDN.

Wednesday, August 05, 2009

Go see Delphi 2010

The first Delphi 2010 sneak peek video's showed up on the Internet. The first sneak peek shows some new IDE features like IDE insight, an everywhere context sensitive IDE navigation system.

Anders Ohlsson has a nice sum up of all the related Delphi 2010 blogposts.

Tuesday, June 30, 2009

CodeRush for free, not for Delphi Prism

As blogged before you know that I think DevExpress CodeRush totally rocks!
Did you know that you can get a lot of this functionality for free?

Mark Miller has got a very nice list of features that are available in CodeRush Xpress for C# and Visual Basic inside Visual Studio 2008. All for free!
In the full product you will get even more, check out the differences in this article: Moving up from CodeRus Xpress to CodeRush

Delphi Prism
The downside of all this good stuff is that Delphi Prism is not supported. The fact that the original CodeRush was a pure Delphi IDE product, I can not believe that it will not be supported in the future.

Monday, June 29, 2009

The future of Delphi

I haven't had much time lately to follow everything on the Delphi side of the fence, but there is a lot going on.
Stefaan Lesage has a nice write up on this future, The future of Delphi looks brighter than ever before.

A very nice read, sums up everything that is cooking in the labs, including the roadmap.

Monday, May 18, 2009

Applying Domain-Driven Design - Book review

Before this weekend I got my copy of Applying Domain-Driven Design and Patterns by Jimmy Nilsson.
Althought the title, in my opinion should be "Applying Domain-Driven Design, Test Driven Design and Patterns", because beside DDD it covers a great deal of TDD also.
Design patterns for me were always a bit fuzzy, something from far-far-away land. However lately I am having more and more interest in Test Driven Devleopment and that software design method drives you towards better, testable, design, and Domain Driven Design seems to being just doing that.

Back to book
When you order a book about Design Patterns you expect it to be more a reference then a complete read, because the stuff looks to be boring ('dry stuff' as we say here), without trying it out.
In this book however the author takes you on a journey of software architecture, design and decisions. The book gives lots of "Aha!", "Huh?" and "Done that" moments which, I guess, keeps you awake.
It is loaded with lots of solutions for particular (recognizable) software problems, not just pushing Design Patterns, but making you think more about the right solutions, which always depends....

In just three days I have read half of the book already! For me that is rare.

So if you are interested in better software design I can highly recommend this book, it reads like a breeze!

Friday, April 24, 2009

Exploring Test Driven Development

A few weeks ago I attended a software event organized by the dutch Software Developer Network SDN. This time I followed a few sessions about Test Driven Development presented by (among others) Alex Thissen, Thomas Huijer and Dennis Doomen.

I must admit that before this sessions I was convinced that automated unit testing was a plus, but it would take just too much time (at least that is what I thought) so that I never actually used it. Triggered by this sessions I started to explore TDD and slowly but surely I am convinced by its pros.

So what is it?
TDD is not strictly about testing, but it is a software design method build upon testing. Check the TDD wiki for all the details, but basically it drills down to the following:

Every new feature in an application starts with building a test around one unit of code (a method or property), because of the fact that the real feature is not yet written that test will fail. After making the test you write the actual method which correctness can be checked by running the test.
Kind of strange huh? First test, then code. But when you think about it a little more it is a great way to improve your code quality.

Consider the following:
- By building a test you are triggered to think more about the specifications, heck by building the test you 'persist' the specifications in your code. (If specification changes, the test changes)
- It doesn't matter who writes the actual method, as long as the test fails he/she did not comply to the specifications.
- New features and specifications, which leads to refactoring your code, will be checked against your tests. If the test passes you will be fine.
In fact in TDD you will first change/refactor your test before refactoring the real code.
- You will try to keep test as small as possible, thus making smaller methods in your applications, thus making it less complex.
Less complex means more maintainable in the future. (Less time/costs)

“I don't care how good you think your design is. If I can't walk in and write a test for an arbitrary method of yours in five minutes its not as good as you think it is, and whether you know it or not, you're paying a price for it.”
Michael Feathers

Testing in Visual Studio
Visual Studio 2008 now offers unit testing. You can add a test project in your solution that refers your application/code library.

Making a first TDD application 
Suppose we have some class Calculator with methods like Add, Divide etcetera.

Step 1
Create two test methods for the Add and Divide methods. A test method's result is stated by either an Assert, or an expected Exception:

public void Add()
int Int1 = 2;
int Int2 = 3;
int Result = calculator.Add(Int1, Int2);
5, Result);

public void Divide()
int Int1 = 6;
int Int2 = 3;
double Result = calculator.Divide(Int1, Int2);
2, Result);

public void DivideByZero()
int Int1 = 6;
int Int2 = 0;
double Result = calculator.Divide(Int1, Int2);

In the test unit we created our Calculator class which we will test. Of course without the actual code this will not compile, so we create the initial method stubs, which will throw a not implemented exception.

Step 2
Run the tests. No supprise they will fail.

Step 3
Write the real methods:

public int Add(int Int1, int Int2)
return Int1 + Int2;

public double Divide(int Int1, int Int2)
return Int1 / Int2;

Step 4
Run the test. They succeed! Because the not so well choosen parameter names you could easily mismatch them in the method Divide, but your test will check for that!

What is next?
This example is rather simple. Complex codes, with for example database interaction will require some more coding for which you will write fakes and mocks. I will explore them in another post.

Although you might think that Test Driven Development takes a lot time in the process I am convinced (now) that it will pay back further on in the development process. Beside that it will boost the quality of your code and give you a base to safely refactor it in the future.

The examples where build in C#. I am not sure if this works in Delphi Prism as well, but I expect that it does.

Wednesday, April 08, 2009

CodeRush, when code smells...

At the beginning of this month Devexpress released the new version of their DXPerience products for .NET (Version 2009.1)
With the release of this components they also released a new version of their coding assisting tool CodeRush and Refactor Pro.
We use CodeRush for a couple of years now in Visual Studio for our C# work. Strange enough this new version somehow managed to trigger the "wow" factor once again.
I will not explain every new feature here, (You will find some resources at the end of this post) but one that is awesome in particular is Code Issues.

The Code Issues feature analyses your source code while your are working in your code. It gives you hints for Unused namespace references, unused methods, undisposed local vars etc, etc.

How does it work?
Hints appear in a bar near the scrollbar of the editor when you hover the mouse over the colored lines (each color is a hint category):
Code Smell  
In this particular example, which seems to be extracted from some farmer application ;-), Coderush hints that a line of code where two strings are concatenated, could be refactored using string.format.

When you hover the code line, it shows you what you could do to improve your code: (or make it smell better)cr1
This is really an impressive cool feature, that will boost the quality of your code.

Delphi Prism
Unfortunately CodeRush only supports C# and VB.NET at this moment. It would be very nice if CodeRush would support Delphi Prism as well.

Beside the fact that CodeRush helps you to boost your productivity with lots of code templates, it also helps you to track code smells and refactor them out of your software which will eventualy increase the quality of it.

You can find more resources on CodeRush here:
The Devexpress website
Mark Miller blog post "What's new in CodeRush & Refactor Pro"
This blogpost by Rory Becker

Thursday, March 12, 2009

New release for Delphi Prism

There is a new release of Delphi Prism available, according this edn article. The Delphi Prism February 2009 release (Build as it is called (Wasn't it already March? ;-) ) contains the following changes.

Wednesday, January 07, 2009

TIOBE language of the year not Delphi

In october Jim Mckeeth reported that Delphi could well be the language of the year in the TIOBE Community language index.
Unfortunately this has not happened despite the efforts of the Delphi community putting "Delphi programming" on webpages.

In january Delphi is fallen slightly one place back to position 10. (Nothing to worry about). Remarkable is that Pascal went up 3 places compared with last year, now holding the 15th position. I predict that Pascal will become the language of the year 2009! ;-)

Language of the year 2008: C

For what it is worth........

What is your prediction?

Tuesday, January 06, 2009

LINQ with Delphi Prism #2 : Deferred Execution

As said in this previous post Delphi Prism supports LINQ all the way so all the LINQ feature just work in Delphi Prism.

Deferred Execution
One of the key features of LINQ is Deferred Execution. That means that a LINQ query does not execute until data is demanded, for except by an iteration through a list. This makes it possible to make a complex query without execution each part of the query seperately.

However, there is one exceptions to the rule, a LINQ query executes immediately when you use a function that must iterate over the list for its result like, for example Sum(), Count(), ToList() etc.

//Example of deferred execution or lazy execution
var Numbers := new List<integer>;
var DoubledList : sequence of integer
= Numbers.Select(n->n*2);
// Query not yet executed!
// Add another number to the list

//At this point query is executed
//Result "2--4"
for i : Integer in DoubledList do begin
Result :
= Result + i.ToString + '--';

//Example of direct execution
var Numbers := new List<integer>;
//Query executed here
var Sum := (Numbers.Select(n->n*2)).Sum();
//Would expect 20, but result is only 6

Monday, January 05, 2009

LINQ with Delphi Prism #1 : Sequences

I have been digging into LINQ this christmas. LINQ is a cool way to query data, whether it is an array, a list or a remote datasource.
LINQ is a new feature of C# 3.0 that comes with Visual Studio 2008, but guess what, Delphi Prism, also supports LINQ all the way.

If you want to play/test LINQ queries syntax you can download and install LinqPad, a free tool to use LINQ querys against a SQL Server database. (You could drop Management Studio for that).

The only disadvantage I found (IMO) on LINQ so far is that quering remote datasources is bound to Microsoft SQL Server database. (Maybe this will be extended in the future)
That involves, the so called "LINQ to SQL" methods, which is, I believe, allready deprecated.

As said before Delphi Prism completely supports LINQ. Starting a 3.5 framework application will give you a reference to System.Linq, the namespace, where LINQ lives.

In this series I will explore LINQ using Delphi Prism:

1. Using LINQ on a sequence
LINQ, in Delphi Prism, works on so called sequences, which is a new type described in the Delphi Prism Wiki as:

Sequences are a special type in the language and can be thought of as a collection of elements, similar to an array.

Declare a sequence like this:

Names : sequence
of String :=
'Mickey', 'Dick', 'Roland', 'Delphi', 'Harry'];

With LINQ it is very easy to query a collection, like this sequence. You can do this in two ways, namely:
1. Using Lambda expressions
2. Using query comprehension syntax (Query Syntax)

With Lambda expressions you can write rather small expressions to query the data, with the query syntax they become more readable (read less magic ;-)).
By the way the compiler (at least in C#) will translate the query syntax into lambda expressions. Both techniques are complementary. (I think the Oxygene compiler also does this....)

Suppose we want to have all the names from our sequence which have more then 4 characters, containing an "a" and sorted in upper case.

//Using Lambda syntax
var FilteredNames := Names
.Where (n
-> (n.Length >= 4)
and n.Contains('a'))
.OrderBy (n
-> n)
.Select (n
-> n.ToUpper());

//Using query comprehension syntax
var FilteredNames := from n in Names
where ((n.Length
>= 4)
and n.Contains('a'))
order by n
select n.ToUpper;

//Note we don't have to declare FilteredNames

Iterate through the filterednames to show them in a messagebox:

for s : string in FilteredNames do begin
FilteredOnes :
= FilteredOnes + s + "--"

'FilteredOnes: ' + FilteredOnes)

Note that the original collection, Names in this case, is still holding all the elements.

Conclusion LINQ is a, in basic, simple way to query collections the SQL way. Delphi Prism supports them complete. Choosing Lambda expression or Query syntax will be mostly a personal preference.

Use an image as your UIBarButtonItem

Using an image as your UIBarButtonItem in your navigationcontroller bar can only be achieved by using a common UIButton as the BarButtonItem...