A Funny Java Flavoured Look at the World

Monday, June 19, 2006

10 tips on writing reusable code

I have been trying to increase code reuse in the projects I have been doing recently. In my first few years of coding I hardly ever got to reuse any of my code because it was always too coupled together and dependant upon other parts of the code.

So recently I have been trying to write code which I can reuse. It has been interesting that since I have been doing this I have noticed that my library of code is starting to grow. I have started to create more Static Helper classes with useful methods in. I have also been removing the business logic away from any Struts actions or framework work.

To do this I have tried to do a number of things to help this and these are the sort of rules and things I do (in no order) to help me try and achieve this. They are a number of rules and tips I have picked up but can't remember where from

1. Keep the code DRY. Dry means Don't repeat yourself. This is one of the main changes I have tried to bring in. Always try to eradicate duplication and if you find any then move remove the duplication to a relevant place. Sometimes this has lead me to create Static Helper classes or sometimes move it to the class it makes most sense to have it.

2. Make a class/method do just one thing. This is along the lines of the advice of giving the class only one reason to change. This often means creating methods that other methods use but this helps to make the methods/classes simple and less coupled.

3. Write unit tests for your classes AND make it easy to test classes. Writing code that is easy to test is decoupled. If you write code and are thinking about writing a unit test for it then you tend to split up the code into smaller testable chunks.

4. Remove the business logic or main code away from any framework code. Following the rules above will help this. An example I have seen is code that is inside Struts Actions classes, this code is practically impossible to reuse because of all the Struts dependencies that it now linked with.

5. Try to think more abstractly and use Interfaces and Abstract classes. Try to hide dependencies of code behind a more Generic interface/abstract class. The benefit this gives the code is it creates a flexible point in the code where you can then hide future changes behind.

6. Code for extension. Write code that can easily be extended in the future. This is particularly true with the above point. If you write code that uses interfaces then you can extend that interface at a later point.

7. Don't write code that isn't needed. Do the simplest thing possible. Don't waste your time adding methods and classes that might be used in the future. Keep the code simple and focused on what you are trying to deliver. I think I read/heard Josh Bloch say once that "if in doubt, leave it out". Basically who wants to write code that no one (including yourself) is going to use again.

8. Try to reduce coupling. When writing code think about the links and coupling the code is creating, does it need to be linked to those other classes.

9. Be more Modular - make your code more modular, think modular, be modular.

10. Write code like your code is an External API. Imagine the code you are writing is a self contained component.

It wasn't going to be ten until I got to 8 and then thought no one writes 8 tips, lets add two more on. It isn't really a list but it's sort of aims and mental notes I try tell myself when writing code. They are more small bits of code I have written recently that has helped. I would like to hear people's comments and especially their tips on writing reusable code

43 Comments:

  • Maybe it's contained in your list implicitly, but I would state it separately:

    Stick on (useful) coding conventions!

    By Anonymous Anonymous, at Mon Jun 19, 10:25:00 am 2006  

  • What's the publish license of this post?

    By Anonymous Anonymous, at Mon Jun 19, 03:02:00 pm 2006  

  • So let me get this straight... are you trying to do Rails in Java?

    By Anonymous Anonymous, at Mon Jun 19, 05:01:00 pm 2006  

  • This applies to C# too ;-)

    By Anonymous Anonymous, at Tue Jun 20, 07:31:00 am 2006  

  • This comes with experience... often, junior programmers have trouble coding efficiently, resulting in slow, ugly, bloated code.

    By Anonymous Anonymous, at Tue Jun 20, 03:14:00 pm 2006  

  • Hey, just letting you know that your blog needs some more styling to it instead of assuming the visitor is using a white background and black text. For me, I'm using a white-on-black theme so all of the text in your blog posts are white and the background of the page itsself is the black I have my theme set to. I have to hit Ctrl+A to read anything.

    By Anonymous Anonymous, at Tue Jun 20, 03:28:00 pm 2006  

  • Sounds like someone just got done reading The Pragmatic Programmer :)

    By Anonymous Anonymous, at Tue Jun 20, 03:31:00 pm 2006  

  • We have got the pragmatic programmer in the office but someone else is reading it.

    Most of these steps are from Josh Bloch interviews/books and Robert C Martin (uncle bob) and his articles here

    www.objectmentor.com/

    Also articles on the pragmatic programmer website are excellent.

    I have tried to take the best bits from all of those sources and give them a quick summary.

    As for the copyright, oh dunno give my blog a quote would be nice.

    By Blogger The Hosk, at Tue Jun 20, 03:39:00 pm 2006  

  • Larry Wall said “The three chief virtues of a programmer are: Laziness, Impatience and Hubris”. Code resuability is one of the reasons why laziness is on this list.

    By Anonymous Anonymous, at Tue Jun 20, 05:26:00 pm 2006  

  • Thanks for ignoring IE users. Too bad I can just turn javascript off. Do you really think that would deter people from using their browser of choice? Don't tell your users what to choose. This is their choice.

    By Anonymous Anonymous, at Tue Jun 20, 05:28:00 pm 2006  

  • I'm not sure why I am ignoring IE users, I use IE and I can see the blog fine.

    Why is this blog ignoring IE users, can someone have mercy and point out the obvious to me

    By Blogger The Hosk, at Tue Jun 20, 05:30:00 pm 2006  

  • Some very useful tips but I would add one more:
    Make comments useful & readable for future reference. If, when writing even a 1,000 line class, you can't remember what exactly it does there is going to be no hope of re-using it.
    This is elementary stuff but is still important.

    By Anonymous Anonymous, at Tue Jun 20, 05:31:00 pm 2006  

  • Can you elaborate more on point 2? I can understand making a function or method perform a single action, but classes need to perform several related actions. For example, a BookmarkManager class can perform several actions related to bookmarking operations, like adding a bookmark, removing one, or updating the bookmark list, etc. I am not sure I agree Classes should generally perform a single function. I'd use a function for that instead. Classes are objects with state (data attributes) and behavior (methods). So naturally, you are going to want to create a class that performs several related operations. If the problem you are trying to solve does not require objects with related state and behavior, then stick to functions. I won't be surprised if I'm misinterpreting that point, though. In the future, I'd also suggest you provide examples for each point you listed. For example, I didn't understand what you meant by static helper classes, but I'm sure if I saw code that demonstrated it, I'd recognize it. Overall, I enjoyed your insights.

    By Blogger Unknown, at Tue Jun 20, 06:14:00 pm 2006  

  • One of the things I do to design functions that perform only a single action is to limit the number of arguments the function can accept. The perfect function accepts zero or one argument. Anything more than 3 arguments is an indicator that I made a bad design decision somewhere. This is also one of my criteria for judging good APIs.

    By Blogger Unknown, at Tue Jun 20, 06:30:00 pm 2006  

  • Mystilleef, he is saying that a class, such as BookmarkManager, should ONLY be responsible for managing bookmarks. So it should add, remove, and modify bookmarks, but not authenticate users. Methods, in the same fashion, should do as little as possible. AddBookmark should simply add a bookmark. Don't use add bookmark to modify bookmarks too.

    By Anonymous Anonymous, at Tue Jun 20, 06:56:00 pm 2006  

  • Mystilleef,

    I believe what he is saying is that classes should perform one job. In your example, the class manages bookmarks. It doesn't, for example, manage the cache and perform client-side validation on the side.

    -- Spiff

    By Anonymous Anonymous, at Tue Jun 20, 07:05:00 pm 2006  

  • Mystilleef,

    Functions with multiple parameters can be far more modular than functions with no parameters. What I like to do is start with a function and find all the variables that change within the body of the function. I make those parameters. After that I split the function into overloaded members and reduce the number of parameters on each overload using default values.

    So I tend to disagree that more parameters denote a less modular design.

    By Anonymous Anonymous, at Tue Jun 20, 10:09:00 pm 2006  

  • I'll agree with Sam here.
    However, really what you want is a way of supplying defaults like in C++, or the signature override like in C#

    public void foo(int a, int b, int c):foo(int a, 2, 3)

    Which is really nice.

    Still prefer Java overall. (Hate C#'s delegates instead of listeners)

    By Anonymous Anonymous, at Tue Jun 20, 11:55:00 pm 2006  

  • too much modularity can turn into bloat as well, not just as source code, but also in performance. programming is a balance. i dont always blame junior programmers for writing poor code. its also a matter of that they don't feel the confidence to make larger design decisions, when they are building off a lot of pre-existing code written by many other developers with their own design views.

    - Hans (www.antipop.co.uk)

    By Anonymous Anonymous, at Wed Jun 21, 12:13:00 am 2006  

  • I'm not so sure about the bit about "static helper classes". In my experience, the existence of static helper classes reduces reusability, since you need to import both the static helper class as well as the class(es) it operates on.

    Allow me to elaborate a bit - if a static method accepts no arguments, then it's probably not doing anything very useful (or it's performing operations on static/global data... and I hope I don't need to go into why that's a bad thing). Instead, most static "helper" methods accept at least one argument - almost always an object (as opposed to native) type. Invariably, I see that the static helper method performs an operation on the data of the object (or objects) they were passed as arguments. When this is the case, it almost always ends up making more sense to just move the "static helper" into the object on which it operates... this actually increases reuse, since importing the class type itself gets you the methods on the class as well.

    I would guess the most common use of static helper methods I see are "converters" (convert a String to an object type, convert one object into another, etc.)... which invariably make more sense as constructors on the target object type.

    Another unfortunate use I've seen static helper classes put to is to act as "null pointer guards"; in other words, they accept, say, a String object and return something like "(s == null ) ? null : s.substring( x, y )". This is unfortunate because the null pointer exception that would be thrown without the guard in this case is a symptom of an actual problem, rather than a problem in and of itself... and "papering over" it this way actually masks the underlying problem (sometimes long enough to create an invalid sale, for example).

    Like I said, I'm immediately skeptical when I hear about static methods used for any purpose at all (they have legitimate uses, like Math.cos(), for example, but those are few and far between) - I guess I'd have to see some examples of cases where moving a method out of a class instance into a static holder actually enhances reusability.

    By Anonymous Anonymous, at Wed Jun 21, 02:18:00 pm 2006  

  • I'm not sure about static helper classes (classes with a private constructor and just static methods)

    but I find sometimes it means you can put a popular function in one place instead of in one class. Usually I might consider it I find I need to use the same function in a number of classes. Do I want the other classes being dependant on that class.

    I have static helper classes for FileUtils, CollectionHelper and a general Utility class. They contain methods that don't really need to sit in a class because they are usually finding something, transforming something etc.

    By Blogger The Hosk, at Wed Jun 21, 03:15:00 pm 2006  

  • Nice list. Writing generic code will make it reusable. I think #2 sounds excessive though I think that comes from the Java world of having to write a class for everything. #3 is very true. #4 is essentially what MVC says. The rest is almost fluff.

    By Anonymous Anonymous, at Wed Jun 21, 07:51:00 pm 2006  

  • Nice article. Thanks for the DRY - I just wrote it to my notebook to the list of my programming rules.

    BTW: I'm the one who digged your article :)

    By Anonymous Anonymous, at Thu Jun 22, 07:29:00 pm 2006  

  • Hopefully this is constructive criticism and I don't sound like an ass, that is not my intention...

    I thought the list was redundant. What I got out of it was:

    1. Modularize your code.
    2. Don't couple.

    These are great. For those who enjoy what they do and care about style (as geeky as it may be) should learn these ideas on their own.

    The #1 conflict I see with this list is that they aren't as much tips for writing reusable code, as much as they are saying, "make your code reusable".

    One last note, if you want to learn a beautiful word, learn "terse". It means "effectively concise" and, to me, is better then "DRY". But, one thing school teaches you is that acronyms are a useful and effective study aid.

    It wasn't a bad read, just a little misleading.

    By Anonymous Anonymous, at Fri Jun 23, 08:40:00 pm 2006  

  • Regarding the code smell of static helper methods: in Java, that's the choice. We can't go extending existing classes willy-nilly like in a more dynamic language.

    In some ways this is good, in some ways this is bad.

    We can compose, which is okay, but I'd rather just use a String than a MyString. We can duplicate, which is bad for the obvious reasons. We can use J. Random bytecode generation method, which is... a PITA.

    By Anonymous Anonymous, at Tue Jul 11, 12:39:00 am 2006  

  • 1. Keep the code DRY. You mean factor it properly.

    2. Make a class/method do just one thing. You mean factor it properly.

    3. Write unit tests for your classes AND make it easy to test classes. You mean factor it properly and understand your own code.

    4. Remove the business logic or main code away from any framework code. You mean design it properly.

    5. Try to think more abstractly and use Interfaces and Abstract classes. You mean design it properly using Change Cases to ensure architecture is "changeable".

    6. Code for extension. You mean use Change Cases to ensure architecture is "changeable"

    7. Don't write code that isn't needed. You mean ensure you use requirement management.

    8. Try to reduce coupling.

    9. Be more Modular - make your code more modular, think modular, be modular. You mean factor it properly

    10. Write code like your code is an External API. You mean factor it properly.

    I love developers. They fob of software engineering and software architecture, talk of agile methods like they stand apart from the mainstream and then re-invent software engineering 101 in their blogs.

    By Anonymous Anonymous, at Fri Sept 08, 03:57:00 am 2006  

  • I'm not re-inventing anything and I think it fairly obvious that I didn't even invent most of these points.

    All I am saying is that when coding I try and make sure my code sticks to these points.

    By Blogger The Hosk, at Fri Sept 08, 08:55:00 am 2006  

  • wow, those ten tips and the newly added 11th tip(adding Comments) are very nice but I have small doubt, when we think in the reusable direction, if a function is going to read some files and some dependent inputs are there where we have to keep them, if we think modularity way we can't pass them as parameters? So does we need to use any properties file or properties class?

    By Blogger J.Naveen, at Sun Sept 07, 08:28:00 am 2008  

  • It was not long cheap wow goldbefore some one knocked at wow gold for salethe house-door and called, open the door, dear children, your mother is here, and wow gold cheap has brought something back with her for each of you. But the little cheapest wow goldkids knew that it was the wolf, by the rough voice. We will fastgg not open the door, cried they, you are not our mother. She has a soft, pleasant voice, but your voice is rough, you are the wolf.

    By Anonymous Anonymous, at Mon Mar 09, 02:29:00 am 2009  

  • By Anonymous Anonymous, at Thu Mar 26, 02:15:00 am 2009  

  • By Anonymous Anonymous, at Thu Mar 26, 02:18:00 am 2009  

  • nice post!

    By Anonymous WoW Gold Guides, at Wed May 06, 11:10:00 pm 2009  

  • By Anonymous Anonymous, at Wed May 13, 02:53:00 am 2009  

  • For the polo shirts, many people loveralphlaurenpoloshirtscheappolos but hate it. This brand is favorite, products like his style; the same is hard not to develop the Lacoste polo shirts brand has been cheap lacoste polos the Asian market. There are stores to buy wholesale polo shirts, However, ralph lauren polo shirts is too many fakes. It will be out of shape cheap ralph lauren polos.

    By Anonymous Anonymous, at Thu Jun 04, 03:50:00 am 2009  

  • In preparation for the purchase of a tennis racquetbefore, we must consider your financial ability to bear; On this basis, a further comparison, as far as possible, choose your tennis racket. Now a lot of cheap tennis racquet and more mixed materials, the proportion of mixed-use to control the stiffness of the tennis racquet discount and the shock-absorbing capacity, the more rigid cheap tennis racket, the swing more powerful force; but the relative resilience of the shock-absorbing capacity and discount tennis racket performance of talks on the easier it is for the wrist and elbow injury.
    head junior tennis racket
    wilson tennis racquet
    wilson tennis racket
    head tennis racket
    babolat tennis racket
    Womens Handbags
    Cheap Purses
    Designer Handbags

    By Anonymous Anonymous, at Thu Jun 11, 04:45:00 am 2009  

  • Burberry polo shirt the steady, solid, so many young girls also love it. Speaking of people of a ralph lauren polo, think it a sign of nobility elegant waving in the horse club.spyder jacket in the cold in your winter activities can be easily.columbia jacket it is expensive, but here you do not need to consider the price of it. the north face jacket one of my favorite money, I do not know how many in this world of its fans.
    ed hardy clothing
    ed hardy clothes
    ed hardy shirts
    ed hardy t-shirts
    ed hardy sunglasses
    ed hardy mens
    ed hardy womens
    Wholesale Handbags
    Cheap Handbags

    By Anonymous Anonymous, at Thu Jun 11, 04:48:00 am 2009  

  • Vietnam lies on the eastern seaboard of th Indochinese peninsula. It borders Chine in the north. Laos and Cambodia in the west, and looks out on the East Sea (Pacific サイト制作) in the east and south.

    By Blogger Unknown, at Sat Jun 20, 07:46:00 am 2009  

  • By Anonymous Anonymous, at Thu Aug 13, 05:18:00 am 2009  

  • By Anonymous Anonymous, at Mon Aug 17, 05:02:00 pm 2009  

  • thanks

    By Anonymous replica de relojes, at Tue Sept 29, 02:52:00 am 2009  

  • Aftersex toysseries,asex shopof,boardadult toysdetermined,companyadult shoppast,Yahoo'ssexy lingerieweek,meetingsvibratorperson,decisionadult productsbelow,anystrap onshare,overadultshopadvantage,coulddildooffer,theMalaysia sex toysregulators,tryingSingapore sex toysdigging,massivelysex toy$31,thatCondomsaid,takeoverParadise sex toys shopbattle,woodenParadise Sex Toys Adult Shop Singapore Malaysiastand,word delivery,stand,wordParadise Sex Toys Adult Shop Singapore Malaysiadelivery,committed toParadise Sex Toys Adult Shop Singapore Malaysiacertain,schoolSex Toys Shop Singapore Malaysiaproducts,BuyParadise Sex Toys Adult Shop Singapore MalaysiaNow

    By Anonymous Anonymous, at Sun Oct 04, 09:41:00 pm 2009  

  • What Are Replica Watches? Replica watches are among the hottest fashion accessories nowadays. They are popular among fashion enthusiasts because it helps them in reflecting their fashion sense on a very low price. Replicas watches are not fake so don't misunderstand them. Designer Replicas Watches are made of best quality materials that are used in making of most designer watches. Stainless steel, quartz, and the mechanism used in making of replicas watch are similar to the designer brands. So, buying replicas watches doesn't mean that you are compromising with quality. Replicas watches have nothing to spend on their marketing, advertising and endorsement. The only cost involved is in their making. The manufacturers sell them with a little margin. This is the secret behind the cheap prices of replicas watches. Modern fashion trends are even encouraging use of watch replicas. Nowadays people don't just want to wear one replicas watch.

    By Anonymous Anonymous, at Thu Nov 19, 07:38:00 am 2009  

  • hmmm what a nice tips it is!! thanks for this tips .


    http://chutti.pk

    By Blogger Unknown, at Sat Mar 26, 06:26:00 am 2011  

Post a Comment

<< Home