• Home
  • RSS Feed
  • Log in

When not to refactor
Posted by Lars Vonk around lunchtime: July 18th, 2008

Refactoring is part of a software developers work. General rule of thumb I always used is if you see code that smells (for instance duplication) you should refactor. But does this rule always apply? Are there any situations when you should not refactor? And if so, how do you recognize those situations?

Last week I worked on a particular task, let's call it task X, where I needed to use a service with an unclear interface and a smelly implementation. After consulting with the rest of the team we decided to refactor this particular method of the service so it will be more clear and remove code duplication in that method. But while I was refactoring I noticed the other methods in the service were also unclear and contained code duplication, so I started to refactor those as well. To proof the service still worked as before I needed a good (automated) regression testset. It was production software and I wanted to make sure I didn't break anything with my refactoring. Unfortunately there wasn't an automated regression testset for all the methods in the service. So while I was on the verge of creating a complete automated regression testset for the entire service that, amongst other things, would have consisted of mocking a webservice call I remembered something about shaving yaks.
Why would I create an automated testset for the entire service, while I am actually working on task X? So before stuff get out of hand I decided not to refactor the other methods in the service, leave the code duplication in place and just stick to refactoring (and testing) that one method in the service.

What made me decide not to refactor?

  • The refacoring did not have a direct connection with task X I was working on
  • There was no automated regression testset available
  • The rest of team agreed with not refactoring
  • The complete refactoring (incl testing) would have taken more than a single day to finish (at least a week)
  • A good practice in agile modeling is only update when it hurts. I think this also applies when it comes to refactoring code. I wasn't using the other methods of the service and therefor it did not hurt me

With pain in my heart I had to leave the smelly code alone and went on with implementing Task X. Does this mean the service stays smelly? I think that will depend on the future functionality we are going to implement and if we need that same service again. And if we do we will probably apply the same rules as we did in this situation.

Lars

  • Share/Bookmark

Filed under Java | 8 Comments »



8 Responses to “When not to refactor”



    Age Mooy Says:
    Posted at: July 18, 2008 at 1:13 pm

    Did you add the lack of a good regression test to your backlog as a user story or an impediment ? I think you made the correct short-term decision but that does not mean the problem goes away.

    If you make these kinds of short-term decisions too often, you end up with (more) technical debt until it reaches a scale where you can’t even fix it within one iteration anymore. Usually somewhere around that point you do have to change the code involved but by that time it is no longer possible to refactor it due to overwhelming technical debt.

    Deciding to not refactor can be a good thing but you should always try to make sure that the problems you found does get solved at some point before they become major impediments.



    Nanne Says:
    Posted at: July 18, 2008 at 1:16 pm

    There is a good book ‘Working Effectively with Legacy Code by Michael Feathers’ about this subject. It describes, amongst others, the situation you described above. The book offers pattern/solutions to problems you might encounter while working with legacy code. It addressed some problems I encounter on a daily basis.



    Frank Smith Says:
    Posted at: July 19, 2008 at 11:10 pm

    A good test suite is a prerequisite for effective refactoring. So this is one answer to your questions. If the team doesn’t have good testing practices and it’s not willing or able to pay that debt then refactoring should be done very carefully, if at all.

    It’s analogous to asking “when should someone not exercise?”. If the person has a serious heart condition from years of smoking and being obese, they might want to consider exercising less than is normally recommended.



    Mathias Says:
    Posted at: July 20, 2008 at 12:07 am

    I agree with Age Mooy. It sounds like the right decision in the short term: starting to refactor right now, just for one feature, with no tests in place, sounds like entering the jungle with just a pocket knife.
    On the other hand, the key issue here is the absence of tests; that’s not going to improve over time, and will make changes more and more painful over time.
    I would discuss with the team and see whether there is an agreement to invest some time in putting in place the minimum missing tests so that next time you don’t have the issue!



    Gerard Janssen Says:
    Posted at: July 20, 2008 at 8:34 am

    Age has an interesting take on this question. It sounds reasonable, but I’m not sure if I agree with it. Sure it is useful to add a user story to make the technical debt visible. But I do not agree that the technical debt was actually increased by this action. It was already there, only hidden. So it remains the question what the long term effect will be. If it will never hurt enough, it is best left alone. I agree that when building new software you should optimize your unit testing (although taking that to far might also get you into trouble as we have experienced in the past…), but when working with existing code you do need to be careful not to go to far with this.
    Writing unit tests is done for a purpose. In this case for being able to refactor smelly code. But smelly code is not the same as broken code. I think in this case the right decision was made to not invest the clients money to refactor, but to save it for adding value in the form of new features. So how about stating that not having unit tests for smelly code is not technical debt at all and that not having unit test for broken code or for code that needs to be changed consists of technical debt. So is it technical debt? It depends. For new code this is different. Here you create unit tests to verify you new code works, so the decision is much easier made to write unit tests.
    Just writing unit tests for every piece of existing code is not a wise investment of money. If you are not going to need it, don’t.



    Sara Says:
    Posted at: July 21, 2008 at 4:54 am

    Very good points. I would also maintain that if the smelly code is driving you crazy enough to refactor in your spare time none of these rules apply.



    Manish Sharma Says:
    Posted at: August 12, 2008 at 8:08 am

    Avoiding refactoring due to lack of time and other factors is a commonly observed in software development. But one thing commonly observed is that we either try to refactor full code or none whereas I believe refactoring is a step by step process.

    Taking you case as example, I would have refactored the duplicate code (visible smell) and moved on with Task X. Sometime later when I or someone else visits the service class then refactor a bit more with unit tests.



    nothing blog from outer space : To refactor or not to refactor Says:
    Posted at: July 28, 2009 at 4:07 pm

    [...] Das Refactoring von grösseren Projekten bringt jedoch auch Risiken mit sich: Zum einen ist schwer abzuschätzen, wann der Code für die Veröffentlichung „schön genug“ ist, und Refactoring kann zum teuren Selbstläufer werden. Zum anderen besteht eine reale Gefahr, vorhandenen Code zu beschädigen: Denn die Einzelteile des bestehenden Systems sind unter Umständen stärker miteinander verwoben, als dies auf den ersten Blick ersichtlich ist. Eine unbedachte Änderung einer Methode kann andernorts zu unerwünschten Nebeneffekten führen. Automatisierte Tests helfen, dieses Risiko zu verringern, doch auch diese müssen sorgfältig erstellt werden und die richtigen Bedingungen testen. Schliesslich ist eine sorgfältige Zeitplanung notwendig, um ein Projekt trotz Refactoring fristgerecht abliefern zu können – auch schöner Code nützt wenig, wenn er nie produktiv eingesetzt wird. (Gründe, auf ein Refactoring zu verzichten.) [...]



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    Scrum Java Maven Functional Programming Grails Closures IntelliJ Architecture Poppendieck Performance Ajax Semantic Web Introduction to Agile Hibernate Scala product owner Agile Awareness Workshop esb Spring SOA XML Groovy Xebia fitnesse Lean Testing JavaOne Seam Agile qcon
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs