this.Blog.Find(entry => entry.IsHelpful);
 Saturday, June 14, 2008
Collection Initializers

Scripting languages like Ruby and Groovy recognize the importance of collections like lists and maps, treating them almost like first class objects.  By doing so, they make it really easy to create collections like these and populate them all in one step.

For example, in Ruby here is how this is done:

# create a list
lst = [1, 2, 3, 4, 5]
# create a map
map = { "one" => 1, "two" => 2, "three" => 3 }

Not surprisingly, we see very similar syntax in Groovy...

// create a list
def lst = [1, 2, 3, 4, 5]
// create a map
def map = ["one":1, "two":2, "three":3]

And in case you missed it, one of the changes in C# 3.0 was the ability to initialize collections similar to the way it's done in these scripting languages (though the syntax is not *quite* as clean):

// create a list
var lst = new List<int> { 1, 2, 3, 4, 5 };
// create a map
var map = new Dictionary<string, int> { {"one", 1}, {"two", 2}, {"three", 3} };

IMO, the new collection initializers (along with property initializers) are one of the nicest changes in the new version of the .Net framework.  And since I'm feeling nice, I won't show how this is accomplished in native Java.  :-D


Kick it on DotNetKicks.com
Saturday, June 14, 2008 8:23:10 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  C# | Groovy | Ruby

 Friday, June 13, 2008
Back To Basics

Inspired by a recent Hanselminutes podcast about getting back to basics, along with my experiences at my last client, I've decided to start a series of blog posts on fundamentals and best practices.  Ideally, I'd like to post about once a week on some aspect of programming that isn't necessarily tied to a particular technology or framework.  While these posts may contain code samples in a particular language, I'd like them to be applicable across platforms.

In this first post, I want to talk about the gravitation of junior programmers to books on particular technologies rather than books on fundamentals. 

Let's face it - programming books are nearing end-of-life status.  Don't get me wrong, I love reading programming books (I'm finishing up one right now and have two more in the queue).  But in this age of the internet and how quickly technologies change, coupled with our "gotta have it now" instant gratification society, it's next to impossible to publish a book that is relevant, accurate, timely, and interesting.  My hat is off to those people who can do so successfully.

Despite this fact, programming books are (for now) still quite popular.  It's certainly not from a lack of volume, both in the number of books available and in the length of the individual books.  A former colleague of mine recently bought an ASP.Net book that appeared to have decimated half the pacific northwest and was so heavy it probably could be considered a weapon.  It makes me wonder how a publisher thinks any modern developer can consume 1,500 page books on subjects that, let's be honest, aren't particularly enthralling. 

Now I love the fact that developers are so interested in learning that they continue to buy programming books despite the logic that says they'd be better off googling and reading blogs.  Here's my problem with developers who buy programming books ... the books I see on developers' bookshelves tend to be targeted at particular technologies (e.g. LINQ, WCF, Ajax, etc...) rather than general software engineering practices.  In particular, I'm talking about junior developers who probably need the fundamental books the most.

Here is a starting place for books that I feel form a solid foundation for a professional programmer:

 

code_complete Code Complete
Start here.  If you've already read it, read it again. I've heard it called the definitive guide to practical programming.  I tend to agree.  One of the best programming blogs on the internet belongs to Jeff Atwood, who borrowed the name of his blog (with McConnell's permission) - Coding Horror - from this book.
prag_prog The Pragmatic Programmer: From Journeyman to Master
This book was way ahead of its time.  Hard to believe this book is approaching 10 years old.  I think it's definitely contributed (if not led the way) to the rise of agile methodologies, unit testing, and polyglot programming, as well as the rising popularity of dynamic languages.  You would be well served to check out a number of titles in the pragmatic series.  IMHO, it's the best publisher of technical books these days.
effective_java Effective Java
If you work in a Java shop, this book should be issued to you on your first day. I'd make a strong argument that even C# developers would benefit from reading this book.  The second edition of this book just came out, reflecting the changes found in the 1.5 JDK.  There is also an Effective C# book by Bill Wagner that is also very good.  I've read on his blog that he is updating his book, too, since the first edition came out just before the 2.0 version of the .Net framework was released.
refactoring Refactoring: Improving The Design Of Existing Code

In the overall lifetime of a piece of software, new development (hopefully) constitutes a very short percentage of that time.  Maintenance and enhancements should encompass a much longer period.  Your design is never right the first time.  Agile thinking teaches us that things will change and designs can always be improved.  This book helps you improve those designs, as well as teaching to look for "code smells" - patterns of software that lend themselves to refactoring.  The end result is code that is simpler and easier to maintain.

gof Design Patterns

The seminal book on object-oriented programming.  This is the one that gave birth to the pattern vernacular programmers still use today: factory, facade, strategy, command, visitor, etc...  The examples are in C++ and SmallTalk, so it's usually a little tough for junior level programmers to grok.  I wouldn't jump into this one first, but once you understand the basics of OOP, this book helps you take it to the next level.

j2ee_development_wo_ejb J2EE Development Without EJB

This one is kind of an outlier, since obviously by its title and content, it is definitely aimed at Java/J2EE.  But this book (along with Rod Johnson's previous book) was possibly one of the most influential programming books I've ever read.  It was written at a time when J2EE was at its height, and openly questioned the way 95% of Java apps were being written.  It changed the way I write my applications, bringing alive the concept of "separation of concerns", layering your architecture, and making sure that your components were easily testable.  It gave birth to the concept of inversion of control, as well as showing off a true MVC implementation that facilitated testing outside of a web container.  Enterprise Java development was turned on its side due to Johnson and his Spring Framework.  .Net is just now getting up to speed on these concepts.

I've said it many times, I'd be much more inclined to have a strong developer on my team who has no experience in a particular technology rather than a weak one who has been doing that technology for 5 years.  Once you grasp the fundamentals, you can pick up any technology and be productive much quicker.


Kick it on DotNetKicks.com
Friday, June 13, 2008 8:16:01 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  Books | Programming

 Friday, May 30, 2008
New release of Miado

This new release contains significant changes.  First and foremost, all the implementation classes have had their public scope removed, so you will now have to program exclusively against the interfaces.  I have also moved the IMiadoDao interface to IMiadoRepository in order to encourage composition and not force an inheritance hierarchy.  Combined with that change, I also moved the functionality from SimpleSql into IMiadoRepository, as well as making that interface the point where you access an IDbStatement, making the IMiadoRepository the main worker module of Miado.   Another change is that you need to use the MiadoRepositoryFactory to create an instance of the IMiadoRepository.

Enough with the talk, let's see some code...

public AdddressDao 
{
private static readonly string INSERT_ADDRESS_SQL =
"insert into Address(Address1, Address2, City, State, ZipCode) " +
"values(@Addr1, @Addr2, @City, @State, @ZipCode)";

private static readonly string SELECT_ADDRESS_SQL =
"select AddressId, Address1, Address2, City, " +
"State, ZipCode " +
"from Address ";

private static readonly string SELECT_ADDRESS_BY_ID =
SELECT_ADDRESS_SQL + "where AddressId = @Id ";

private static readonly string SELECT_ADDRESS_BY_ZIP_CODE =
SELECT_ADDRESS_SQL + "where ZipCode = @ZipCode ";

private static readonly string SELECT_COUNT_BY_STATE =
"select count(*) from Address where State = @State ";

// uses MiadoRepositoryFactory.CreateMiadoRepository()
public AddressDao()
: this(MiadoRepositoryFactory.CreateMiadoRepository(
SqlClientFactory.Instance,
ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString)) {}

public AdddressDao(IMiadoRepository repository)
{
this.MiadoRepository = repository;
}

protected IMiadoRepository MiadoRepository
{
get;
set;
}

public void SaveAddress(Address addr)
{
// uses SQL right in IMiadoRepository
this.MiadoRepository
.ExecuteNonQuery(INSERT_ADDRESS_SQL,
addr.Address1,
addr.Address2,
addr.City,
addr.State,
addr.ZipCode)
}

public ICollection<Address> FindAddressesByZipCode(string zipCode)
{
// build IDbStatement and do the mapping in a lambda expression
ICollection<Address> addresses =
this.MiadoRepository
.CreateDbStatement(SELECT_ADDRESS_BY_ZIP_CODE)
.AddParameter("ZipCode", zipCode)
.QueryForResults<Address>(
row => new Address()
{
AddressId = row.GetValue<int>("AddressId"),
Address1 = row.GetValue<string>("Address1"),
Address2 = row.GetValue<string>("Address2"),
City = row.GetValue<string>("City"),
State = row.GetValue<string>("State"),
ZipCode = row.GetValue<string>("ZipCode")
});
return addresses;
}

public Address LoadAddress(int addrId)
{
// uses delegate method to do the mapping
return
this.MiadoRepository
.CreateDbStatement(SELECT_ADDRESS_BY_ID)
.AddParameter("Id", addrId)
.QueryForOne<Address>(CreateAddress);
}

public int FindCountByState(string state)
{
return
this.MiadoRepository
.CreateDbStatement(SELECT_COUNT_BY_STATE)
.AddParameter("State", state)
.QueryForOne<int>(row => row.GetValue<int>(0));
}

private static Address CreateAddress(IResultSetRow row)
{
return
new Address()
{
AddressId = row.GetValue<int>("AddressId"),
Address1 = row.GetValue<string>("Address1"),
Address2 = row.GetValue<string>("Address2"),
City = row.GetValue<string>("City"),
State = row.GetValue<string>("State"),
ZipCode = row.GetValue<string>("ZipCode")
};
}

}

Kick it on DotNetKicks.com
Friday, May 30, 2008 10:57:03 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C# | Miado

 Friday, May 23, 2008
No Fluff Just Stuff recap

This past weekend I attended the No Fluff Just Stuff conference here in Atlanta.  If you're not familiar with NFJS, it's a traveling conference that hits most of the major markets here in the US.  It's held over weekends so as not to disrupt your daily job, and it covers topics in Java and Agility. 

I'd been to one NFJS a few years ago here in Atlanta and thought it was well worth it.  At that time, Bruce Tate was on the circuit. He was preaching (along with many of the other speakers at the time) about the bloat inherit in J2EE applications, and that Java developers should really be focusing their attention on lighter-weight J2EE alternatives such as Spring and Hibernate.  Mind you, this was long before either had become mainstream.  Having been a Rod Johnson disciple after reading his first book (the contents of which would eventually become Spring), I guess it's not surprising I enjoyed the conference so much.  Interestingly enough, Bruce, along with Stu Halloway and Justin Gehtland (who also spoke at that conference), are now big Ruby-On-Rails guys.

Now I've been doing .Net stuff almost exclusively for the last few years, so I had a slight reservation about attending this year's conference, given that I'm not doing Java day-to-day anymore and I wasn't sure how much would be relevant.  But given that I'm an independent consultant who should be up on such things, I thought it would be a good idea to at least re-familiarize myself with the goings on in the Java community. 

I really am technology agnostic, but I do find the language of Java to be extremely noisy, tedious, and verbose anymore, especially coming from C# 3.0.  Do you know how many language-level (not library-level) changes have gone into the JVM since 1.1.7?  Off the top of my head, I can remember:

  • the new for loop (finally in 1.5!)
  • the crappy implementation of generics
  • annotations
  • static imports
  • enums
  • varargs

That's not a whole lot (or really anything significant) for a language that is over 10 years old. 

And in case you are not following it, there is a huge debate in the Java world if/how closures should be implemented in the Java language.  Have you seen the candidates?  Good lord, they make the syntax for anonymous classes look simple!  Put me firmly in the camp of leaving Java the language itself good and well alone and concentrate your efforts on other languages that run on the JVM.

So given the stale nature of the Java language and the rise of my interest in dynamic languages, I figured this would be an excellent chance for me to explore Groovy and Grails.  I attended the sessions by Jeff Brown from G2One on both technologies the first day, and I was hooked right away on both.

Groovy compiles to native Java bytecode, and thus can be used interchangeably with standard Java classes (along with the innumerable number of Java frameworks out there).  Plus, it has strong support for the things I love in C# 3.0 - properties, extension methods, and closures.

Grails is rapid web application framework for Groovy similar to Rails.  It favors convention over configuration and uses a classic MVC architecture that allows for easy testability.  Under the hood, it uses best of breed Java technologies as plumbing infrastructure (e.g. Spring and Hibernate).  Just by creating a new project through scaffolding, it creates a nice project layout structure that provides a beautiful separation of concerns.  It really makes it easy for you to write unit tests (no more excuses!).  Basically, it creates a solid project architecture that would be roughly close to something a strong Java architect would formulate. 

I learned of a term from Scott Hanselman called "The Pit Of Success".  The concept is that you make it easy for developers to do the right thing and perform best practices.  Don't make them have to overcome the language or framework, but rather fall into success by default.  That's exactly what Grails does for you.

I stayed on the Groovy path the second day of the conference, attending sessions on meta-programming using Groovy.  Meta-programming in Groovy is quite powerful, which makes it damn easy to build DSLs.  One of the gems of the language is the simplicity in which you can create XML documents using a DSL in its XML builder.  If you've ever struggled over a unwieldy ant file (or jumped through hoops just to perform a simple "if" statement in the XML file), you really owe it to yourself to check out Gant.

My last day was my Neil Ford day.  I attended all four of Neil's sessions the last day.  The first two were on Agile project management and metrics while the last two on Ruby/JRuby.  Neil is a very entertaining speaker (and Atlanta resident the 10 days a year when he is not traveling).  Again, to reference Scott Hanselman, the joke is that Scott got hired on by Microsoft and now gets paid "to be Scott Hanselman".  I think Neil is exactly in the same camp.  He gets paid "to be Neil Ford".  Where do I get the gig "to be Chris Rauber"?

One last comment to make on NFJS.  One thing I like about Java conferences in general and No Fluff Just Stuff in particular is that they don't seem to favor "technology" over "methodology".  NFJS has a strong Agile underpinning, and offers a number of session on practicing Agile methodologies.  Where it did offer technology sessions, it seemed that it targeted as how a particular technology implements Agile.  For example, I mentioned in a previous post how Sun announced JavaFX at JavaOne this year (again).  This was a mere two weeks before the NFJS conference.  Yet there was hardly any mention of JavaFX at NFJS.  If this were a .Net conference, nearly half the sessions would be about this new technology.  Now, you could make the argument that JavaFX isn't really all that appealing to everyday Java developers, and truth to be told, you wouldn't get much argument from me.  But I thought it was very interesting nonetheless.

The bottom line - if NJFS comes to your town, I would highly recommend checking it out.  They really seem interested in providing top-notch speakers and giving you your money's worth in a conference. 

Now ... anybody looking to hire a Groovy consultant??? :-D


Kick it on DotNetKicks.com
Friday, May 23, 2008 12:08:33 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  Conferences | Java

 Wednesday, May 21, 2008
Using LINQ to generate a random confirmation number

Igor Ostrovsky recently published a great blog post about 7 tricks for using LINQ to simplify your programs.  Posts like this really make me re-evaluate how I am writing my code in C# 3.0.  For example, I had written a piece of code for my current project that generates a random confirmation number for a reservation system.  After reading Igor's post, I built off one of his examples and refactored my code to use LINQ to build my confirmation number.  I must admit, the refactored code is much more elegant:

private static readonly char[] AVAILABLE_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789".ToCharArray();

private static string GenerateConfirmationNumber(int length)
{
int lastIndex = AVAILABLE_CHARS.length - 1;
Random rand = new Random();
var confNbr =
Enumerable.Repeat<int>(0, length) // loop N times
.Select<int, int>(loopNbr => rand.Next(0, lastIndex)) // get a random index
.Select<int, char>(index => AVAILABLE_CHARS[index]) // pull a char
.ToArray(); // project the results to a char[]
return new String(confNbr);
}

I think it's important to remember that LINQ is much, much more than just LINQ-to-SQL (which is what most people immediately think of when you refer to LINQ).  In fact, none of the examples in Igor's post have anything to do with SQL.  Take a look at his post (and other LINQ examples online) and hopefully it will give you ideas on how to code using more of a dynamic language type syntax.


Kick it on DotNetKicks.com
Wednesday, May 21, 2008 9:42:57 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C# | Linq

 Saturday, May 17, 2008
String extension methods in ASP.Net Ajax

In an earlier post, I showed you how you could add a trim() method to the String class in Javascript.  Well, as I found out late last week, if you are using the ASP.Net Ajax framework, they have already done this work for you (as well as a few more methods).  Here are the extension methods for the String class that are provided to you:

Method Description
endsWith() Test to see if the string ends with a particular string
format() Similar to .Net's String.Format(), it replaces a set of tokens with some replacement values
localeFormat() Similar to format(), but it uses the current culture to format dates and numbers
startsWith() Test to see if the string begins with a particular string
trim() Strips both leading and trailing whitespace from the string
trimEnd() Strips whitespace from the end of the string
trimStart() Strips leading whitespace from the string

One other nice thing it provides is a StringBuilder class similar to .Net's System.Text.StringBuilder class.  This is especially nice when creating big chunks of HTML to throw in an innerHTML property.

<input type="button" name="btn1" value="Click Me!" onclick="javascript:changeText();"><br />
<span id="myText"></span>
<script type="text/javascript">

function changeText() {
var sb = new Sys.StringBuilder(); // thank you, ASP.Net Ajax!
sb.append('<h1>How cool is this?</h1>');
sb.append('<br />');
sb.append('You just clicked my button. ');
sb.append('Now we will change some text');

$get('myText').innerHTML = sb.toString();
}

</script>

Kick it on DotNetKicks.com
Saturday, May 17, 2008 10:32:30 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  Ajax | ASP.Net | Javascript