Slashdot Mirror


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

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?

142 of 197 comments (clear)

  1. Dice by ADRA · · Score: 1, Insightful

    Dice dice dice dice dice.. oh and add some dice.

    --
    Bye!
  2. How to simplify your code... by __aaclcg7560 · · Score: 1, Funny

    One line at a time.

    1. Re:How to simplify your code... by PRMan · · Score: 4, Insightful

      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)

      --
      Peter predicted that you would "deliberately forget" creation 2000 years ago...
    2. Re:How to simplify your code... by Forgefather · · Score: 1

      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. We lost the concept of simple well defined methods that do one thing and do it well.

      If I had the time to clean some of this up I would identify all of the most basic elements and start factoring them out of the code before making access methods that are distinct for every service that needs to use the back end. This would ensure less crossover of issues and minimize the impact of bugs while making the stack easier to follow based on where the information is coming from.

      --
      "There are lies, there are damn lies, and there are statistics"
    3. Re:How to simplify your code... by selectspec · · Score: 1

      Cut and paste.

      --

      Someone you trust is one of us.

    4. Re:How to simplify your code... by jofas · · Score: 1

      Yes, but why male models?

    5. Re:How to simplify your code... by istartedi · · Score: 1

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

      Some Perl maintainers would like a word with you.

      --
      For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
    6. Re:How to simplify your code... by Ravaldy · · Score: 1

      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 it's easier to read although it's probably lighter on the processing.

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

      Assuming a simple null = 0 check:
      object obj = 123;
      int somenum;

      Short:
      somenum = obj is int ? (int)obj : 0;

      Long:
      if (obj is int) somenum = (int)obj;
      else somenum = 0;

      I would argue the Long one is easier to read.

      You will end up using more libraries, which have been well-tested by others

      Modules not only allow better reading but as you stated improves reliability. It also enables better team work down the road.

      Your code will fit in the CPU cache, making it even faster/quote
      For interpreted languages yes, for compiled it's completely incorrect for most compliers. In .NET I could present to you a douzen line of code many .NET programmers use that is 500 times more taxing on the CPU than my 50 line routine (which has been modularized for reusability).

    7. Re:How to simplify your code... by swilver · · Score: 1

      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.

    8. Re:How to simplify your code... by budgenator · · Score: 1

      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.

      --
      Apocalypse Cancelled, Sorry, No Ticket Refunds
    9. Re:How to simplify your code... by Rinikusu · · Score: 1

      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."

      --
      If you were me, you'd be good lookin'. - six string samurai
    10. Re:How to simplify your code... by Ravaldy · · Score: 1

      I find them equally easy to read

      I do too but not everybody does. When asked on a MS forum, just over 25% of programmers said they were familiar with it and only 15% said they made use of it. So based on that my argument is valid but I'm sure you understood what I meant.

      You should just get some more experience with ?: constructs

      I use them often. I find them practical in properties. I use them in many other places but for some reason the way I modularize my projects, they often end up in get/sets.

    11. Re:How to simplify your code... by Ravaldy · · Score: 1

      If you modularize properly complex conditions disappear.

  3. Don't try to do too much in one program by QuietLagoon · · Score: 3, Insightful
    systemd fell into the trap of doing too much.

    .
    And then there is always this old chestnut... The Big Ball of Mud.

    1. Re:Don't try to do too much in one program by QuietLagoon · · Score: 1

      One could argue that "trying to do too much" has led to the sloppiness you cite. ;)

    2. Re:Don't try to do too much in one program by mattventura · · Score: 1

      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.

  4. How to deal by Rei · · Score: 4, Funny

    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!

    --
    He's the sort of person who would sell the Red Cross to Dracula.
    1. Re:How to deal by bobbied · · Score: 1

      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.....

      --
      "File to fit, pound to insert, paint to match" - Aircraft Maintenance 101
    2. Re:How to deal by PRMan · · Score: 1

      I really hate people like you. You take all the joy out of coding with your crap.

      --
      Peter predicted that you would "deliberately forget" creation 2000 years ago...
    3. Re:How to deal by phantomfive · · Score: 4, Insightful

      I think the code is a representation of the person. People who think clearly write clear code. Learn to think clearly.

      --
      "First they came for the slanderers and i said nothing."
    4. Re:How to deal by jofas · · Score: 2

      This doesn't address the part where you inherit someone ELSE's mess.

    5. Re:How to deal by phantomfive · · Score: 1

      This line of thinking implies that one never improves

      No. Please read the part where I wrote, "Learn to think clearly."

      --
      "First they came for the slanderers and i said nothing."
    6. Re:How to deal by phantomfive · · Score: 1

      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 become very clean, and you'll be able to work with the code easily and quickly.

      A constant need to refactor is a sign that something is wrong.

      --
      "First they came for the slanderers and i said nothing."
    7. Re:How to deal by phantomfive · · Score: 1

      I contend that one can always learn to think more clearly, and if one is constantly doing so then one's code will constantly be less clear than one is capable of writing.

      You are right, but there's a point where you are 'good enough'. Let me give an analogy:

      Traffic going onto the freeway can be bad, and if it gets too bad, then suddenly there is a slowdown, or even traffic jam. If the traffic is clear, then you can go the speed limit. The traffic can become more clear, but there is a point where it's "good enough."

      Of course, you should ask, "When is it 'clear enough' in software development?" I think Jim Shore has the answer. When your code is clean enough that you can operate in the sort of 'no bug' environment he describes, then there is still room for improvement, but you write good code at that point.

      --
      "First they came for the slanderers and i said nothing."
    8. Re:How to deal by jarrowwx · · Score: 1

      Amen. I would add, learn to think DIFFERENTLY. There is Imperative programming, which is to think like the computer, and tell the computer exactly what to do and how to do it. There is Object Oriented programming, which is really just an attempt to limit the amount of tangle you get into while writing an imperative program. And there is Functional programming, which tries to avoid the mess altogether, but can end up creating a different kind of mess, and if taken too far, makes the code even harder to read to a less experienced programmer. And lets not forget Logic Programming. Did I miss any? The point? A good way of enhancing your own ability to write less convoluted, buggy code is to learn to solve the same problem in all those different ways. The cognitive flexibility that it gives you will enable you to solve problems faster, with less code, and likely, less bugs.

    9. Re:How to deal by phantomfive · · Score: 1

      And lets not forget Logic Programming. Did I miss any?

      Stack based programming, table oriented programming, probably more lol
      Personally, I think Smalltalk does a nice job of finding the balance between the various methodologies.

      --
      "First they came for the slanderers and i said nothing."
    10. Re:How to deal by Darinbob · · Score: 1

      Don't mess with code from Texas.

    11. Re:How to deal by mikael · · Score: 1
      --
      Vintage computer adverts: http://www.vintageadbrowser.com/computers-and-software-ads
    12. Re:How to deal by david_thornley · · Score: 1

      Common Lisp covers imperative, object-oriented, and functional programming nicely, as well as C++-style generic programming with actual readable syntax. If you find another form of programming, you can make it support it (I've seen a module for logic programming). The downside is that you have to forego almost all syntax, and write code like a parse tree generated in a compiler, using parentheses to show the structure.

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
    13. Re:How to deal by Proudrooster · · Score: 1

      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.

    14. Re:How to deal by phantomfive · · Score: 1

      Lisp is really great I won't deny, and macros are without a doubt better than C++ style generic programming, but writing hygienic macros in Lisp is still a pain. We'll say almost readable syntax.

      And Smalltalk is without a doubt worth looking into. The best way IMO is to check out Squeak and play with it (there's a tutorial).

      --
      "First they came for the slanderers and i said nothing."
    15. Re:How to deal by Xest · · Score: 1

      Yeah, to be honest, in my experience, technical debt largely increases as developer competence decreases. A highly competent developer knows how to think through a problem well, and to build a solution that satisfies not just the requirement now, but is flexible enough to cope with potential future changes. A good developer doesn't just ask "How can I solve this problem?" they ask "How can I solve this problem in a way that'll be flexible enough to also solve future problems?". The amateur balks at that, they say, "But I don't have time to do anything other than fix the immediate problem!" and yet the reality is the flexible and future-proof solution is typically no more time consuming to implement than the quick hack to solve the immediate issue.

      So in my experience, a good developer just doesn't really leave much technical debt, they have the capability for clear thought as you say, and the knowledge and experience to solve a problem in a way that doesn't leave any (or at least leaves very little) technical debt behind in the first place.

      Typically, technical debt is usually a sign of poor architectural experience - many bad programmers scoff at software architecture, but really that's what software architecture does, it teaches you to think clearly through a solution to a problem and to do so in a way that shrinks or eliminates the technical debt that you leave behind.

      Learning a language teaches you how to write code, learning maths and algorithms give you a toolbox of solutions, and learning architectural concepts teaches you how to implement without leaving a trail of technical debt. Good programmers know to keep learning, but the best programmers know to keep learning both the soft and the hard skills - it's not about just learning a new language, or technology, or algorithm, you have to learn about things like design patterns, you have to know your respective language paradigm(s) and how to map problems to it, you need to know how to plan, how to think through a problem and produce a solution in a structured and methodical manner, and you need to know how to organise your code.

      For every SICP you should be reading a Mythical Man Month, for every K&R's The C Programming Language you should be reading the GOF Design Patterns book, and for every Introduction to Algorithms you should be reading a Software Systems Architecture. Personally I sympathise with those who don't want to or struggle to do this because I find the less technical side of things hard going as I find them less interesting and hence less captivating, but unless you fight your way through it you're only going to be half the developer you could and should be. You can't just learn one side of the equation and expect to be a great developer - there are plenty who think they are, but they're the ones thinking they're rocking through their list of tasks because they're awesome whilst leaving a massive trail of technical debt behind them for everyone else to clear up.

    16. Re:How to deal by Big+Hairy+Ian · · Score: 1

      Adopt Definition of Done that includes code quality and test coverage

      Police it like the Stazzi

      No more technical debt

      --

      Build a Man a Fire, and He'll Be Warm for a Day. Set a Man on Fire, and He'll Be Warm for the Rest of His Life.

    17. Re:How to deal by phantomfive · · Score: 1

      Yeah, to be honest, in my experience, technical debt largely increases as developer competence decreases.

      Yeah, I think that's true.

      --
      "First they came for the slanderers and i said nothing."
    18. Re:How to deal by DutchUncle · · Score: 1

      Encapsulating the ugliness just pours epoxy on the technical debt. Managers will always say "leave the old stuff alone, it works, just work around it", when the new features or spec-changes are totally different; or the bug that someone finally found indicates that the old stuff really DOESN'T work, at least not in all cases. Your comments about the danger of change are valid, but sometimes the only real solution is to rip something out and replace it. Otherwise it'll be painful forever.

    19. Re:How to deal by phantomfive · · Score: 1

      A lot of programmers get addicted to rewriting from scratch, and are often afraid of trying to understand old code. You are not one of those people.

      It's not always possible to rip out the old code and rewrite it. If a section of code took a team three years to write, it's going to take you a while to replace it, and you probably don't have that much time. "Encapsulate the ugliness" is a way to, as you poetically say, pour epoxy on it, neutralize it so it doesn't grow bigger, then over time, replace it. It's not a strategy that works in every situation, but no strategy is.

      --
      "First they came for the slanderers and i said nothing."
  5. Step 1 - Don't by mccalli · · Score: 4, Insightful

    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.

    1. Re:Step 1 - Don't by Fly+Swatter · · Score: 5, Insightful

      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.

    2. Re:Step 1 - Don't by mark-t · · Score: 3, Insightful

      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.

    3. Re:Step 1 - Don't by gstoddart · · Score: 4, Insightful

      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.

      --
      Lost at C:>. Found at C.
    4. Re:Step 1 - Don't by __aaclcg7560 · · Score: 2

      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.

    5. Re:Step 1 - Don't by phantomfive · · Score: 3, Insightful

      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.

      --
      "First they came for the slanderers and i said nothing."
    6. Re:Step 1 - Don't by bigpat · · Score: 1

      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.

    7. Re:Step 1 - Don't by Immerman · · Score: 1

      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 undertaking in its own right, but without it you can virtually guarantee that any major refactoring will create new and potentially rare and cryptic bugs.

      And sadly, if old code is ugly to the point of needing a dramatic refactoring - then it probably wasn't created along with a unit test suite designed to make refactoring easy.

      --
      --- Most topics have many sides worth arguing, allow me to take one opposite you.
    8. Re:Step 1 - Don't by Anonymous Coward · · Score: 1

      Simple solution...Don't refactor until you have a set of unit tests/functional tests that demonstrate the expected behavior of the code/component you're planning on refactoring. And don't let Business push you down that path without alerting them to the fact that this is a risk and that they need to acknowledge the risk, after which you can go ahead.

      If you're developing code on your own, learn how to write tests. Use other techniques like Design By Contract (pre/post conditions), design patterns, maintain decoupled codebase etc... IOC, etc...basically anything that allows you to work on a body of code and verify that behavior hasn't changed. And use modern techniques proven to give you confidence in your code that have evolved from over 40 years of software engineering.

      Software engineering isn't a new field, yet many times I've encountered new developers that think every problem they encounter is brand new. Strange. We fail to learn from the past.

    9. Re:Step 1 - Don't by david_thornley · · Score: 1

      What if you don't really know the expected behavior? What if you can only figure that out by refactoring until you can actually think about the code?

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
    10. Re:Step 1 - Don't by david_thornley · · Score: 1

      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.

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
    11. Re:Step 1 - Don't by budgenator · · Score: 1

      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.

      --
      Apocalypse Cancelled, Sorry, No Ticket Refunds
    12. Re:Step 1 - Don't by turbidostato · · Score: 1

      "What if you don't really know the expected behavior?"

      Don't refactor.

      Unless you mathematically can offer proof that your tweaking of the code is not going to change the output, in and out the expected input data boundaries, don't touch it. Of course, once you reach that point you *do* know the expected behaviour, don't you?

      And, if you are really, really *that* desperate for the change to come, make sure you can run in parallel your new version along the old with production data for a long enough time (sometimes that takes a whole year) to check for their outputs to be the same.

    13. Re:Step 1 - Don't by goose-incarnated · · Score: 1

      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.

      That's not really a unit-test though, is it? I call those things integration tests.

      --
      I'm a minority race. Save your vitriol for white people.
    14. Re:Step 1 - Don't by david_thornley · · Score: 1

      Depends on what I'm doing. If I'm changing something in the hole-threading code, it directly affects the gcode, which I can't really test without firing up one of the mills.

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
    15. Re:Step 1 - Don't by phantomfive · · Score: 1

      Well, I don't disagree with your main point, that some code is not worth the effort of writing comprehensive unit tests.
      However, it's worth pointing out that in this case, Uncle Bob suggests writing a stub function right before the command goes to the machine.

      I have no understanding of your code base though, so I'm not telling you what to do; I have confidence in your coding ability.

      --
      "First they came for the slanderers and i said nothing."
    16. Re:Step 1 - Don't by david_thornley · · Score: 1

      The problem with that diff is that we like to improve things, and unit tests are particularly valuable in that sort of situation. If I come up with something more efficient, the diff test is worthless because all it can show is that I changed something, which I already knew.

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
  6. Re:Dice sucks dick. by iced_tea · · Score: 3, Interesting

    Ok... it's DICE but I'll bite... What I have found: IF time allows, the technical debt can be revisited and cleared/reduced. Some schedules don't allow for this, but during non-peak times (like the week between Christmas and New Years) when stuff is slow, I like to revisit some of the bad places and do damage control.

    I think spotting these issues, and giving the developer enough time to re-visit the bad section of the code is ESSENTIAL to maintain a relatively clean code base.

    Code reviews can help, but the project deadline pressure-cooker usually prevails. My .02

  7. Fuck dice by Lunix+Nutcase · · Score: 3, Insightful

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

    1. Re:Fuck dice by jofas · · Score: 2

      They really are bad. Genuinely awful.

  8. fuck off dice by Anonymous Coward · · Score: 2, Insightful

    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 them well enough that they're invested in writing good stuff. You need to hire good people and provide your mediocre developers with good examples to follow. If your developers think they're going to be fired long before they have to maintain anything, they'll probably turn the shittiness up to 11 out of spite. if they anticipate quitting over compensation or overwork or work-life balance, how good is their code going to be? If they hate your guts because they're on a visa and getting taken advantage of, how good is the code going to be?

    1. Re:fuck off dice by Kellamity · · Score: 1
      This is the problem with our industry.

      No on wants to pay us enough to do things properly.

      No one wants to keep a bunch of developers around on a long term permanent basis, in case the work slows down. Better to get them on three months contracts, use them for the project's major development phase, then get rid of them. Just get more for the next project. The short termer's don't give a shit what kind of code they write, because they won't be there to maintain it, and they'll have another contract after this one. Then they'll write more garbage code, collect the bucks and move on.

      Yet no one is keen on the idea of having a permanent, well trained team who are invested in the quality of the product, even though it probably would be cheaper in the long run. But most projects run on a 'money now' basis.

      Then there's the look from the project manager you'll get if you say at stand up, "yesterday I re-wrote a bunch of existing code." They need to understand that's not a waste of time.

  9. I don't. by Anonymous Coward · · Score: 1, Insightful

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

    You get the job done as fast as possible and let the Indians worry about it when they get it.

    See, you'll be on a project with an impossible deadline; all the while upper management has been wined and dined by the Tata/WiPro/CSC sales people and are gonna offshore the project for the production and maintenance phase. And many are just offshoring everything.

    So, get your stuff done on time, learn everything you can and find another job. Because if you stick around, you'll be canned and when you are unemployed in this profession, you are unemployable - if you're any good, you'd have a job.

    And do what you can to get into management before you're 35.

    And if you're really smart, you won't fall for this STEM career hype.

    1. Re:I don't. by Mats+Svensson · · Score: 2

      Oh, and don't forget to always tell everyone how much being a dev sucks. Put a big "BIG SNAKES INSIDE!"-sign up on the tree-house,to keep new kids out.

  10. technical debt vs. simplification - wha? by xxxJonBoyxxx · · Score: 2

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

  11. When your question gets closed by SO by phantomfive · · Score: 4, Insightful

    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?"

    --
    "First they came for the slanderers and i said nothing."
    1. Re:When your question gets closed by SO by phantomfive · · Score: 1

      The Peter principal says that all 'professional' programmers will be asked to do things more and more complicated.

      Donald Knuth discussed this, and said that you keep doing harder and hard things, things you've never done before, and that is why you can't write perfect code.
      The upside is, your skills keep getting better, and that's what keeps programming fun.

      In practice, you'll probably just end up writing yet more web services.

      --
      "First they came for the slanderers and i said nothing."
    2. Re:When your question gets closed by SO by mark-t · · Score: 1

      The Peter principle is only applicable here insomuch as a developer is not capable of learning from mistakes.

      Everyone makes mistakes... But if they overcome those mistakes and learn from them, then they may continually take on challenges of ever-increasing complexity and not cap out on their skills until retirement.

    3. Re:When your question gets closed by SO by Darinbob · · Score: 1

      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.

    4. Re:When your question gets closed by SO by phantomfive · · Score: 1

      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.

      --
      "First they came for the slanderers and i said nothing."
    5. Re:When your question gets closed by SO by Darinbob · · Score: 1

      Why, were its pants falling down?

  12. Goto by Anonymous Coward · · Score: 5, Funny

    has a go-to technique

    How did they know my technique!?

  13. Re:be smart by bobbied · · Score: 1

    Just finished "Hello World" then eh? Good for you, time for the next example in the tutorial...

    --
    "File to fit, pound to insert, paint to match" - Aircraft Maintenance 101
  14. Number 1 way to simplify your code: by hey! · · Score: 2

    Understand the problem it addresses better.

    --
    Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
  15. And in related news... by dark.nebulae · · Score: 3, Funny

    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.

    1. Re:And in related news... by Krishnoid · · Score: 2

      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 lot of writers let their source material get out of control, and trying to plan beforehand doesn't necessarily prevent the work from getting overcomplicated. It seems like every writer has a go-to technique (or four) for keeping things a little more streamlined. What are yours?

  16. Make it as simple as possible, but no simpler by Anonymous Coward · · Score: 1

    Next!

    Kidding aside, simplicity is the art in programming. It comes from understanding, not methodology. The question is similar to the one posed to Michelangelo: "How do you know what to cut away?" And the correct response is about as useful as Michelangelo's: "I just remove everything that doesn’t look like David."

  17. Best way to simplify? by Rob+Lister · · Score: 1

    Eliminate error handling.

    1. Re:Best way to simplify? by Anonymous Coward · · Score: 1

      use shorter names for variables and functions
      remove comments that just make it hard to read the code
      for functions use a varcache instead of returning a cumbersome data structure that you don't want or need

    2. Re:Best way to simplify? by The-Ixian · · Score: 2

      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.

      --
      My eyes reflect the stars and a smile lights up my face.
    3. Re:Best way to simplify? by david_thornley · · Score: 1

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

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
  18. Stop, Dice. by crow_t_robot · · Score: 2

    No one, absolutely no one, wants to read your shit articles. Stop pumping them into the feed.

  19. MIne were all blocked by Sarbaynes Oxley by Maxo-Texas · · Score: 2

    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 to argue for code cleanup a couple times a year as a team lead than as a programmer because we had two people saying it would be beneficial.

    But...

    *Changing non-meaningful variable names
    acnum to AccountingCustomerNumber
    This was the number one way I helped other programmer's fix their bugs. I would just ask- what's this- okay rename it. what's that- okay rename it. And after a short time (20? 30?) minutes they would see the bug themselves. After comments like, "Why do I need a long name- we only use this variable a few times.

    Refactoring any routine where the actual code was over a page in size into subroutines.

    Running performance tools to locate "hot spots".

    --
    She was like chocolate when she drank... semi-sweet at first and then increasingly bitter.
    1. Re:MIne were all blocked by Sarbaynes Oxley by phantomfive · · Score: 1

      I went into management. Programming ceased to be engaging. it was easier to argue for code cleanup a couple times a year as a team lead than as a programmer because we had two people saying it would be beneficial.

      Yeah, I learned the hard way that sometimes it's better to become a manager, even if you don't want to, because otherwise bad managers will make decisions for you.

      --
      "First they came for the slanderers and i said nothing."
  20. Top piece of advice... by Junta · · Score: 1

    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.

    --
    XML is like violence. If it doesn't solve the problem, use more.
  21. Answer is not in the code by postmortem · · Score: 2

    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.

    1. Re:Answer is not in the code by phantomfive · · Score: 1

      Unit tests or no, you're still going to get lousy code from lousy programmers, and good code from good programmers (I think that is the point you were trying to make).

      --
      "First they came for the slanderers and i said nothing."
  22. Re:Dice sucks dick. by ShanghaiBill · · Score: 4, Insightful

    When I take shortcuts because I am in a hurry, I try to leave breadcrumbs. I put comments that start with the string "FIXME" and then write a quick sentence or two explaining how I would do it if I had more time. Then later, when I do have time, I can just grep for "FIXME" and find a list of things that need to be fixed. Those comments save me a lot of time, because I have an explanation from when it was still fresh in my mind, preventing many "WTF moments".

  23. Instead of click-bat here are some real sources... by AlanBDee · · Score: 4, Insightful

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

  24. Re:Dice sucks dick. by fph+il+quozientatore · · Score: 2, Insightful

    Dice.com sucks big dicks.

    +4 insightful? Is everyone with moderation points 14 year old?

    --
    My first program:

    Hell Segmentation fault

  25. Do we want to? by monkeyxpress · · Score: 1

    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 is a stupid system, but I can't really see it being changed any time soon. Sometimes I imagine the accountants/lawyers who pretty much run the economy just have a big laugh at idealistic programmers trying to do 'good' in their jobs.

    My advice is that if you want to write good code, go work for yourself, where you can profit directly from reducing the time it takes you to maintain your programs. Otherwise, my advice is work for a really big hourly rate and don't get conned by 'job security' and a foosball table.

  26. Re:be smart by Anonymous Coward · · Score: 2, Interesting

    #include main() { long long P = 1, E = 2, T = 5, A = 61, L = 251, N = 3659, R = 271173410, G = 1479296389, x[] = { G * R * E * E * T , P * L * A * N * E * T }; puts((char*)x); }

  27. Re:I don't understand. by Anonymous Coward · · Score: 5, Insightful

    I think what everybody is hating on is the undisclosed relationship. Nerval's Lobster is a shill account. This is not ethical business practice.

  28. Two things by DFDumont · · Score: 4, Interesting

    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?

    1. Re:Two things by phantomfive · · Score: 1

      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.

      --
      "First they came for the slanderers and i said nothing."
    2. Re:Two things by Anonymous Coward · · Score: 1

      Yes to this x 1000. This is one of those gems of truth one only truly can appreciate after 30+ years of experience. Often there's too much emphasis on simple examples, with variable names like "acc" or "accno" instead of "deposit_account_number". There's no effort or time wasted for someone proficient in typing on a keyboard, not compared to the potential errors and confusion that ambiguous names can provoke later.

      In fact, any serious program should really have a domain dictionary of definitions, that directly ties in to the core business logic and explains the terms in a clear and unambiguous manner. Then, there will never be a confusion what is meant, and you will be using the same terminology as the customer / business people. The only problem is when you need to integrate between two domains with slightly different terminology, but there are rare exceptions when names really do conflict in unexpected ways. Thus, with such an initial investment in clarity, you will spend less time thinking of and remembering obtuse names, and can get on with business.

      Too often, people think commenting code should read like "iterate over all i's here", when the code is really stating exactly the same thing.
      Instead, comments should only be offered about conditions and thoughts that is not expressed in code, but which can help to clarify limitations, design-choices, dependencies, duplications etc.

      Regarding libraries, seasoned programmers have learnt to fear dependencies. If not truly bringing much value, it's often simpler just to write the code yourself, even if it's a duplication of effort. Less dependencies, mean less possibilities for unexpected failures, breakage or slow-downs from tying too many strings together at the same place, which can be a very bad design choice.

    3. Re:Two things by mark-t · · Score: 1

      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 it does and how it works should be transparently obvious to someone reading the code itself. All code submissions are reviewed by a peer or superior before being committed to the master repo, and the system actually seems to be working quite well.

    4. Re:Two things by Darinbob · · Score: 1

      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.

    5. Re:Two things by Hognoxious · · Score: 1

      The code tells you what the code does. The comments tell you why.

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    6. Re:Two things by mark-t · · Score: 1
      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 reads the comment and misunderstands what the code is doing and ends up being the source of dozens of hours of wasted time. If programmers were instead forced to read the code, this would not have happened. If the code is clear, functions are kept small enough that what they do is transparently obvious, and identifiers are given descriptive names that reflect their purpose, then it should take very little time for a fluent programmer to understand even a potentially very long program fragment.

    7. Re:Two things by i.r.id10t · · Score: 1

      So you mean that since I have to work with data provided by a group that doesn't believe in validating input I shouldn't do something like /*
      this is here 'cause the fucktards in G building can't bother to validate
      input before it hits the data warehouse. Don't trust any data provided by
      them to be in the proper format, etc.
      */
      if (filter_var($email, FILTER_VALIDATE_EMAIL)) { .....
      }

      --
      Don't blame me, I voted for Kodos
    8. Re:Two things by Hognoxious · · Score: 1

      Another new programmer comes along and reads the comment and misunderstands what the code is doing

      I hope you're better at reading code than you are at comprehending English.

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    9. Re:Two things by mark-t · · Score: 1

      The reason for validating user input should be self-explanatory: you do not otherwise have any control over whether it may be valid as input to lower level routines. That the variables involved were user input should be clear from the identifier name that reflects that content, and that the purpose behind the function to validate an email address is to ensure that its input is clean should be clear by its name as well.

      Because modern IDE's have variable name completion, long identifiers do not really significantly increase the likelihood of errors as they might have at one time.

    10. Re:Two things by mark-t · · Score: 1

      Understanding exactly what a function is supposed to do in the first place is the first step to understanding why the function is even there. If the code is clean, elegant, and concise, you do not need a comment to clarify that point.... and all that adding a comment does is increase the chance that if the code should ever change, the comment may get deprecated without anybody noticing, and later the code may be misunderstood by another programmer because the comment no longer reflects what a maintainer may have needed to know about the function.

    11. Re:Two things by Hognoxious · · Score: 1

      The reason for doing it in general is self explanatory. The specifics frequently aren't.

      //fuckheads in sales can't type
      if ! numeric(orderQuantity) then
          transform(orderQuantity,'Ii|1;Oo|0'

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
  29. Re:Dice sucks dick. by fahrbot-bot · · Score: 4, Funny

    Dice.com sucks big dicks.

    +4 insightful? Is everyone with moderation points 14 year old?

    Apparently, and it ignores the simple fact that Dice probably sucks small and medium dicks as well.

    So, in keeping with the thread topic, I'll simplify the original statement: Dice.com sucks dicks.

    --
    It must have been something you assimilated. . . .
  30. modules, boxes, refactor by Mirar · · Score: 1

    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 functional and object oriented).

  31. code reviews by lcall · · Score: 3, Informative

    I agree about code reviews: in fact I consider them essential in a team environment and wouldn't want to work in a code base where they will not be consistently held, at least going forward. Then the team can agree on some kind of standards and I recommend that the team develop a checklist for things the reviewer should check, where near the top of the list is: "Would I want to maintain this, and could I understand it easily if I came back to it years from now?". Also somewhere on the list is: "How was this tested?". Nothing ever gets into the master branch without such a review. Ideally the review is asynchronous, at least the first pass, to help see if the code is clear without its author explaining it.

    Also, the coder should review his own code first with that in mind, before sending it to someone else to review.

    Otherwise code becomes a mess. On a team small enough to enforce it, things can go much better.

    --
    A Free, fast personal organizer for touch typists: onemodel
  32. Re:Dice sucks dick. by serviscope_minor · · Score: 1

    Dice.com sucks big dicks.

    I'm guessing that Dice then is making someone or some people quite happy. A lot of guys seem to devote considerable effort towards getting their dicks sucked, so I don't really see how it's a bad thing

    --
    SJW n. One who posts facts.
  33. Re:Dice sucks dick. by Anonymous Coward · · Score: 1

    If you're gonna suck dicks, GO BIG OR GO HOME

    Dice.com went big, and OP was recognizing their bravery and determination.

    Cheers, OP, I'm with you!

  34. Re:Dice sucks dick. by phantomfive · · Score: 1

    but during non-peak times (like the week between Christmas and New Years) when stuff is slow

    Best week of the year because no one is there, and you can work on whatever you want.

    --
    "First they came for the slanderers and i said nothing."
  35. Keep it simple by plopez · · Score: 1

    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.

    --
    putting the 'B' in LGBTQ+
  36. More art than science by Anonymous Coward · · Score: 1

    Any principle that is good most of the time can be mis-applied. I have worked with developers who loved linq and would use it to compact loops and such down to a line or two of completely impenetrable gibberish. The long-term maintenance cost significantly outweighed the elegance of dearth.

    I have also seen a simple multi-step script be broken out into a series of objects with an inheritance hierarchy...what was previously 50 some-odd lines of simple and straightforward code became 200 lines broken out over three files, with a slight reduction in performance (we tested it for that), and a bug was introduced in the process.

    Whatever it is you plan to do...make sure you have a good reason for doing it, that whatever rules you are following actually make sense in your specific context, and that you have it all covered by good testing.

  37. Remember that most code is white space by Anonymous Coward · · Score: 1

    Just delete all white space and line feeds and your code will be much more stream lined. Removal of all comments will also significantly improve information density as well.

  38. Re:Dice sucks dick. by DigiShaman · · Score: 1

    It's a feedback loop. Post stories in a manner that treats its readership like 14 years old, and we'll act 14 years old; which I'm fine with BTW cause being old sucks ass.

    --
    Life is not for the lazy.
  39. That's easy by EmagGeek · · Score: 1

    Write it in assembly.

  40. Cull the herd by Anonymous Coward · · Score: 1

    You should aggressively get rid of developers who 'make a mess' in order to 'get things done'. Such people are outwardly productive but are ultimately a negative for your project because you have to rewrite their garbage. Recognize them as early as possible.

  41. In complement, assume you do NOT understand it by raymorris · · Score: 2

    > 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 anything about what the code did. Basically, I saw something like this:

    for (i=0; i = 1_000_000_000; i++) {
            foo = 'bar';
            fi = 'bee';
            printf(foo, fi); ...
    }

    I could change that to this and know it was write, without understanding anything:
    foo = 'bar';
    fi = 'bee';
    for (i=0; i = 1_000_000_000; i++) {
            printf(foo, fi); ...
    }

    Similarly I could cut-paste blocks of code into functions, without caring what that block of code did - I only cared about which variables it accessed.

    Or when I saw this:
    cnm = get_customer_cumber()
    I could then rename the variable via search and replace to cnm to customer_number throughout the scope. I don't know or care what a customer number is, but I know "cnm" means "customer_number", so I can do that search and replace.

    So I'd say you can choose to either a) understand the code well or b) assume you don't understand it at all, and therefore make provably equivalent transformations, such as renaming, properly extracting functions and subroutines, etc. What's dangerous is when you make changes based on an imperfect understanding, when you -think_ you know what the code does, but you're wrong. You can go a long way while knowing that you don't understand it.

    1. Re:In complement, assume you do NOT understand it by phantomfive · · Score: 1

      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."

      --
      "First they came for the slanderers and i said nothing."
  42. Best way to code in C++ by DrXym · · Score: 1

    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.

  43. Re:Dice sucks dick. by Anonymous Coward · · Score: 1

    Taking a little longer to do the job right first time is a great idea, but if the boss is a micromanager who wants everything done yesterday it just will not happen that way. The only way in this case is to leave yourself clues to ease the pain when the next disaster hits.

    I'm being a little unfair though: most bosses are actually not that bad (though micromanaging imbeciles do exist). However what most bosses do not understand, in my experience, is the value of *thinking* about how to write the code. Not brainstorming, not googling like a million demented monkeys hammering on a million typewriters, but stopping for a brief time, staring blankly into space and just thinking about "how can I do this right?". This sort of introspection is the best way to write good code first time, and it's also almost guaranteed to get the boss on your back asking why you're not working and making inane suggestions about talking to golden boy two desks over.

  44. Re:Dice sucks dick. by sjames · · Score: 1

    What you suggest is the right way to do it, but it depends on having time allocated to doing it the right way and a manager who gives a crap about anything but squeezing out more features faster.

    Otherwise, you become just that guy who never meets the deadline. Shortly after, you become the former occupant of cube 230B.

  45. incentive code removal ... by whh3 · · Score: 1

    .. as much as some companies incentive code addition. If a programmer is paid using a metric of LoC then, I think, something is wrong. There is just as much work done in removing code as there is in adding it.

    The flipside is important, too, though: Just rewriting good eloquent code with "clever" oneliners is absolutely wrong.

    Code that has to be there should be eloquent and well-documented. Code that does not need to be there should be removed.

    --
    remove nospam. to email!
    1. Re:incentive code removal ... by whh3 · · Score: 1

      Of course I mistyped. My subject line should have been "incentivize".

      --
      remove nospam. to email!
  46. Stupid by byteherder · · Score: 1

    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?

    1. Re:Stupid by david_thornley · · Score: 1

      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.

      --
      "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
  47. Re:Dice sucks dick. by JoeMerchant · · Score: 2

    Or just write it correctly the first time? I know it may be harder and more time consuming, but you'll get further in your career if you do.

    Depends, in R&D I write an awful lot of throwaway code - maybe as much as 80% (depending...) but, at the outset, I can't tell you which 20% will be kept and used in the product and which 80% ends up being "investigatory."

    Sure, you could just rewrite the 20% from scratch and "do it right," but that's not as efficient as reusing the proven test mules - which usually aren't in too bad of shape, if you trim off the FIXME: and TODO:s.

    In my career, being able to show working code, quickly and easily, is important - much more concrete than sitting in a meeting and drawing bad sketches on a whiteboard while waving hands and attempting to explain things to people who all visualize verbal explanations differently.

  48. Rewrite it by John+Jorsett · · Score: 1

    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 into letting me.

  49. Re:A More Radical Position by mark-t · · Score: 1

    When you have 10,000s of lines of glue code, to glue your systems together, and you're actively maintaining them against one another, ... and the alternative was to write a 500 line program that would do EXACTLY what you want, and is easy to modify and understand, ... ... something has gone horribly, horribly wrong.

    Obviously, but if computer programs are written by humans, who are, unfortunately imperfect, and make mistakes. Sometimes we don't think of everything right away, and a better solution may simply not be known at the time of initial implementation. That's not anybody's fault.

    Anyone who expects a good programmer to be someone who never make mistakes (or at least who has already made all of the mistakes they ever will by now) and will never have to sometimes do something completely over again from scratch because they did it wrong is living in a fantasy. A good programmer is not someone who doesn't make mistakes, it is someone who can *LEARN* from the mistakes that they do make.

  50. Re:Dice sucks dick. by Darinbob · · Score: 1

    Best thing I think, which will never happen, is to keep the work load light so that the team has actual time to spend making the code better in the first place as well as time to go back and rewrite older code. But too often everyone's on a death march to meet deadlines, you can only add features and fix bugs and any redesign or rewriting isn't assumed to help the bottom line. A lot of bad code I see is not because the programmer is bad but because they're being forced to add the code quickly and move on to the next task quickly.

  51. Refactor strategy by swilver · · Score: 1, Informative

    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 integration tests. This is usually the case on projects I work on, or I won't be sticking around for long.

    Third, I do refactors in tiny incremental steps. Usually it's like "remove one method", "remove a parameter", "add/remove an interface", "delete a class", "split a class", "move a method", "make a parameter required by moving it to a constructor", "make something immutable by removing its setter".

    As soon as you do one of those, there are gonna be errors detected by the compiler. I ignore the ones in tests and quickly check the ones in real code to see if the refactoring does not have something I did not foresee that would be tough to fix. If there's something unforeseen, I think about what refactoring would be need to be done before this one that would make that easier to fix later.

    Once it looks like it will work, I fix the errors in one class, then in its test, then run the test to see if nothing broke. Then I go to next class, until all the errors are gone (usually this takes around an hour for 50-200 errors when I started).

    I then run all the tests, and if everything is ok, I make a commit of that refactor step. Then I start with the next incremental refactor step. At any time, I can merge the stuff with master and stop and work on something else, while still having some small benefits of the refactorings done so far.

    In this fashion I've refactored existing code bases to use a different time/date system, refactored code to use two different models (instead of a unified one), made models slowly immutable (it's amazing how many problems you discover when you start doing that), etcetera.

  52. Re:Judicious use of Pimpl by DrXym · · Score: 1

    If you need to aggressively hide the implementation there are other ways than doubling up the number of definitions and classes. Pimpls are just annoying, particularly when they're in code which has no reason to use them - I could sort of understand the purpose if the class was a library of some kind but I've encountered them in internal code where their only purpose is to be a pain in the ass when the class(es) need to be modified.

  53. Implement first, optimize later... by cplusplus · · Score: 1

    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.

    --
    "False hope is why we'll never run out of natural resources!" - Lewis Black
  54. Re:be smart by david_thornley · · Score: 1

    Nice work in keeping the first product just below 2^63 - 1, and avoiding undefined behavior that way. However, it looks like it will only work in a little-endian environment.

    --
    "When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
  55. YOU WIN THE INTERNETS. by tlambert · · Score: 1

    YOU WIN THE INTERNETS. That is all.

    Seriously, funniest thing I have seen in days!

  56. Re:Dice sucks dick. by ShanghaiBill · · Score: 2

    What you suggest is the right way to do it

    It is almost never the right way to do it. Specs change, or are incomplete, or don't even exist. So it is better to hack up something quick, make sure it is what the customer (or your boss) actually wanted, and then go back and do it "right". It is silly to waste time making code "perfect" when it most likely will be thrown out.

  57. Dice hate aside... by istartedi · · Score: 1

    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 "managing millions of lines of code". If somebody came along, audited it, and told them it was really just a massive macro expansion that came from 2500 lines, they might not be so happy.

    --
    For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
  58. Re:Dice sucks dick. by sjames · · Score: 1

    That also depends on management. If the management is any good, they'll make it clear when a spec should be treated as final or tentative. They'll also give you time to do go back and re-do it right if/when it becomes final.

    Otherwise, you have no idea if it is fixed or not and you will NOT get a chance to replace the spit and baling wire later.

  59. Don't Put Extra Crap in It by BrendaEM · · Score: 1

    "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.

    --
    https://www.youtube.com/c/BrendaEM
  60. The best way? by Namlak · · Score: 1

    Change jobs!

  61. Re:Dice sucks dick. by turbidostato · · Score: 2

    "What you suggest is the right way to do it, but it depends on having time allocated to doing it the right way and a manager who gives a crap"

    On one hand, you already have been told that's not usually "the right way to do it" since allowing for features to go along and see, once they are tested in real world, which ones will stay and which ones will not is usually the best way to go.

    On the other hand, unless your manager is both a micromanager *and* technically competent, don't think about what your manager can do for you but what can you do for your manager.

    If you think a bit about it, he's completely at your mercy and the code can not be "done" till you make it "done". No, not when you *say* it's done, but when you *make* it done: don't think about refactoring the code and refactor the way you write it instead, and even if your manager is the kind of "you say it's a mock up, but it looks good enough for production to me", if there's no box, no screen, no output, it won't be done even for him. Instead of coding "the happy path" first and then go after the corner cases (and never have time for the corner cases), go with the inner parts first and make your code so it doesn't do anything useful till you deem it good enough (and don't fool yourself: it's probably "good enough" quite before you usually think).

  62. The right way, the wrong way, the army way by c.r.croitoru · · Score: 1

    Each time you rewrite a function in a different way the inherent risk of bugs increases. As such, you'd want to undergo all the sdlc retesting, which does add overhead...

  63. Code metrics by drolli · · Score: 1

    Use Sonar or other code checkers.

    After you resolve the critical things (i.e. circular dependencies) etc there, life will be simpler.

  64. Terse !== Short by tomxor · · Score: 1

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

    Assuming a simple null = 0 check: object obj = 123; int somenum;

    Short: somenum = obj is int ? (int)obj : 0;

    Long: if (obj is int) somenum = (int)obj; else somenum = 0;

    I would argue the Long one is easier to read.

    Short does not mean try to condense it... you can stick everything on one line to achieve that and it will be the most illegible and hard to read format.

    Ternary conditions are not a way to make your code short, you should consider them equal in length conceptually but more concise - that can be good or bad depending on the complexity of the statement.

    That's not to say there is no value in trying to keep some things concise for legibility, but there is a difficult balance between terse and concise when doing this... I think the important thing is to focus on clarity, this other attributes are just ways to achieve that, they should not be used for their own sake:

    Short, concise, simple (as possible) and DRY can help achieve clarity; using single letter variables and ternary statements for everything will achieve a short terse and unclear mess.

    1. Re:Terse !== Short by Ravaldy · · Score: 1

      I think the important thing is to focus on clarity

      But that was the point I was trying to make without writing 100 lines of code in a /. comment.

      The argument I was making is that shorter is not equal better maintainability or readability. It fitting on the screen is not equal readability. I think it's more important to comment properly than to shrink the code.

  65. make it even more complex by anyaristow · · Score: 1

    Judging from the way most programmers "refactor", the solution to complex code is to replace it with even more complex code, because something that employs as many technologies, buzzwords and frameworks-of-the-week is obviously better.