Thursday, March 19, 2009

Writing Methods? Less is More!!

This is a lesson I learned as a young aspiring programmer. I was in my early 20s and just about to complete the 200th line of code in a single method when it dawned on me, I sure hope nothing goes wrong with this method. We’ve all seen it and we’ve all done at some stage in our development life. The goal of my nice little blog is to bring visibility to the problem and give you some guidelines for writing methods, which ultimately will lead to reusable code, easier debugging and better code management.

Try to limit your methods to around 35 lines, what you really want, is to be able to see the entire method on the screen. Limit how far out you go horizontally to achieve this same goal. You want to be able to look at the entire method without scrolling. I will guarantee that if you need more that 35 lines of code in a single method you have code that can (maybe not now) be reused. Make methods to copy properties, use libraries that will copy your bean properties from a value object to another object (jakarta has a nice library to do this). Using this best practice will help you start thinking about code reuse and will help the next guy/gal that has to debug your misbehaving method get a good understanding of what’s going on faster.

Till next time,

Chris

No comments:

Post a Comment