 Monday, July 07, 2008
 Sunday, June 22, 2008
Enforce non-instantiability on static classes
Every project ends up with one or even possibly many static helper classes. If you program in Java, I'm willing to bet the house your project has a StringUtil class lurking around somewhere. These classes are easily abused, but can serve a valid purpose, such as a factory class responsible for creating instances. If these classes contain only static methods (as they usually do), there is never any reason for them to to be instantiated. However, in both Java and C#, it's easy to forget that if you do not explicitly declare a constructor, the compiler will generate a no-arg constructor by default. The consequence is that the following code is valid: StringUtil util = new StringUtil();
You've just allocated memory unnecessarily. Plus, the garbage collector will now incur extra overhead since it will have to reclaim this memory even though it was never actually used. All of the methods are static, so there is no reason to instantiate an individual object from this class.
To avoid instantiations, make sure you declare a private no-arg constructor. This will cause the compiler to throw an error any time the class is attempted to be instantiated. public class StringUtil
{
// constructor marked private since all methods are static
private StringUtil() {}
// bunch of static methods not shown
}
A side note - If you are using C# 3.0, I recommend using extension methods to enhance the behavior of existing classes rather than creating a something like a dedicated StringUtil class. First of all, any class declaring extension methods has to be marked as static and cannot be instantiated. And more importantly, it provides a much cleaner implementation to add those helper methods directly on the affected class. The added bonus is that Visual Studio is smart enough to provide Intellisense for extension methods on targeted classes.
Sunday, June 22, 2008 9:35:25 PM (Eastern Standard Time, UTC-05:00) Back To Basics | C# | Java | Programming
 Saturday, June 21, 2008
Macs to Java developers: You Want Me
At the next Java conference you're at, pay close attention to how many of the speakers are using Apple laptops. Here's a wild-ass guess - all of them. Well, maybe you'll find the one strange dude who didn't get the memo, but I'm not sure that guy is even allowed in the speakers' lounge. Now, I sort of get it. Apple makes beautiful machines. The hardware is top-notch, the UI is slick, it's UNIX based, and, probably most importantly to most Java developers, it's *not* Windows. Here's the odd part. In case you didn't know it already, OS X uses it's own JVM instead of using one provided by Sun. And Apple is notorious for lagging behind Sun with releasing updated versions of the JVM. They only recently released a 1.6 version of their JVM a month or so ago, but only with support for 64-bit Intel-based hardware (i.e. machines bought within the last 2 years). If Microsoft tried to pull off stuff like this, they would get absolutely killed in the press and blogosphere. None of this has seemed to slow down the spread of Java developers to the Mac. Is it clever advertising? The eye candy? A status symbol? The fact that it's not Windows? I think it's kind of like the whipped guy in college who was dating the super hot girl that always cheated on him. He knew it, she didn't exactly hide it, but he could never bring himself to break up with her because she was just too hot. His options were to either put up with her cheating, enjoy his turn at bat every now and then, and walk around campus with her on his arm; or go back to the minors and date somebody more in his own league. Steve Jobs famously said, "Java's not worth building in. Nobody uses Java anymore. It's this big heavyweight ball and chain." It is easily apparent to me that Apple doesn't view Java as a first class citizen on its platform. Are other Java developers blind to this fact? Do they hold out hope that things will change? Are they willing to put up with it for other reasons? As for me, I'm a happy Vista customer. :-P
Saturday, June 21, 2008 10:02:13 PM (Eastern Standard Time, UTC-05:00) Apple | Java
 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. 
Saturday, June 14, 2008 8:23:10 PM (Eastern Standard Time, UTC-05:00) 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
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.
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
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: 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.
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 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.
Friday, June 13, 2008 8:16:01 PM (Eastern Standard Time, UTC-05:00) 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") }; } }
Friday, May 30, 2008 10:57:03 PM (Eastern Standard Time, UTC-05:00) .Net | C# | Miado
|

Subscribe to this feed
 Email Me
 Follow Me On Twitter
| | Sun | Mon | Tue | Wed | Thu | Fri | Sat |
|---|
| 29 | 30 | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 10 | 11 | 12 | | 13 | 14 | 15 | 16 | 17 | 18 | 19 | | 20 | 21 | 22 | 23 | 24 | 25 | 26 | | 27 | 28 | 29 | 30 | 31 | 1 | 2 | | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Search
Navigation
Tag Cloud
Archive
Blogroll
|