Click here to monitor SSC

Tony Davis is an Editor with Red Gate Software, based in Cambridge (UK), specializing in databases, and especially SQL Server. He edits articles and writes editorials for both the Simple-talk.com and SQLServerCentral.com websites and newsletters, with a combined audience of over 1.5 million subscribers. You can sample his short-form writing at either his Simple-Talk.com blog or his SQLServerCentral.com author page. As the editor behind most of the SQL Server books published by Red Gate, he spends much of his time helping others express what they know about SQL Server. He is also the lead author of the book, SQL Server Transaction Log Management. In his spare time, he enjoys running, football, contemporary fiction and real ale.

What’s the use of code reuse?

Published 6 June 2013 4:11 pm

All great developers write reusable code, don’t they? Well, maybe, but as with all statements regarding what “great” developers do or don’t do, it’s probably an over-simplification.

A novice programmer, in particular, will encounter in the literature a general assumption of the importance of code reusability. They spend time worrying about DRY (don’t repeat yourself), moving logic into specific “helper” modules that they can then reuse, agonizing about the minutiae of the class structure, inheritance and interface design that will promote easy reuse. Unfortunately, writing code specifically for reuse often leads to complicated object hierarchies and inheritance models that are anything but reusable. If, instead, one strives to write simple code units that are highly maintainable and perform a single function, in a concise, isolated fashion then the potential for reuse simply “drops out” as a natural by-product.

Programmers, of course, care about these principles, about encapsulation and clean interfaces that don’t expose inner workings and allow easy pluggability. This is great when it helps with the maintenance and development of code but how often, in practice, do we actually reuse our code?

Most DBAs and database developers are familiar with the practical reasons for the limited opportunities to reuse database code and its potential downsides. However, surely elsewhere in our code base, reuse happens often. After all, we can all name examples, such as date/time handling modules, which if we write with enough care we can plug in to many places.

I spoke to a developer just yesterday who looked me in the eye and told me that in 30+ years as a developer (a successful one, I’d add), he’d never once reused his own code. As I sat blinking in disbelief, he explained that, of course, he always thought he would reuse it. He’d often agonized over its design, certain that he was creating code of great significance that he and other generations would reuse, with grateful tears misting their eyes. In fact, it never happened.

He had in his head, most of the algorithms he needed and would simply write the code from scratch each time, refining the algorithms and tailoring the code to meet the specific requirements. It was, he said, simply quicker to do that than dig out the old code, check it, correct the mistakes, and adapt it.

Is this a common experience, or just a strange anomaly? Viewed in a certain light, building code with a focus on reusability seems to hark to a past age where people built cars and music systems with the idea that someone else could and would replace and reuse the parts. Technology advances so rapidly that the next time you need the “same” code, it’s likely a new technique, or a whole new language, has emerged in the meantime, better equipped to tackle the task. Maybe we should be less fearful of the idea that we could write code well suited to the system requirements, but with little regard for reuse potential, and then rewrite a better version from scratch the next time.

16 Responses to “What’s the use of code reuse?”

  1. DanielRothig says:

    Hi Tony,

    I can’t say that I agree. In my daily work, I reuse code routinely, and often, when I can’t find appropriate reusable code, I find some fragment in the code base I can encapsulate, and then reuse.

    The thing that does bite me is when I try to reuse data structures and POCOs, because they tend to not be quite in the right namespace, have quite the right methods on them, etc., and adding what I need to them makes them diffuse and cumbersome. Writing very small data structures and then using them for composition helps a little, but not much.

    Algorithms are a different beast. When I do have to write a new one from scratch (the exception rather than the rule), I find myself reusing it within a couple of months.

    While I rewrite my algorithms several times over their life span (because who doesn’t get become frustrated with their past selves for their lack of experience?), but because there’s just one version of them in the code base at any point, these improvements will always be consistent and universal.

    Moreover, I find that designing my code for re-use makes it more modular and encapsulated, and therefore more readable, scannable, and testable (which to me are the main benefits of DRY).

    I’m a fairly pragmatic developer – I don’t nearly write as many tests as many would advocate, for example – but re-usability is at the top of my list, mostly because for me, re-usability guarantees usability.

  2. Celko says:

    Back in the 1980′s we did the research at AIRMICS on code reuse. The magic numbers seem to be that it was worth it when you got five opportunities, but no savings for less than that. This was in the context of copy books for COBOL, so the DATA DIVISION (the Cobol version of DDL, sort of) got re-used a lot, but not so much for the PROCEDURAL DIVISION.

  3. Robert Young says:

    A number of issues here.

    1 – code which is sufficiently general (i.e. reusable) ends up in libraries (those date/time thingees, fur instance), while application specific code doesn’t and can’t; if code existed to suffice for a new application, then the application wouldn’t be new, would it? there are thousands, if not tens of thousands, of general ledger implementations extant; all of which represent about 4 or so distinct types (manufacturing, distribution, retail, financial services, …), but those thousands were each built under the delusion that each was the one true right way to write a GL, now there’s an opportunity for reuse, an entire application
    2 – to the extent that, as database centric folks, we cleave to the notion that procedural logic is just mucked up DRI (in all of its glorious manifestations), then the most reusable code are high NF schemas, which might not be directly reused, but the metadata (or meta-analysis) will be
    3 – most coders write to a framework and aren’t writing C++ or java or F#, in any case; if they did write OO as described by Meyer or Holub, then the software widget would make sense, but as things really are, real code is tethered to frameworks and runs as data object driven by action object (see Joe’s comment), or COBOL in camel case
    4 – hardware plays a role in this passion play; previously, most coders (and even many database folks, alas) worshiped at the feet of sequential processing, eschewing the benefits of random processing offered up by DASD. with quality SSD on offer, there’s little reason to continue with application code looping over sequential structures. one of the reasons there’s billions and billions of lines of COBOL three tape sort/merge out there (and more each day) is that disk was (and still is) treated as just faster tape. time to move on, and resist the urge to reuse all that code
    5 – I guess Joe hasn’t spent too much time recently rubbing shoulders in Fortune X00 IT; DECLGEN still rules, where COPYBOOK become table and PROCEDURE DIVISION code continues to run; oft times transliterated to java (and the rarer C#) – it’s the nature of COBOL for the COPYBOOK to be Chang to PROCEDURE Eng
    6 – more code, esp. web facing, is so embedded in specific framework, that database migration is so much more feasible than code migration or reuse outside the base framework. I forget who but Somebody Famous noted, “if you’re using a framework, then you’re using a language that’s too low level”; as we move up the ladder (much like Maslow), application code becomes ever more task specific, and thus not reusable, by definition

  4. Tom Fischer says:

    Code reuse means many things to many people. For example, I rarely see developers grab enterprise components more than five years old due to technical decrepitude. But, as already noted in the comments, sure watch plenty swipe algorithms and business rules from the “old” code.

    As a potentially twisted corollary to Tony’s point, I have observed something interesting about code reuse. Over the years I’ve seen many developers carrying a cache of code and components from prior gigs. By and large their hoard rarely proved valuable. In many cases it required debugging, fixing and excuses for rewriting (by other team members)?!

  5. MattieNH says:

    As a COBOL programmer, I reuse my code my lot. .net programmers probably wouldn’t consider a lot of it reuse, because the code is written as stand-alone programs, albeit with a lot of called subroutines. But by copying the structure, and adjusting the business rule logic, you come up with a good set of templates for most programming issues. You know, what are referred to now as design patterns.

    Whenever I have to write a new Cobol application, I’m reminded of the story of the sculptor and the art patron. The patron was just amazed at the sculptor’s skill, and asked her how she would go about creating a statue of something, such as an elephant. She responded “It’s easy. You take a piece of granite shaped like an elephant and chip away everything that doesn’t look like an elephant”. When asked to develop a new program, you find the program that’s shaped most like the program you need to create. It’s all in the selection of the granite.

    I suspect there isn’t more code reuse in new languages because in order to reuse code, you have to know what the original code does. And that requires documentation, which all of the programmers I know just love to write.

  6. mdullnig says:

    Since I started out in 3rd generation coding (C), it is ingrained in me to write modularized code. I always strive to write general subs or functions. Currently, I maintain an Access (VBA) front-end system that was developed by someone who copied large amounts of the same code into each form/report/module developed. So, when I have to modify one line of code, I have to change it in many objects. When I can, I convert the duplicate code to a sub/function. For example, writing the output to an Excel file. I have one sub to which I pass in some variables (path\filename, title, etc.) to create the file. It greatly reduces the lines of code in its calling routines, simplifies reading current code, and creating new processes that call the sub/function.
    I wouldn’t have it any other way.

  7. Phil Factor says:

    I think that the general consensus of good practice in programming are all fine. It is hard to disagree with the actual programming practices suggested by the Gang of 4 who are mainly responsible for the myth of reusability (Design Patterns: Elements of Reusable Object-Oriented Software). I think that the objective of making it easy to rewrite and maintain code is much more important than any idea that it must be created with a view to being reusable. If your prime objective is really re-usability, then you are either writing a public framework, or you are a deluding yourself.
    I like to architect applications that make it easy to rewrite, maintain, test, build, integrate and deploy. This is far more useful than making ‘reusable’ code. Reuse just doesn’t often happen. You’re probably going to do things much the same way, only faster and more stress-free, without all the overhead that goes into developing a framework. It is a different art.

  8. jerryhung says:

    Thankfully I only write code in T-SQL nowadays as true DBA. It’s not bad actually

    Code reuse actually means I seek out the best code out there to reuse before writing my own
    e.g. using Ola’s DB Maintenance code to re-index or DBCC instead of my own

    Then I’ll customize to my work environment instead, like scripts to
    - show index sizes/usage
    - Script to backup to UNC with our naming standards
    - generate restore TSQL from a given UNC path

    However I’m not sure if I can share the code due to work permissions @@ I hope there are more out there and one day I can share as well

  9. paschott says:

    I’ll tend to use snippets of prior code, but rarely re-use the entire thing. The situations are different or structures are slightly different, but the underlying principles are pretty much the same. I can take the techniques used and apply them to the current scenario.

    I will admit that I built a crude framework for PGP, Zip, and FTP for files in Python that could then be called from other files. I re-used the underlying code in my calls, but tweaked the names, files, folders, destinations and such to suit the current needs. That was an interesting project, but ultimately saved my sanity. I haven’t had a need to re-use that code elsewhere since it was written, but heard that it’s still in use today.

  10. Timothy A Wiseman says:

    It depends.

    As you mention, I do not reuse SQL Code on a new project all that often. But that is due to the nature of SQL code often being tightly bound to the data structure. Even there, I have some functions and procedures that tend to get used in more than one project.

    Outside of SQL, I tend to reuse code somewhat often. This is partially results from my current job often creating needing projects that are closely related to an old project.

    But even if the code is unlikely to get reused, I find it useful to write it as thought it will be reused. This is in a way the inversion of your statement about writing highly-maintainable, concise, code and having reusability fall out as a side effect. For me, I find focusing on making the code reusable helps me to ensure I have written something which is highly maintainable and concise. If it ever actually does get reused that is a nice side effect.

  11. Andrew Watson says:

    When I started programming, you would write your own list class, and creating something reusable was a good thing… now we have generics – so it’s a matter of just reusing the one they made (and documented!). I guess that’s the problem… writing an algorithm for reuse is one thing, writing business logic for reuse is something altogether – because if it doesn’t come as a whole, then you will probably need to modify lots of it….

    If you want to abstract business process and rules then you end up creating something like Windows WorkFlow, etc, which is reusable to construct business logic in a generic way, and perhaps the components (email this person, print this invoice using this template), might be reusable. Other than that, in my experience businesses and their needs are unique – as most people who implement “off the shelf enterprise systems” (and always seem to go over the quoted project time tailoring it to the business) could tell you.

  12. Robert Young says:

    I do wonder, though, how much longer it will be until some troll finds/gains a patent on “the order entry process” or “the means of establishing and updating a general ledger”?

    Reuse? We’ll spend most of our time writing around these “design” patents, creating mounds of spaghetti never before seen.

    I thought I was being hyperbolic, so I just did a quick search:

    http://www.google.com/patents/US20030216979

  13. callcopse says:

    I think a key point here is that most of the truly re-usable parts of a software development are now taken care of for you either by the framework you work with or by third party extensions. Of course there are plenty of other elements to any kind of project but these are likely specific to that project (and / or related work). Perhaps we are now a mature enough industry to have the tools to only spend time working on the bits that matter.

    I might look at prior projects to see how I did something – I don’t have that technique enshrined in a component. What I do take from project to project is method, and refine that method as I go along taking what has worked well. I agree that taking code from gig to gig, while a nice idea, is not actually that useful.

  14. Vishwas says:

    This is good discussion. Yes, code reuse means different things for different people and this can encompass the algorithms, design & architectural patterns, good practices like comments and coding conventions. I would like to think reusability in more general terms like when one doesn’t need to reinvent the wheel for solving the same or similar problem. In the age of frameworks also, one has to write code which is reusable across the project/application and it won’t be just code but other artifacts like algorithm, design, architecture, best practices. I have been re factoring and re engineering the code sometimes in just 6 months of its birth and major reason has been the very few avenues for reuse.Even in one module (mostly written by one developer) the code is sporadic and mostly same code snippets are copied everywhere. So essentially the DRY principle needs to employed in a way that repetition shall not occur for doing (solving) the same problem.

  15. cryinstone says:

    The mentioned “doing not bad” programmer (in which way? economically?) is definitely relying on work of other, much greater programmers, who created REUSABLE frameworks and libraries for him :-)

Leave a Reply