Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
Check out the new SourceForge HTML5 internet speed test! No Flash necessary and runs on all devices. ×
Programming

The Best Ways To Simplify Your Code? (dice.com) 197

Nerval's Lobster writes: Technical debt arises for many reasons—whether moving goal posts, pressure to get code tested and released, high programmer turnover, and lack of documentation. Over time, it can also render code a spaghetti-like mess. But how to deal with it? In a new column on Dice, developer David Bolton offers some suggestions, ranging from refactoring to using compiler inference to increase readability and shorten declarations. While those techniques are straightforward, it's clear that a lot of developers let their code get out of control, and trying to plan beforehand doesn't necessarily prevent the work from getting overcomplicated. It seems like every developer has a go-to technique (or four) for keeping things a little more streamlined. What are yours?
This discussion has been archived. No new comments can be posted.

The Best Ways To Simplify Your Code?

Comments Filter:
  • One line at a time.
    • by PRMan ( 959735 ) on Thursday January 14, 2016 @01:57PM (#51301417)

      Think more. Write less.

      Writing less code has many benefits:

      • Since bugs are a function of lines of code, you write less bugs
      • Since your code is shorter, other people can read and understand it easier
      • You will end up using more libraries, which have been well-tested by others
      • Your code will fit in the CPU cache, making it even faster

      Ideas that involve writing a ton more code to do X always backfire, the latest being TDD/IOC. That stuff is nearly impossible to read and maintain.

      KISS (keep it simple, stupid)

      • I would agree to this sentiment within the classes as the methods, but in terms of an overall enterprise application I think there is a lot of value in "going wide" so to speak.

        In our application a lot of the cruft that built up was due to new services being built out at a fast pace within the framework of other code designed to do slightly different things for slightly different people. The result is that we have gigantic stacks of code trying to figure out what came from where and what it needs in return

      • Since your code is shorter, other people can read and understand it easier

        Some Perl maintainers would like a word with you.

      • Think more. Write less.

        Totally agree but you can also overthink a problem. I've been caught doing this myself. A strategy I've been using is to identify the maintainability requirements. That's how I decide how much work will go into the structure and it's ability to expand for the future.

        Writing less code has many benefits

        I'm going to assume you mean modularize you code because less code is not necessary easier to read or more efficient on the IOs. I can overcomplicate a simple if statement by using a series of NOT, AND, XOR, OR operations but that doesn't mean i

        • by swilver ( 617741 )

          I find them equally easy to read. You should just get some more experience with ?: constructs. They're not the same as IF's, which gives you added feedback that only one thing happens (a value is guaranteed assigned), where as in a IF I can do other things, with no guarantee anything was assigned.

        • I tend to put too many lines in my conditionals when it would have been better to split it out into a function; if the conditional doesn't fit on a single screen, you should seriously consider shortening up the code.

      • by Rinikusu ( 28164 )

        Ever see "A River Runs Through It"? Sometimes I harbor a thought that every programmer needs to have the dad as their programming mentor, especially from the scene where the kid is turning in his writing assignment.

        "Again, this time half as long."
        "Again, this time half as long."
        "Again, this time half as long."
        "Good. Now throw it in the trash."

    • Cut and paste.

  • by QuietLagoon ( 813062 ) on Thursday January 14, 2016 @01:47PM (#51301299)
    systemd fell into the trap of doing too much.

    .
    And then there is always this old chestnut... The Big Ball of Mud. [laputan.org]

    • It's not necessarily about doing too much, it's about doing stuff that nobody was even asking for to begin with. Notice the common trend with Lennart's software is "the current solution is bad in some corner case, let's replace it with something that's worse in every other situation". Perfect example is the new interface naming standards: all it does is fix a few corner cases that could already be done with udev rules, at the expense of less simplicity for general cases.
  • How to deal (Score:5, Funny)

    by Rei ( 128717 ) on Thursday January 14, 2016 @01:47PM (#51301305) Homepage

    It seems like every developer has a go-to technique (or four) for keeping things a little more streamlined. What are yours?

    The mess is just part of coding. Deal with the mess. Accept the mess. Live with the mess. Join with the mess. Speak with the mess. Hear its answers whispered into your head. Nod assent as the mess intones its instructions. Welcome the mess in and let its tendrils throw through your veins. Understand the mess's greater plans and become its corporeal servant on this earth. Hail the mess. Hail the mess. All hail the mess. HAIL!

    • No, no, no... You ABSTRACT away the mess by making sweeping generalizations which with introspection leads you to a way to implement the mess. Remember, there is a METHOD in the madness.....

      • Then take all of of your glorious abstraction and stuff it into a FRAMEWORK that is so simple, anyone could effortlessly use as soon as they learn all the rules of using the framework properly.

        Then have different programming teams start stuffing stuff into different frameworks and this famous quote comes to mind,

        "Frameworks that Eat Frameworks don’t like it when you Customize the Frameworks they Eat"

        When you get to this point, large modular software starts looking very supportable.

    • by PRMan ( 959735 )
      I really hate people like you. You take all the joy out of coding with your crap.
    • Re:How to deal (Score:5, Insightful)

      by phantomfive ( 622387 ) on Thursday January 14, 2016 @02:07PM (#51301519) Journal
      I think the code is a representation of the person. People who think clearly write clear code. Learn to think clearly.
      • by jofas ( 1081977 )
        This doesn't address the part where you inherit someone ELSE's mess.
        • If you inherit someone else's mess, and your team is really good (because if your team is not good, your first priority needs to be training them, otherwise they'll just write even more bad code), then the answer is to encapsulate the ugliness and move on.

          If you are working in a section of code, spend a little time clean it up, since you'll have to test it anyway. Make sure you understand the implications of every line you change (yeah, that's slow). Over time, the sections you work with a lot will becom
          • > Make sure you understand the implications of every line you change (yeah, that's slow).

            A complementary technique I used recently was to make sure I did NOT understand the code. I could understand the implications of changes, avoid any side-effects, by not trying to understand what the code did and instead applying mechanical transformations. I got a new job, working on a code base I'd never seen before. I made some significant improvements by refactoring code while making sure I didn't understand anyth

            • That's a good point, too. You kind of have to draw a line in your mind, "This is affected by the change......That is not affected by the change."
    • Don't mess with code from Texas.

  • Step 1 - Don't (Score:5, Insightful)

    by mccalli ( 323026 ) on Thursday January 14, 2016 @01:49PM (#51301325) Homepage
    No really, do not do this unless you actually need to make changes in the area involved. Diving into old code just to tidy it up brings its own set of risks, and they may simply outweigh any 'niceness' advantage.

    Instead - black box it. Interface it off. Make your new code structured, shiny and gleaming. Do black box-style testing (inputs vs outputs, almost like futzing) against the old code's API and make sure your interfaced version produces the same. Unit test the hell out of your new code.

    Over time, should you actually find a genuine need to, you can then start to look at the black box. Can it be made into a series of smaller black boxes? Can you interface those off too, independently? Cool - do it, one at a time, and use the same approach you used before. Eventually you'll either be left with nicely restructured code or, more likely, nice code that changes often and gnarly horrible stuff that doesn't change ever, but that's hidden behind an interface/library/<insert abstraction methodology here> and works.

    Should always weigh the operational risk of changing ugly-but-known-quantity against shiny-but-unknown-quantity. The path of what to do will be different for every case.
    • Re:Step 1 - Don't (Score:5, Insightful)

      by Fly Swatter ( 30498 ) on Thursday January 14, 2016 @02:03PM (#51301485) Homepage

      Yes this.

      It seems there is always that programmer that decides "I'm going to refactor this bit of code here to make it smaller, faster and cleaner". The actual result is things break (often not immediately) and it winds up taking up even more of said developers time as well as others that use or rely on that code.

      If someone says "I'm going to refactor this bit of code here to make it smaller, faster and cleaner", and they can not give a very good reason to the question "why?", don't let them do it.

      • Re:Step 1 - Don't (Score:4, Insightful)

        by mark-t ( 151149 ) <markt@nerdflat. c o m> on Thursday January 14, 2016 @02:09PM (#51301531) Journal

        The programmer that decides I'm going to refactor some working bit of code to make it smaller and faster without first having the working version saved in the main code repository is an idiot.

        There is absolutely nothing wrong with refactoring code that is working to make it better, as long as you approach the task incrementally - don't try to do too much in one go, and test and retest each change to ensure that you haven't broken anything. If you do, revert and try to figure out what you did wrong. The time it will save you in the long run when the code is more readable will pay for the time spent refactoring it by more than an order of magnitude.

      • That make a lot of sense pragmatically, but it would be much less likely to happen if the codebase wasn't in serious need of refactoring. unanticipatable side-effects is a sure sign of speghetti-code, often sprinkled with GOTOs.

    • Re:Step 1 - Don't (Score:5, Insightful)

      by gstoddart ( 321705 ) on Thursday January 14, 2016 @02:18PM (#51301605) Homepage

      Let me offer a counter point: abstracting, wrapping, deferring, and hiding those black boxes can often lead you to building abstractions and interfaces which promise more than the underlying code can deliver, or which are outright not compatible with it.

      If you run screaming from your real code so you can add a layer of code which allows you to pretend like you know what code you have, sooner or later you do something monumentally STUPID.

      And the more you add layers of pretty on top of layers of ugly, the sooner it will bite you in the ass.

      I've seen (on more than one occasion) someone taking old and ugly code, building a few layers of shiny on top of it, and then start passing around code which explicitly says "WARNING, THIS IS NOT THREAD SAFE" or "DANGER, DON'T EVER DO THIS", and then pass it into stuff which violates those assumptions right up until the code fails spectacularly.

      And then of course people look as far as their abstraction and say "looks good here, we won't check down where the dragons are because our abstraction is awesome and perfect".

      There are dragons, and if you don't understand it well enough to deal with the dragons, you may not be qualified to build a wrapper around the dragons. Because dragons are sneaky and always looking for a way to bit you on the ass.

      I'm not saying don't clean up old code where you can. But if you think piling layers of bad assumptions on top of something you don't understand is a good solution, you're just waiting to get burned.

      Or bit in the ass by a dragon you though was no longer a threat.

      • Re:Step 1 - Don't (Score:4, Insightful)

        by phantomfive ( 622387 ) on Thursday January 14, 2016 @02:44PM (#51301849) Journal

        Let me offer a counter point: abstracting, wrapping, deferring, and hiding those black boxes can often lead you to building abstractions and interfaces which promise more than the underlying code can deliver, or which are outright not compatible with it. If you run screaming from your real code so you can add a layer of code which allows you to pretend like you know what code you have, sooner or later you do something monumentally STUPID.

        You are right, and the GP is also right. The reality is, people who write bad code will write bad code, no matter what 'strategy' they use (and those people will typically use the wrong strategy, too).

        When programmers aren't asking themselves, "how can I write readable code?" then you can be sure their code won't be readable, even when they follow all the guidelines.

        Also, if the programmers on your team are writing bad code, you either need to teach them to do better or leave the company because it doesn't matter how brilliant you are, you can't clean faster than the other programmers make a mess.

    • by creimer ( 824291 )

      Diving into old code just to tidy it up brings its own set of risks, and they may simply outweigh any 'niceness' advantage.

      This is where unit tests come in. Refactor and test is a good way to clean up code.

      • That's lovely if you already have *comprehensive* unit tests available, and is one of the big wonderful reasons to create them as you work.

        If you're not so lucky though, say coming in on a big project where the previous maintainers weren't 100% committed to creating and maintaining a comprehensive unit test suite, then you first need to have a comprehensive understanding of *every* way in which the module is used, everywhere in the program, in order to create the missing tests. That can be a major undertaki

        • Also, some software is not well suited for a comprehensive unit test suite. I work on stuff that has a GUI, which I can't unit-test with the tools we have, and it spits out gcode for CNC mills, which I also can't unit-test. When a serious test of some functionality requires that the operator load something into a CNC mill and run it, it really can't be unit-tested.

    • by bigpat ( 158134 )

      The best thing that can result in this type of divide and conquer approach is when you realize a thousand lines of code is pretty much necessary for doing one thing and there is a one line code solution for that functionality. That feels good and it has happened to me more than once... with other people's code of course.

      The most important keys on the programmers keyboard are backspace and delete keys. Followed closely by or preceded by Ctrl-a.

  • Fuck dice (Score:4, Insightful)

    by Lunix Nutcase ( 1092239 ) on Thursday January 14, 2016 @01:50PM (#51301341)

    The best way is likely by not reading a Dice article.

  • fuck off dice (Score:2, Insightful)

    by Anonymous Coward

    But seriously, the main problem is that many developers don't give a shit about the quality of their work and no one notices or does anything about it. It's not a matter of learning a technique.

    If there's no rigor around what you write or how it gets tested, software will turn out shitty. If the development issues can't be fixed, it's often easier to just lie to the client or use hacks and workarounds to hide problems.

    The fault for this lies with management. You need to police your developers but also treat

  • by xxxJonBoyxxx ( 565205 ) on Thursday January 14, 2016 @01:54PM (#51301375)

    Are you sure you know what those terms mean? (e.g., Fast but simple solutions often create technical debt.)

  • by phantomfive ( 622387 ) on Thursday January 14, 2016 @01:56PM (#51301401) Journal
    When your question gets closed on Stack Overflow, then try to ask it on Slashdot?

    Frankly, if your code is constantly getting out of control and becoming unreadable, you are not doing professional work, you are doing amateur work (and yes, I know that there are plenty of paid professionals who do amateur work. We've seen stories from Trend Micro programmers here recently on Slashdot).

    It's not a set of rules to follow. If there were a mindless algorithm to follow, then a computer could do it. Instead, when you are about to write code, always ask yourself, "How can I write this in a way that future programmers can understand it?"
    • And a set of rules if it did exist would not apply to everyone. The way to do things when writing web code is not the same way to write a Java application, versus a C++ application, versus code for an embedded system, etc. Some of the good techniques in some domains are really awful ideas in other domains.

      • Some of the good techniques in some domains are really awful ideas in other domains.

        As a Python programmer, I used to disagree with you, but lately I've found my C++ code is much more flexible since I added some braces.

  • Goto (Score:5, Funny)

    by Anonymous Coward on Thursday January 14, 2016 @01:57PM (#51301419)

    has a go-to technique

    How did they know my technique!?

  • by hey! ( 33014 ) on Thursday January 14, 2016 @01:59PM (#51301447) Homepage Journal

    Understand the problem it addresses better.

  • by dark.nebulae ( 3950923 ) on Thursday January 14, 2016 @02:02PM (#51301465)

    Developer David Bolton has moved on from Dice and the remaining authors have been left scrambling trying to pull his notes and articles etc together to generate new content. They report having difficulty understanding how he cobbled together the disparate information into existing articles and have advocated just rewriting the articles from the ground up so they would be easier to maintain going forward.

    • Narrative debt arises for many reasons - whether moving goal posts, pressure to get articles edited and posted, high writer turnover, and lack of organization of source material. Over time, it can also render workflow a spaghetti-like mess. But how to deal with it?

      In a new column on Dice, developer David Bolton offers some suggestions, ranging from restructuring to using natural language inference to increase readability and shorten sentences. While those techniques are straightforward, it's clear that a lo

  • Eliminate error handling.
    • Also don't do any string validation from user input.

      All that stuff is just extra cruft that gets in the way of clean looking code.

      • Just check anything like a textbook. You'll find that almost all, if not all, of the code examples follow these simple rules.

  • by crow_t_robot ( 528562 ) on Thursday January 14, 2016 @02:11PM (#51301547)
    No one, absolutely no one, wants to read your shit articles. Stop pumping them into the feed.
  • Basically, I used to refactor constantly whenever I maintained code.

    When sarbaynes oxley was passed, every change had to be approved by lower, then mid, then upper management in a series of 6 meetings. Doing anything except exactly the enhancement they wanted was virtually impossible. There is never a good cost/benefit for cleaning code when you think that way. Any change outside exactly what was approved would get you written up.

    I went into management. Programming ceased to be engaging. it was easier

  • Don't get a development team larger than the task really calls for. I've seen so many chunks of code that really has not much to do be horribly convoluted because they split up the work amongst more developers than it makes sense to have working on it.

  • by postmortem ( 906676 ) on Thursday January 14, 2016 @02:16PM (#51301591) Journal

    It is in having detailed requirements and performing proper testing. Good requirements will lead to good tests which will detect most of code defects. Doing structural coverage will also find not needed code.

  • by AlanBDee ( 2261976 ) on Thursday January 14, 2016 @02:20PM (#51301623)

    These books provide much better information on the topic and deserve a place on your shelf alongside the GoF's Design Patterns.

  • Do you think that lawyers sit around lamenting the complexity of the legal system that means cases take years and thousands of hours of work to decide? Or that accountants sit around wishing the tax code was simplified to the point where a regular small business owner could prepare their returns themselves?

    It may be a good thing for humanity if programmers create less work for themselves, but it is certainly not a good thing for the programming profession in the money-go-round that is banker-capitalism. It

  • Two things (Score:5, Interesting)

    by DFDumont ( 19326 ) on Thursday January 14, 2016 @02:32PM (#51301743)

    One of the checks I do is to have a non-programmer just READ my code. If they can make any sense of it (Think variable and function names) then I continue. If not, I rewrite until it reads like English (with extra stuff in the middle :-)

    I also have SHORT (as in a single line or perhaps two) comment block at the start of anything that isn't immediately obvious. This adds to readability.

    I have code blocks that are more than 10 years old, that I still refer to and which I can make out the intent and the execution without issue because of these two very simple techniques. '$a' doesn't tell me anything. '$account_name' does. Stop trying to limit your typing load.

    Other thing I do, which I find missing from a a great many things; Check your inputs and your return values. As much as this is Programming 101 level stuff, it is remarkably absent from so much code. How is it that SQL injection works at all?

    • One of the checks I do is to have a non-programmer just READ my code. If they can make any sense of it (Think variable and function names) then I continue.

      That's a really good idea.

    • by mark-t ( 151149 )
      Lately, I have been working for an employer that eschews comments. His beef with them is that they are capable of telling lies, and you won't necessarily know what a function does or how it works without reading the code itself anyways, so one should try to write code that is clear and easy to read *without* comments. He argues that writing a comment is an admission of failure on the part of the developer, that the developer has knowingly failed to write their code in a concise a clear way so that what i
      • The code tells you what the code does. The comments tell you why.

        • by mark-t ( 151149 )
          One should be able to infer that from the function name, and if that's not enough, finding the places in the code where the function is called (common functionality in a modern IDE).

          Really, is it the tendency for comments to be deprecated by evolving code that is the fundamental problem.... because the compiler rarely checks comments for accuracy, there is nothing to stop a programmer from leaving a deprecated comment in the code that may go undetected for weeks. Another new programmer comes along and r

    • Have good code reviews too. However sometimes on my team I feel like I'm the only one that really does this. Others do code reviews but they mostly just say "looks good, check in in" rather than actually inspecting the code in any depth or providing constructive feedback. I'll see some code with incredibly obvious bugs and wonder how it managed to slide past the code reviewer... It seems the code review is treated as just another check box to get done fast rather than something that's important to do.

  • 1. refactor
    2. while you do that, divide up the code into modules that is a black box from outside
    3. refactor those boxes as needed (split into more as needed)

    and don't be afraid to do that before your program is finished, if it seems needed.

    The time you save on a refactor is often quite a lot, so you shouldn't be too afraid of doing it.

    Also making boxes like that helps testing.

    But then again, I thought that was already what most projects did.
    It's kind of a central point in most programming paradigms (both f

  • Don't be clever. Most of us aren't paid to be clever. Follow the KISS principle. Be kind to the maintenance programmers and keep classes and methods short and to the point. After all the maintenance programmer might be you. Methods more than 1 screen in size are suspect. Avoid lasagna code.

    Just a few rules I try to use.

  • Make your APIs sane, make ownership obvious and only abstract as far as strictly necessary. And for god's sake don't use PImpls - they might make headers cleaner but they make code twice as hard to maintain and debug.
  • 4 out of 5 of his suggestions were so simple the you could have gotten them out of any of the 10,000 blogs on 'improve' your programming, Refactor, use OOP, Unit Test and use Version Control. Any programmer that has more than an ounce of experience is already doing this.

    The fifth suggestion was the one that was just plain stupid. Using auto/var for declaring variables is the intellectual equivalent to Visual Basic's, Option Explicit Off. Sure you could do it but why?
    • There are cases in which "auto" is pretty much necessary in C++ code. There are cases where writing the type yourself would be cumbersome and error-prone. After that, those that work here start getting into disagreements.

      Really, sometimes you don't care about the type, if it's suited to hold the value.

  • Once I can't bear to look at my old code any longer, I don't even feel like investing the time in trying to bring it up to snuff. I just rewrite it, which usually works out well because I get more experienced over time and have thought of different approaches that could have been used originally. Fortunately I'm almost always the sole author and I deal mainly with embedded apps, so the code is fairly short. I'd never dare to use this approach with more complex programs, assuming I could even talk anyone int
  • Refactor strategy (Score:2, Informative)

    by swilver ( 617741 )

    When I want to refactor code, I first make sure we're working in a programming language that is suited for refactoring. That usually means it must be Java... nothing comes close in refactorability. It certainly rules out anything that isn't extensively checked by a compiler (eg. Javascript) -- there's always code paths that aren't covered in tests, and you rely on the compiler to warn you of potential problems in those.

    Second, I make sure there are good tests available, not just unit tests but also integr

  • Implement first, optimize later! Don't pre-optimize, because optimization usually introduces code complexity. A lot of the time your code will be "fast enough" or "small enough" to get the job done. Don't get too clever. Also, plan things out at least a little bit. Don't just start coding. Draw some pictures, talk through some use cases... try and ferret out and plan for some oddball corner cases before your testing finds them.
  • Dice hate aside, it really is a pretty lame click-bait article that could have been written by a bot. It's not bad to spark a discussion on Slashdot though so I'll bite. The first thing that comes to mind is DRY. Knowing when you are RY isn't always easy though, and there are some interesting tools out there that claim to be capable of detecting patterns via static analysis. I have to confess I haven't used them though. I'm wondering how big an obstacle to reduction is found in the "prestige" of "manag

  • "Tis a fine barn, but is no pool," Early Simpsons. Does you thing really need a blah--just because everyone else is doing it. Do we really need a internet connection for a notepad application? How much work is the "Managers" and now, the "Centers" doing?

    Just don't put useless crap no one needs in your software.

Writing software is more fun than working.

Working...