Enterprise Software

Do you use reusable code?

Justin James notes that most code never gets reused, unless it is a fairly generic component such as a screen widget or a math library. How often do you actually reuse code?

When object-oriented programming (OOP) became popular, one of the things it promised was code reused everywhere. Service-oriented architecture (SOA) also promises code reuse. Every new system out there seems to have code reuse on its bullet point list of wonderful things it enables. Yet it seems as though most code -- even reusable code -- never gets reused, unless it is a fairly generic component such as a screen widget or a math library.

I almost never try writing code to be reusable since nearly every project I work on is completely unrelated to my other projects, and the effort involved is often more than it would be to rewrite the code again. Take this quick poll to let us know whether you really use reusable code.

J.Ja

Disclosure of Justin's industry affiliations: Justin James has a working arrangement with Microsoft to write an article for MSDN Magazine. He also has a contract with Spiceworks to write product buying guides.

---------------------------------------------------------------------------------------

Get weekly development tips in your inbox Keep your developer skills sharp by signing up for TechRepublic's free Web Developer newsletter, delivered each Tuesday. Automatically subscribe today!

About

Justin James is the Lead Architect for Conigent.

77 comments
inet32
inet32

I reuse code some of the time - maybe 10% - but I can't always predict WHICH bits of code I will want to reuse in the future so I write all of it according best practice WRT O-O, typopgraphical conventions, naming conventions, and extensive commenting. Another advantage of this is that code that is designed for reuse is also easier to maintain.

read
read

Some of the code all of the time, but not most of the code most of the time. Things are either reusable or not. However, those that are predicted to be should be written that way. Things that can be found to be reused later may be rewritten to be reusable. It depends on how much QA has been done vs what would need to be done in future. In theory, something that is reusable and that has already been tested should only require minor testing when called from a new location, ie: in context testing, rather than a full blown regression.

RaymondBoisvert
RaymondBoisvert

To me it is a matter of saving for an organisation. If code is well defined and more important well designed, part can be reusable. The biddest problem is to know about code existence.

chris
chris

does reusing functions count? I have a few functions that I know work and ive written so I use them all time time. not EVERY project, but darn nearly. Things like email validation, string validation, random image code, displaying the main menu using a config array that a function spins out into the [ul]. I have a "dynamic query function" that has 3 modes (insert, update and delete) with takes an array as input and does all the db query code dynamically. All procedural by definition, but OOP in spirit :-)

ndavies
ndavies

Yes, I use reusable code and I write reusable code. While every project I work on is ultimately different - different ficus, different output, different audience. they all use the same language, they all have similar needs - querying a database, setting user permissions, access the file structure. All of these tasks are handled by classes - a data object, a user object, a file object, an email object, an error hander object etc. There are more. When I start a new project these classes are imported into the project. If there is some minor tweak then that is made and a new copy saved but this architecture enables me to complete projects very rapidly. The classes develop over time as new project throw up new ideas that are useful to all projects and so the update carries through.

jslarochelle
jslarochelle

I see several types of reusable code artefact: 1) Little snippets of code that are not too complicated but written often. Those are often easy to put in a static method repository (static class in the case of an OO language) or canned in a simple class. This kind of artefact is easy to reuse (simple API) and I do it quite often and efficiently. 2) More complicated functionalities implemented by classes (or modules) or ensemble of classes that are sometimes repeated but less often than (1). In this case it is more difficult to package the functionality in a reusable library. It requires more time and skill. This kind of artefact is also more difficult to reuse because the API is often more complicated and the initial design less than perfect (and thus it requires tuning or sometimes rewriting). As per the definition I reuse those sometimes but with varying level of success. The second aspect of the problem of reuse is reuse by other people. Paradoxically I find that a lot of the code in the first category gets rewritten (and sometimes all over the place) by other programmers while code in the second category will get reused proportionally more often. I guess that this is normal though since it is probably easier to remember a limited number of big artefacts while keeping tabs of a large number of little ones is a challenge on the old brain cells. So, because of the above I feel that it is worth spending a little extra time trying to disseminate knowledge about the little snippets in the first category. So I periodically send emails with little presentation on the latest snippets in category (1) and sometimes a refresher on neglected ones (I call those emails: "Tip of the week" - in fact here in Quebec the actual name is "Truc de la semaine"). I have not given up on the code of the second category. I try to improve my skill there all the time. Right now I'm reading Jaroslav Tulach's "Practical API DEsign". Quite interesting. JS

Mark Miller
Mark Miller

That's a more challenging question. I would think that most developers now use re-usable code at some level all the time. If you use Java, .Net, or some other modern development environment you don't have a choice but to [b]use[/b] re-usable code (the APIs). The greater question in my mind is "Do you write re-usable code?" To that I would say "occasionally".

Saurondor
Saurondor

or any other buzzword like SOA. I believe the best formula for reusable code is a flexible and helpful IDE that allows you to mold your code. OOP facilitates the encapsulation of variables and functions, but it isn't a magic reusability factory. Most of my reusable code starts off as inline code in a method. Say for example print a pdf. // get template // build template // output pdf You select the code then extract a method. When you have that you can then move print related methods to a class and determine class properties (path to template, fill in variables, etc). You start using that class inside the program when you print a pdf. This usually happens when moving from the prototype phase to workable releases. When you have that class then you can at some time move it to its own little library. Since you probably have the core functionality set you'll just have to work a bit more to make its interface more generic. For example if you were doing a desktop app and saving to a file then generalize the output method to accept a stream rather than a file. That way you can output to a filestream or an outputstream that you can plug to the response of a server request. At this point you just extract the interface say "PDFPrinter" and package it as a library. Working from the specific to the generic works best for me. Otherwise (working from generic to specific) you end up with a lot of generic tools that have not been tested in the "field" and might not be what you need. Thus end costing you more to develop and are not being reused. Once again you don't need to use OOP to have reusable code. It has more to do with synthesis and analysis than anything else. And a good IDE goes a long way in helping you reuse code. Back in the days I did C we had reusable code didn't we?

LyleTaylor
LyleTaylor

As I'm writing code, I find that I can often tell what aspects of what I'm writing my be useful in other projects later, and I will often segregate that code in a way that makes it more easily reusable. Of course, not everything is reusable, because, as you say, projects are often very different from each other, but I often find that I can pull things from other projects, even if they have to be modified slightly, even when the projects are radically different.

Justin James
Justin James

Do you really reuse code? Is it something you keep meaning to do, but don't? Do you do it all of the time? Why or why not? J.Ja

hercules.gunter
hercules.gunter

Anything you call more than once is re-use. The original assembler-language macro feature was re-use! Macros were simply heaved in entire by the assembler, but still meant a unit of functionality not actually recoded. Functions and subroutines were more efficient, since there was only a call in the code, and parameters made for variations in the result. Code re-use is one of the most fundamental concepts in writing software.

martyn
martyn

Agree entirely, resusable code is nothing new.

Tony Hopkinson
Tony Hopkinson

However 'componentisation' is fundamental to the idea of the cost saving in OOP reuse, and usually detrimental to actually doing it....

C_Tharp
C_Tharp

JS has obviously practiced reuse. For it to work on a large scale, you must know about all of the reusable code. That can be a huge investment in knowledge. When time constraints are tight, can you afford to search for something reusable, that might not exist? If you find something, will it be documented well enough so that you know it is usable? You know how to write code so where do you put your effort? The risks are high. Communication and knowledge are necessary for it to work. Unfortunately, these are weak in many organizations. To create reusable code you need to know that the potential for reuse exists. That usually requires a big picture view of a project(s). With knowledge of the whole, you should be able to see the common parts and direct the code toward reusable components. If you are simply handed a set of requirements for a piece of a project you can't see that the same code has application in another piece of the project. If you have seen the same thing before you can react and produce a reusable component. As Mr. Saurondor state earlier, it is reative vs proactive. Either way you can get there, but they have different risks and costs.

Justin James
Justin James

... another trip back to my "EdScheme" days in high school! I swear, that half-year class did more to teach me programming than anything before or since... The whole point of the class was to build a useful language out of roughly 13 or 18 operators. I discovered at one point that the language supported a "load library" command of some sort. From that moment on, I went back, rewrote my old projects to all use coherent, consistent terminology and usage patterns, put them into logical library groups, and load them into future projects as-needed. Everytime I did this, the teach deducted points because she said that all of the code must be visible within the project, not hidden in an external library. I continued to do so, because I felt that putting it in a single maintenance point offset the opacity of the code. J.Ja

Tony Hopkinson
Tony Hopkinson

Only kidding. :D We both remember C libraries with functions with extensive argument lists that ended up doing all sorts of things no one sane would ever have put in one place. Now we have 'objects' designed by their descendants.

jhollenb
jhollenb

I wrote a library (library.inc) wich has a massive amount of reusable code. like graphic plot routines, calculations, beautyfiers, login, database functions like one of my fafourites wildata(database,field,knowfieldvalue,anotherfield) wich gets from a known value, from an another table the value from a field. so YES i reuse.......

nishchaya.andrew
nishchaya.andrew

Actually, I want to reuse code most of the time. Current organization I am working has lot more pressure from client side, so I can't able to write class/module which can be reused, but whenever I get time to write those line I do & use them later wherever they fits. If any one know how to do this most of the times just let me & other people (like me) know the way.

GTGeek88
GTGeek88

Did you really say you "almost never try writing code to be reusable"? If your projects are so truly diverse that you are writing in different languages across various operating systems on different platforms, then maybe you're excused. But with the monopoly that Windows has on the desktop, it's hard to believe that you wouldn't be able to write reusable code. Have you no application framework? Have you no set of base classes for forms, form controls, etc? Have you no procedural library that you can call on to do things like format strings, etc? Oh, wait, you're not the programmer who writes all those web sites that refuse to let me enter the dashes on my credit card number because they're too lazy to strip them out on the back end are you? Come on, Justin, can't you do better? I don't expect perfection, but shouldn't you be setting some sort of example if you're writing a blog on Tech Republic? BTW, when I originally tried to post this I got a "could not locate resource" error. I contacted tech support at TR to notify them of this. Their answer was not "sorry, we'll get that fixed", it was "post somewhere else." How's that for quality tech support?!

Alex
Alex

Too simplistic. You need to extend survey to reflect categories by topic: user interfaces, math algorithms, media presentation, database handling, etc. Then you need to give a percentage of reuse approx: 0-100% by type of programmer-web, database, game, graphics design, engineering, etc.. Then you might want to indicate language and language modality: subroutines, programs, classes, structures, applets or dll/ocx like objects. I reuse only about 5% of my code but I had to answer "yes occasionally". That's so misleading it approaches criminal!!

hercules.gunter
hercules.gunter

Any re-usable component requires an interface, and I have often found that one will do what I need except that I can't tell it to do one tiny extra thing. A solution is to add the extra parameter to a thing which has a slightly different name, and embed the original plus the modified code in that, and then have the original simply call the new component with a blank extra parameter. This gets messy after a while. A good solution is an additional parameter provided for extension purposes using an indefinitely-extensible data structure, e.g. a collection, even an array if the language doesn't support collections. Existing code is unaffected by extensions, and the interface need never change, while the capabilities of the component can be extended.

The Unknown IT Guy
The Unknown IT Guy

In the 20 years I have been writing code in various forms, other than school project, I have never written a program from scratch. I always start with a previous version of something, strip out what I don't want, add what I need and modify anything else.

SnoopDougEDoug
SnoopDougEDoug

If so, I reuse code all of the time. Just yesterday I refactored some C++ code off into a function as I realized it was used in two different places in the app.

basstrumpeter
basstrumpeter

I develop embedded software and have a large library of reusable code. Plus the hardware developers are clued in so that a new design has the same basic structure if possible (display, keypad, microprocessor family, communications bus). My estimate is 50% reuse, 30% reused with modifications, and 20% new code for the average new controller. With this I was able to put 2 new 40K line packages into initial system test within 9 weeks. A similar pair (slightly smaller) written from scratch took over 2 years.

mavismel
mavismel

I don't write code myself but i sure appreciate those that do. My website has many mini slide shows because I was able to use the same code every time with relatively few changes. Websites like HTML Goodies To Go provide samples of reusable code that I can rewrite with my material and it's done. Without sites like the above, my web site would not be as interesting.

techrepublic
techrepublic

When I do programming, I find I have little tasks that need to be done often enough that it's worth the time to write a separate chunk of code to reuse as needed. A few months ago I decided to start putting some of my code blocks on a website so that my scripts can just call or use those little pieces right from there.

santhoshsrgm
santhoshsrgm

yes ofcourse, if the code is for two different project but not on same project

Bad Boys Drive Audi
Bad Boys Drive Audi

It all boils down to the triangle of budget, time/effort, and project structure. So often, projects are simply geared to getting a job done in their own little vacuum that no one seems to think about code reuse. In order to build in reusability, you essentially have to break up a portion of the project into some other mini project that may or may not take on a life of its own. And that's when the budget limitations start nipping at you. In my personal experience, I've had to be selective at times to figure out which projects had enough of a budget that would allow me to drive a "mini project" geared toward creating reusable libraries (like the project I'm currently managing now). The effort will be around 200 or so hours, but once complete, we'll use it for the current main project as well as a handful of other projects in the pipeline in the next two years. None of the other projects have the capital to fund this effort and my project really deosn't either - I just had to scramble to endure a 66% budget cut. However, I believe this effort is valuable enough to keep it on the project plan. I know I've certainly had my share of "this couldn't possibly be reused anywhere so why waste the effort" moments. And I've been a part of many projects where I wasn't the PM or even senior level developer so I didn't get to make the call. More often than not, you run into a situation later where you could've benefitted had reusability been thought of (and built) previously. So find and extract what can be reused, get it out of the current project's namespace (one killer of reusability) and source it separately. You'll be surprised how often you'll go back to the well if it's there.

mattohare
mattohare

One of the whole points to procedures and functions and procedures was code reuse. For any project other than the 'hello world' type, I'd put pieces of fucntionality into functions rather naturally. True, back in the old days, it was common to copy and paste. But if I found I was about to copy/paste, I'd rethink and put it into a function. After I'd used objects a while, I went more to them. It's a matter of saving sanity and being able to move on. Do I want to debug something fifty or sixty times? Or keep it to once or twice? This isn't something that's good in theory, but not very practical. It saves me time, money and energy.

Slayer_
Slayer_

Which is impressive considering 99% of my code is done in VBA :) a completely none object oriented language. It's really not hard to write or use reusable code. I don't understand the difficulties people post about here? Ok, I give an example. I wrote a huge file manager class that uses the standard file functions in VB without using any extra referenses, but it can be used the same way as the FSO. It can also read and write INI files without API calls. It can even generate and regenerate INI files automatically when writing to them. Every ounce of code was built to be reusable. And in almost every case, every function is used :). It's a class so you can make more than one and managed as many files at once as you want, you can even automate it mirrioring two or more files.

Jaqui
Jaqui

I save every function I write into the ide code snippets. then, when I need it, I can just insert it. edit variable names to suit the current project. every change other than variable names, I save as a new function in the snippets.

Tony Hopkinson
Tony Hopkinson

That's on the basis, that I design with reuse in mind, and that the penalty for doing so is acceptable. As I've said in the past, re-usability tends to be a joke. Far too often, it costs more than writing something fit for purpose in the first place. The big problem to me, is in order to get it right. You need to know where and how it's going to be reused, good luck wth that. You need the resources to do it properly, something like this the foundation had to be correct. Trying to bodge in extra functionality after you've gone down one usage path, is very expensive. It's either start again, or a cascade of bodging and complexity. You need to stay in scope. By definition, if you go down the reuse route, you are implicitly or explicitly coupled, code rot will ruin you.

jck
jck

it's unavoidable. You're right tho. It's gotta be a generic enough function or object to implement (and not have to struggle in the effort to sub- or super-class it) that will make it useful throughout other projects or other parts of the same project. But most of the time, I don't go about hunting ways to re-use. Whenever it becomes apparent that it will be re-usable, I put the code in a module and call it.

aardvark92
aardvark92

I look for patterns. If I see myself needing the same functionality in project after project, I'll put together a reusable library. But it won't actually be reusable, and will have to be refined over several projects. What I end up with is some mostly reusable code, and half a dozen intermediate versions of it embedded in older projects. It's not an ideal solution, but it does seem to save some development time.

Sterling chip Camden
Sterling chip Camden

My clients are software developers, so the code I write is designed for reuse. Naturally, test harnesses and examples are typically victims of cut-and-paste reuse, but the stuff I'm actually developing is almost always in the form of reusable functions and classes.

chris
chris

is how so many things that come out of "manufacturers libraries" get used for just a small piece. a whole class get instantiated just to do something like "SELECT Lname FROM Clients WHERE...." Another one is writing "SELECT *" and just choosing one of two fields/columns. overhead, overhead, overhead. Or lazy lazy lazy

Sterling chip Camden
Sterling chip Camden

That happens a lot -- people try to reuse the same utility for too many different things, and that's just bad design. The problem needs to be broken down into smaller components.

Justin James
Justin James

Yes, my projects really are that diverse. When I write Windows forms stuff, the UI end of things has always been adequetely handled by the standard controls. Same thing for Web development. I can't remember the last time I put a control on a Web or Windows Form that needed anything other than a character limit on it, for example. The job I had before this one, all of my hands-on code work was SQL to fix problems, import data, etc. There was a slight amount of reuse there; if I saw the same problem more than once, I made the code so that it could be run by other people. In the job before that, all of my code was backend report generation, data processing, etc. The code was very reusable on a project-by-project basis, but it was usually reusable in the "copy/paste then change to fit" way, not the "inherit a class and overload a method or two" way. My last Web development project was to work with an existing CMS system and add in our own backend processing functionality (processing CCs through our bank, coordination with our software licensing system, etc.). Actually, on that one, the CC processing I did was quite reusable; the maker of the CMS actually passed on the module I wrote to another one of their customers to use, it was very much so a "drop in an run" item, but you certainly wouldn't be able to drop it in to any other Web project and process CCs without major rewriting. Indeed, my projects are so diverse, no, there is no application framework. The applications I write never touch the same data, never work with the same things, etc. The TR forums are known to be a bit... buggy... sometimes. I have nothing to do with that, those errors seem to pop up at random in my experience. :( J.Ja

Broosbee
Broosbee

When I design a project, I pay attention to what is generic and what is not. I do mainly DB projects. Name and address is pretty standard. Years ago I noticed most ask you to fill in city and then state and then zip. Now mine ask for zip before city and state. Then it checks if the zip is in a database. If found, it fills in the city and state automatically. If not, it asks for them and updates the database. A bit more to it than that, but you get the idea. It makes the data entry a lot friendlier and more accurate. And all of that is reusable. Unfortunately, there is still a lot of coding, but it does help to reuse generic functions.

chris
chris

everything "important" is in a function. for me it's about not having to worry about debugging. if I know my function works (because it has the last x years), I know the problem is somewhere else, which helps. It also speeds time to launch. I don't worry about the main menus on sites because they reference a config file and a function that spins it out (using a [ul] with text link or even rolloever images). just change the main menu config file, done. That works for 90% of my sites, and the ones that need more get more. I just write those ones from scratch, instead of fighting with my existing fuinction

Realvdude
Realvdude

A great exmaple of designed reuse. Literally everything in any library is code that has been designed for reuse.

chris
chris

One cannot think, "well, i got lots of functions that'll do that so I can quote a lower price" no way. you wrote it, it's going to work for the client, charge them full price. --- And as far as "re-use" goes, i re-use individual functions all over the place and a couple "modules" i built for public websites (contact us form with validation and sending), events module (with single db table) that displays list and jumps to details page), that kind of thing. I just plug em in. of course, I'll customize them too sometimes. so, it is re-used to start with. If the definition of "re-usable" is somehow that the code will be frozen and usable in the form of some divine library, im not really interested in that :-)

Sterling chip Camden
Sterling chip Camden

If it tries to do too much, then reuse is always suboptimal. But if you design components that perform a specific task that will likely be needed elsewhere, then they can be reused successfully. We don't rewrite the UNIX utilities whenever we need a tee or a more. If your component starts gathering a host of options, though, then the chances are you're trying to do too much. Even some of the UNIX utilities suffer from that.

Saurondor
Saurondor

can add up in a non-reuse environment. If you're writing the same process again and again then you'll have to be (hopefully) testing it again and again. The cost of adding more functionality depends on how you compartmentalize your functionality. If you create a piece of code that makes scrambled eggs and call it MakeBreakfast because you only eat eggs for breakfast. Then it will be a bit hard to reuse the code to make another dish. But if you create a piece of code called PrepareEggs and it has a few methods like scrambled and fried. Then you can reuse that for breakfast or any other meal or dish. It will improve over time and hopefully prepare the best eggs in the shortest amount of time. If you ever want pouch eggs then just teach it how to do that. You don't need to touch the other part. If you don't reuse and follow the MakeBreakfast path then you'll have to recode when you get to MakeDinner and MakeSupper. Because like you say it is very hard to modify MakeBreakfast to make dinner or supper. Thus your eggs may taste different in the morning than in the evening because they're two different codes. Thus the key is to reuse a simple and small set of features in a component. Not create a mega-component and try to reuse that. That would be very hard indeed. A bit like trying to have MakeThanksgivingDinner prepare Christmas Eve dinner. But CookTurkey on the other hand is quite reusable.

chris
chris

a function should do ONE thing (from somewhere inside Code Complete). it makes it easier to make it reusable.

BlissC
BlissC

I don't necessarily set out to code something that's re-usable, but often I'll find myself re-using the same snippets over and over again. At that point it becomes reusable. No use reinventing the wheel when there's nothing wrong with the round shape that's already there! ;-)

Bad Boys Drive Audi
Bad Boys Drive Audi

While what you have is a good starting point, you'd be much better off with just a tad more energy spent toward where things might be reusable rather than reacting to things after the fact. I sooooo remember being in your shoes earlier in my career. What helped me break the cycle was to think of building the library FIRST, and then building the current project's application LAST - making it use the library. What I found out with that approach was how much I unnecessarily coupled applications and possible reusable code together, making it unsuitable for reuse. By forcing myself to build libraries as stand-alone components and uncoupling any possible application functionalilty from that library, I helped myself break the mold in which you find yourself. Think "mini project" for reusable code. A stand-alone project who's sole purpose is to build a library for the entire company to be able to access. Once you get your mind there, it's hard to go back; you'll only do so when budget/time simply won't allow it. And even then, you'll go down fighting...

Tony Hopkinson
Tony Hopkinson

You need a graph, use MSChart, just don't bother with the 3d multi-range radar scattering plot... You want a grid where negative numbers show in red, buy an entire component suite... n weeks making your app work with it, versus, ten minutes for if value < 0 then BackGroundColor = red; WTF? "Oh we did it to save development time" Yeah right...

chris
chris

a function should do only one thing. hey, not my rule, but one i agree with...most of the time :-D

mattohare
mattohare

Some of the .net framework is a good case of making sure your reuse is fit for purpose. I'll inherit from existing classes when I can (my own or others'). Part of the testing is to ensure that I'm writing to my needs, and not for an empty value of mindless reuse.

chris
chris

my only issue with some language components is that you end up being handcuffed doing what they want. not a c example, but a good one is the use of .net datagrids. Fast, yes, what i want? not normally. But, more apps I see just use it. Why? is fast and good for their bottom line. Even though the customer (the app) really deserved better.

Bad Boys Drive Audi
Bad Boys Drive Audi

I agree that the reusable component needs to do one thing well and shouldn't be polluted with trying to make it do everything under the sun or trying to handle every single possible permutation of one task. If a project needs to have it handle some specific mutation, then that project should write wrapper code that is an extension of the already existing (and well tested) reusable component. In no instance should you (a) try to make the reusable component do everything or (b) directly modify the component after it has been built, tested and deployed.

chris
chris

we need that there. :-P

Jaqui
Jaqui

from the vi(m) fanbois: emacs? why? I already HAVE an operating system installed.

Justin James
Justin James

Isn't Emacs the text editor with a chess plugin? ;) J.Ja

Tony Hopkinson
Tony Hopkinson

I'm a big fan of simple. All things to all men compoments do me in. MSChart for instance.... Reusability doesn't mean put every possible use in one place. It means avoiding designing yourself into a corner for as long as practical, an approach that has many other advantages.

Tony Hopkinson
Tony Hopkinson

choose to use PHP... :p Not one of my favourites at all.

chris
chris

then they diverge. I agree, lots of projects start out well, but end up with what is essentially spaghetti oop. huge budgets are needed to keep that from ever happening. or, smaller projects where "the guy" can just fix it as he goes.

chris
chris

based upon the library they got. THAT is the MS way, which is why i choose PHP. it's more hand work but i get only what I want (and Im arrogant enough to believe that is better than having MS tell me differently :-P)

chris
chris

I agree and not all them many seem to really do it. it's just like designing a db. you want to use meta data to get you there (the name should make it obvious what it is/does). are they contacts, customers, clients, people, or humans? is it checkEmail or validateEmailFormat

Tony Hopkinson
Tony Hopkinson

If you start with preparefood, and then do prepareeggs and preparebacon, then youhave a chance. Even more so if preparefood makes no mention whatsoever of eggs bacon, mushrooms or any damn thing else. All too often, you have prepareeggs, you go back and create preparefood, realise you need another week to do it properly, don't get the resource and end up with poached pigs testicles.... Which is why my main thrust has been you need to write with reuse in mind. Even then you can end up with PrepareFood doing nothing but food.Prepare. If one application does eggs and the other bacon, you just wrote a lot of code to pay lip service to reuse.

Realvdude
Realvdude

I sure have experienced this, to the point where I have found variables named based on a different SQL table than what a ASP page is handling. I think there's a line between reusability (it does what I need) and retasking (it does nearly the same thing). When the decision falls to retasking code, then I think that the responsibility of managing the derived code falls to the new task. Reusable code being like the trunk or roots of a tree and retasking being branches and leaves; once the code is retasked the original and the copy have no effect on each other.

SnoopDougEDoug
SnoopDougEDoug

Decoupling data from presentation is not really using reusable code, but it is reasonable practice. Although I have seen terrible dependencies even there.

ian
ian

"But if you create a piece of code called PrepareEggs and it has a few methods like scrambled and fried. Then you can reuse that for breakfast or any other meal or dish. It will improve over time and hopefully prepare the best eggs in the shortest amount of time. If you ever want pouch eggs then just teach it how to do that. You don't need to touch the other part." But even better to take it a step more generic and create code called "cook something". That's what I and colleagues did with health care applications some years ago and were able to build bulletproof back ends coupled with sensitiove customisable front ends. The problem often is that people think the code should reflect what the user expects, rather than what the fundamental processes and data are.

Tony Hopkinson
Tony Hopkinson

Between developers and across a homogenous product suite. Individual working environment doesn't come in to it. I was talking components B,C & D descend from A, then some one adds E, and enhances B, wants some common functionality, and so adds it to A.... If you started again, you might for instance put the behaviour you want in an interface, or as a sub class and aggregate it, but that's reworking the lot, and therefore regression testing the lot. Regression testing is a QA decision at our place, and they err on the side of caution. Bearing in mind the above scenario has ben going on across the boad for ten years, I can hardly blame them... Cut, paste and twiddle to me is not reuse, as the reuse at all costs muppets would define it. Even if we add that in, it all depends on the complexity of what you are reusing, and how close it is to what you now need. Chuck in unrefactored code, written by someone else, when no standards have been enforced, or they have changed, and it's a toss up whether it would have been quicker to write what you needed from scratch anyway. Have we got more problems than reuse, definitely, but it was reuse without realisation of the penalties, that kicked it off. It's not win-win

Saurondor
Saurondor

While what you comment is correct. It assumes one updates blindly and automatically and can't rollback. Lets label your example. I create version 1.0.1. Then someone creates version 1.0.2 and then someone comes along and creates version 1.0.3. Yet I'm still using 1.0.1. Do I need regression testing? Nope. I'm still using the same code I released. Even when someone modified it to do some extra thing. Because they did that in their working environment. The good thing is the person who created version 1.0.2 didn't have to start from scratch and that saves time (money). All the others who needed what I have in 1.0.1 and don't need any changes saved the most. Now if Mr 1.0.2's edit somehow got from his development environment to mine without my consent. Then I have more important things to worry about than code reusability. If version 1.0.3 adds new features that I don't need do I need regression testing? Theoretically not. Because I'm not using them in my code. If I developed functions A and B and Mr 1.0.3 added function C. Does it affect my code? No, because I'm not calling it. Now if Mr 1.0.2 or 1.0.3 modified functions A or B do I need to spend a fortune on regression testing? No. Because the tests in place that I did for A and B should still apply. On the other hand if Mr 1.0.2 or Mr 1.0.3 modified A or B in a way it does change things from say divide two numbers to multiply them. Then we're not doing code reuse, we are doing a mess. And there is no cure for that. Yet if the changes done by these gentlemen are more on the lines of removing A and adding C. They they should be Mr. 1.1.0 and Mr. 1.1.1 rather than 1.0.x. While it could be challenged that I'm omitting regression testing in some cases were it would be needed (specifically in the case of the 1.1.x examples of the last paragraph). I have a hard time believing it would be more expensive than the alternative. Which is having Mr 1.0.3, Mr. 1.0.2 and myself (Mr. 1.0.1) independently identify the problem the reused code is addressing, design a solution for it, implement it and test it. Only in the most trivial problems is this cheaper than regression testing. And like I exemplified I don't need to use somebody's addon work while that person does benefit from my prior work. And when that somebody is myself working on a newer project I get a quick start that benefits me. I might never use the evolved version in the old project (omitting the need for regression testing altogether), but I need not start from zero on the new project either.

Tony Hopkinson
Tony Hopkinson

If you have a piece of code, tested working and released. Then someone comes along and says let's reuse this. Then they realise, it's needs a 'tweak' or two. Then they test and release. Then someone comes along says lets, reuse it again, but hey it needs another two changes... Then there's the fact that unit testing, tests all the features of the reusable code, front end testing automated or not, you may not want one of those features to be enabled. Even if your documentation is good enough to detect the dependancy (well done !) you are still talking about regression testing product A for an enhancement to product B. Now being a sensible bloke you might argue that maybe, this isn't/wasn't reuse. The reuse at all costs muppets do not though. This stuff happens, all I'm saying is that in the land of the real, code reuse can cost more than it saves.

Saurondor
Saurondor

How much of that is poor version control and dependency control? Are we blaming "reusable code" when we should be blaming the lack of proper tools to manage a project? Is regression testing costing us more because we don't have automated testing in place? I can not see how testing a new piece of code can be cheaper than maintaining the old piece of code when we already have tests in place for the old piece of code.

Tony Hopkinson
Tony Hopkinson

the people who employ us.... Far to often the question posed is how can I reuse this code, not is this code reusable? Regression testing reusable code can cost way more than testing individually. If you are allowed to do it right, it works, most of the time in commercial dcevlopement we are not allowed to, in fact as far as I can see we actively discouraged from doing so. At least if you have a lot of simial;r but separate code, you don't end up fragging, something that appears to be completely unrelated from a usage point of view.

Saurondor
Saurondor

You hit a very valid point here: "How much additional time is argumentative because it would be faster for someone skilled at it than someone who only has one or two projects under their belt." And how do you become skilled if you never have the time to redesign for reuse? If a)skilled reusers take less time to create reusable code than unskilled reusers. b)both skilled and unskilled reusers take the same amount of time to create non reusable code. c)becoming skilled at reusing takes time d)skill in reusing is itself reusable ;) We can conclude that there will always be a drop in efficiency as one begins to practice reuse in one's project. This drop will lessen as one becomes more experience and one will then begin to reap the benefits of reusable code. Since reuse skills are themselves reusable we don't have to train every other year. Unlike new tools and languages and markup standards. So the question is. If we have time to spare for new tools, languages and what not. Why not spend a little at becoming better at reusing?

Bad Boys Drive Audi
Bad Boys Drive Audi

I believe you misinterpretted what I was saying. I wasn't suggesting that project A needed to simply tap something that was already built and working. What I was saying was that when in the process of building project A, would you take the necessary time to build project B (the reusable component) so that future projects could tap that component. There's a difference. In the latter scenario, it will certainly take more time and effort to extract out the reusable portion and build it separately than to build everything coupled together. How much additional time is argumentative because it would be faster for someone skilled at it than someone who only has one or two projects under their belt. You then have to factor in the additional testing time, although if one engages in basic unit testing with everything they build, then the difference wouldn't be that drastic. Personally, I tend to unit test everything, so the breakout of testing is quite time heavy on the unit test part of the equation, and lighter on the system test and end-to-end tests - simply because most bugs have already been squished during unit tests. My experience is whatever fails in end-to-end tests are generally business process situations and not programming bugs.

hercules.gunter
hercules.gunter

I have always found that plugging in a re-usable component takes very little time. If your budget is tight, then you haven't got the time to do it all from scratch! If you haven't got the time to do it the best way, using existing components, you certainly haven't got the time to do it in a less effective way.

chris
chris

I do something similar (but in a more inline way. When i need a function, I step back and write it in a generic way that it could be used over and over again (which is what I would've done had i done it beforehand)), but you must stay open to the idea that your app will dictate some code. otherwise you are going to make app decisions based upon your library, which may not really fit the need. You'll end up coding like MS, then you choose "Add Attachment" and the "Accept/choose" button says "Open" on it. Open? no, Attach, Accept, but not open. to me, that is an example of OOP getting in the way of good design.

Editor's Picks