Stories
Slash Boxes
Comments

News for nerds, stuff that matters

Slashdot Log In

Log In

Create Account  |  Retrieve Password

Any "Pretty" Code Out There?

Posted by kdawson on Sat Jul 14, 2007 07:30 PM
from the prettyprinting-doesn't-count dept.
andhow writes "Practically any time I hear a large software system discussed I hear "X is a #%@!in mess," or "Y is unmanageable and really should be rewritten." Some of this I know is just fresh programmers seeing their first big hunk o' code and having the natural reaction. In other cases I've heard it from main developers, so I'll take their word for it. Over time, it paints a bleak picture, and I'd be really like to know of a counterexample. Getting to know a piece of software well enough to ascertain its quality takes a long time, so I submit to the experience of the readership: what projects have you worked on which you felt had admirable code, both high-level architecture and in-the-trenches implementation? In particular I am interested in large user applications using modern C++ libraries and techniques like exception handling and RAII."
+ -
story
This discussion has been archived. No new comments can be posted.
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More
Loading... please wait.
  • sure (Score:5, Funny)

    by buswolley (591500) on Saturday July 14 2007, @07:32PM (#19862767) Journal
    Hello World!!!
    • Hello World (Score:5, Funny)

      by MillionthMonkey (240664) on Saturday July 14 2007, @07:45PM (#19862863)
      public interface MessageStrategy {
              public void sendMessage();
      }

      public abstract class AbstractStrategyFactory {
              public abstract MessageStrategy createStrategy(MessageBody mb);
      }

      public class MessageBody {
              Object payload;
              public Object getPayload() { return payload; }
              public void configure(Object obj) { payload = obj; }
              public void send(MessageStrategy ms) {
                      ms.sendMessage();
              }
      }

      public class DefaultFactory extends AbstractStrategyFactory {
              private DefaultFactory() {}
              static DefaultFactory instance;
              public static AbstractStrategyFactory getInstance() {
                      if (null==instance) instance = new DefaultFactory();
                      return instance;
              }
              public MessageStrategy createStrategy(final MessageBody mb) {
                      return new MessageStrategy() {
                              MessageBody body = mb;
                              public void sendMessage() {
                                      Object obj = body.getPayload();
                                      System.out.println(obj.toString());
                              }
                      };
              }
      }
      public class HelloWorld {
                  public static void main(String[] args) {
                              MessageBody mb = new MessageBody();
                              mb.configure("Hello World!");
                              AbstractStrategyFactory asf = DefaultFactory.getInstance();
                              MessageStrategy strategy = asf.createStrategy(mb);
                              mb.send(strategy);
                  }
      }
      • license (Score:5, Funny)

        by MillionthMonkey (240664) on Saturday July 14 2007, @07:53PM (#19862939)
        Ooops, I almost forgot:
        /*
              Hello World
              Copyright 2002 MillionthMonkey

              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at

                      http://www.apache.org/licenses/LICENSE-2.0 [apache.org]

              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
        */


        You're welcome, "World"!
      • by smitty_one_each (243267) * on Saturday July 14 2007, @08:03PM (#19863011) Homepage Journal
        This is such an exquisite example of design pattern overkill that I may require a private moment.
        • by Tablizer (95088) on Saturday July 14 2007, @08:12PM (#19863079) Homepage Journal
          This is such an exquisite example of design pattern overkill that I may require a private moment.

          It is the Gang-of-four Job_Security_Strategy pattern. Only the author can figure out their own code like this, and if you get paid per volume of code, you get wealthy.

               
            • Re:Hello World (Score:5, Informative)

              by MillionthMonkey (240664) on Saturday July 14 2007, @08:38PM (#19863285)
              Not so secure when the company is sued for stealing source code. He took credit (with his copywright notice) for a very old joke. A blatent copy-and-paste. One has to wonder how much of that he does on the job.

              Ha ha, joke's on you, you dick- that "old joke" was written by me five years ago [slashdot.org] as part of a larger post and I was not at work- in fact it was way after hours and I was about to go home. I just started with the base concrete implementation and this is what it looked like after a few minutes of stuffing patterns into it- Singleton, Factory, and Strategy. I keep thinking one of these days I'll release a 2.0 version with Proxy and Bridge. Since I was the original author I retain the right to paste it wherever I want and to attach any license agreement I feel like attaching.

              This has become the most famous code I've ever written which is the sort of thing that makes you reflect on your career. So far it has netted me about 20-30 karma points over the years (lord knows how much karma was gotten from pirated copies). I found it being examined in some software engineering papers and it even made its way into one of the patterns books [powells.com] (as an example of "Patterns Happy" code). When I found out about that, I made the guy send me a free copy and acknowledge me in print so I can maybe net some jobs unnecessarily screwing up simple code with GoF patterns which always pays well. Now that I released it under the terms of the Apache license he might come back for his book.
      • by owlstead (636356) on Saturday July 14 2007, @08:27PM (#19863207)
        /** Look, ma, no literals */
        public class Hello_World {
          public static void main(String ... args) {
            System.out.println(Hello_World.class.getSimpleName ());
          }
        }
      • by ookabooka (731013) on Saturday July 14 2007, @09:27PM (#19863583)
        I spent about an hour on this, but I think it's funny. There was no way to get this past the lameness filter, so I used nopaste: http://rafb.net/p/D1f39951.html [rafb.net]
        Here is a little teaser though :)

        /**
        * This program is an elaborate joke about the strucuture of the Java
        * programming language. Technically you'll have to put all the
        * public interfaces and classes in their own file to get it to
        * compile. The actual code came from a slashdot post, comments were
        * later added by ookabooka.
        *
        * Originally Copyright 2002 MillionthMonkey.
        *
        * Ridiculously verbose and mostly useless comments (AKA good
        * commenting) added by ookabooka Copyright 2007.
        *
        * Licensed under the Apache License, Version 2.0 (the "License");
        * you may not use this file except in compliance with the License.
        * You may obtain a copy of the License at
        * http://www.apache.org/licenses/LICENSE-2.0
        * Unless required by applicable law or agreed to in writing,
        * software distributed under the License is distributed on an "AS IS"
        * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
        * or implied. See the License for the specific language governing
        * permissions and limitations under the License.
        *
        * TODO:
        * Add some try/catches and a plethora of exceptions to further insult
        * Java.
        *
        * @author ookabooka
        * @version 2.41.54b_2-rc4
        * @see http://ask.slashdot.org/article.pl?sid=07/07/14/20 11208
        */
  • New Law? (Score:5, Insightful)

    by VGPowerlord (621254) on Saturday July 14 2007, @07:34PM (#19862779) Homepage
    The cruftiness of source code is directly proportional to the amount of time spent working on it times the number of people working on it.

    Has someone created such a law before?
    • Re:New Law? (Score:5, Interesting)

      by Anonymous Coward on Saturday July 14 2007, @08:07PM (#19863041)

      The cruftiness of source code is directly proportional to the amount of time spent working on it times the number of people working on it.

      I think you meant the cruftiness of source code is direcly proportional to the number of people working on it DIVIDED BY the amount of time spent working on it.

      This explains why commercial source code produced by large teams of programmers under tight arbitrary deadlines tends to be sloppy. Source code produced by passionate hobbyists under the "we'll release it when it's done" deadline perspective tends to be cleaner.

  • what? (Score:5, Funny)

    by joe 155 (937621) on Saturday July 14 2007, @07:40PM (#19862821) Journal
    "Practically any time I hear a large software system discussed I hear "X is a #%@!in mess,"

    I get that with reading the next line you get the context, but was I the only one taken aback at this seemingly blatant flame of our beloved X?
  • Inconsistency (Score:5, Insightful)

    by Anrego (830717) on Saturday July 14 2007, @07:45PM (#19862867)
    I find the thing that really makes code unreadible is inconsistency. This is particularly true of languages like C++ where there is no well defined one true coding convention. If all your code is in house, this is not such a problem, because you can define your own coding convention and stick to it. If however you are relying on other libraries, chances are your going to end up with one library that names its function like_this, and one likeThis, and another fnct_LikeThis ...

    Worse is when you don't even define a coding convention for the code you throw into the mix. Now you have libraries with inconsistent naming, and multiple developers all using their own favorite notation.

    Additionally, their is inconsistency in the functioning of libraries. Some use function pointers, some work by inheritance, some (like glade) read the export list..

    I'm not a huge Java fan, but I think they have maintainability down pat. Very consistent language, well defined coding convention, and a mature set of defacto tools (JUnit, javadoc, log4j, struts, spring, hibernate, etc..) make it a lot easier to jump into older code because everything feels familiar. In most other languages you have to spend quite a bit of time just decrypting the existing code, and then more time learning the particular API's they've chosen.

  • by squarefish (561836) * on Saturday July 14 2007, @07:48PM (#19862893)
    The more GOTOs the better!
  • good source (Score:5, Interesting)

    by belmolis (702863) <billposer AT alum DOT mit DOT edu> on Saturday July 14 2007, @07:50PM (#19862911) Homepage
    The source for Tcl [sourceforge.net] is widely considered by those who have worked with it to be unusually clean and clear.
  • Amazing (Score:5, Funny)

    by Dachannien (617929) on Saturday July 14 2007, @08:15PM (#19863099)
    "X is a #%@!in mess," or "Y is unmanageable and really should be rewritten."

    I see those all the time as comments in my own code.

  • OpenSolaris (Score:5, Informative)

    by jlarocco (851450) on Saturday July 14 2007, @08:24PM (#19863183) Homepage

    As large and old as it is, OpenSolaris [opensolaris.org] has fairly readable code. Plus, most of it has comments explaining why it's done the way it is.

  • A experiment (Score:5, Interesting)

    by kabdib (81955) on Saturday July 14 2007, @09:05PM (#19863445) Homepage
    I wrote a Perl filter that took C code as input, and applied all kinds of "unprettifications" to it (removing comments, collapsing variable declarations, introducing random curly-brace and indentation styles, removing whitespace or adding strange whitespace). The output looked like it had been written at 3am by a hung-over ex-FORTRAN engineer who had just discovered FORTH.

    Then I demonstrated that a bunch of code checked into our system looked like it had *already* been run through this tool. After the public shaming, a couple of the offenders cleaned up their acts for a while, but they're back to their old tricks.

    These days I'm working on a project where all the devs are really, really serious about the formatting and naming conventions. Some of the rules suck, in my opinion, but there's a lot to be said for consistency.

    [In the 80s, HyperCard team at Apple used to regularly run their sources through a Pascal formatter. The code, in a friend's words, "looked ironed." Unfortunately I haven't run across any good C++ formatters.]
  • by Okian Warrior (537106) on Saturday July 14 2007, @10:06PM (#19863771) Homepage
    Phoenix Technologies used to make both BIOS and printer software. The printer software department split off and became a different company, and then I lost track of them...

    They made printer software that went into virtually every printer not made by HP at the time. Canon, Ricoh, Lexmark, or whoever would come out with new hardware and license the software from Phoenix. Yep, some of my code is in every Lexmark printer right now.

    They had a couple hundred thousand lines of code that did PCL, GL, and Postscript for the consumer market, and it was the most readable and well developed code I have seen. Comments were explanatory, variables were well named, and execution paths were well defined and easy to follow.

    They really had their act together for testing as well, with an elaborate and comprehensive regression suite that checked *every* aspect of all of the [printer] languages, and a team of QA people who would go over the results nightly. I'm not making this up - you would come in to work in the morning and there would be maybe 5 E-mails from QA outlining bugs which were either in your code or assigned to you for reasonable reasons.

    We did the software for the first Lexmark printer. The first internal release gathered 900 bug reports from QA. When we went to market there were 7 remaining, all of which were deemed inconsequential.

    When you are in the commercial market making fixed-program computers (dishwashers, printers, cell phones, VCRs) you don't have security updates and new versions, and a recall is usually out of the question. It's much cheaper to do all of your QA up front and ship a quality product.

    In my opinion we've grown sloppy in the programming business. I've been a contractor for the past 30 years and I haven't seen anyone else who comes close to true quality procedures. Even FAA safety certified stuff is usually hokey and obscure. Thank god we've still got human pilots.

    Having seen the procedures firsthand I have an appreciation of how easy and valuable it all is. No one else seems to understand that, and so everyone keeps running around putting out fires and slipping deadlines.

  • Bourne Shell (Score:5, Interesting)

    by Repton (60818) on Saturday July 14 2007, @10:20PM (#19863839) Homepage

    The Bourne Shell [tuhs.org] must get some kind of mention here. What do you do if you prefer ALGOL to C? Why, #define your own syntax [tuhs.org], and thus turn boring old C code into a thing of beauty [tuhs.org].

      • Re:Firefox (Score:5, Funny)

        by Rick Zeman (15628) on Saturday July 14 2007, @08:02PM (#19863003)
        At one point I found an screenshot of qmail vs. postfix code in similar areas for handling some condition. The qmail code was hardcoded, had nasty loops and was just plain unbearable. The postfix version, however, was exceedingly elegant and I knew right away what the code was doing.

        And don't forget that postfix is well-commented, and with superb documentation. Re the comments about qmail, I've kept lying around in my mailbox Linus' thoughts about qmail. Couple of interesting points in there.

        On Sun, 6 Jun 2004, Kalin KOZHUHAROV wrote:

        Well, not exactly sure about my reply, but let me try.

        The other day I was debugging some config problems with my qmail instalation and I ended up doing:
        # strace -p 4563 -f -F
        [...] (deleted to bypass lameness filter)
        qmail is a piece of crap. The source code is completely unreadable, and it
        seems to think that "getpid()" is a good source of random data. Don't ask
        me why.

        It literally does things like

                random = now() + (getpid() (two less than signs deleted) 16);
        and since there isn't a single comment in the whole source tree, it's
        pointless to wonder why. (In case you wonder, "now()" just does a
        "time(NULL)" call - whee.).

        I don't understand why people bother with it. It's not like Dan Bernstein
        is so charming that it makes up for the deficiencies of his programs.

        But no, even despite the strange usage, this isn't a performance issue.
        qmail will call "getpid()" a few tens of times per connection because of
        the wonderful quality of randomness it provides, or something.

        This is another gem you find when grepping for "getpid()" in qmail, and
        apparently the source of most of them:

                if (now() - when (less than sign deleted) ((60 + (getpid() & 31)) (two less than signs deleted) 6))

        Don't you love it how timeouts etc seem to be based on random values that
        are calculated off the lower 5 bits of the process ID? And don't you find
        the above (totally uncommented) line just a thing of beauty and clarity?

        Yeah.

        Anyway, you did find something that used more than a handful of getpid()
        calls, but no, it doesn't qualify as performance-critical, and even
        despite it's peyote-induced (or hey, some people are just crazy on their
        own) getpid() usage, it's not a reason to have a buggy glibc.

                        Linus

    • by PianoComp81 (589011) on Saturday July 14 2007, @08:02PM (#19863005)

      And on a related note - why rewrite? Can't people ever just go for cleaning something up? No cause then you are just doing mindless reformatting - while if you rewrite, you can claim you make it better, faster, whatever... So of course people will say its better to rewrite...
      On one project I'm currently working on, we DO just clean up the code. It's necessary because over time developers (myself included) haven't been following the coding standard for the project. To make the code more readable to future developers, we actually will try to clean up a file or pieces of a file when we touch it (comments, style, magic numbers, etc.). There are a lot files, and it hasn't always been a success (it's a continual battle), but it's better than rewriting it.

      Now, I *have* rewritten a lot of the code on the project, but not because it was "ugly". We had quite a lot of "prototype" code still in the project. Since it was prototype code, it didn't check for or handle error conditions very well (not to mention the endless bugs that have been found due to the prototype code). We've had to rewrite a lot of the code because it was easier to do that than fix the bugs in the code. This usually allows for easier debugging in the future AND gets rid of any of the bugs that were found (the bugs were usually caused by a bad or even completely wrong approach to the implementation).

      The difference is knowing when to clean up the code and when to rewrite it. If a developer just can't understand the code (because it needs cleanup or it's just very complicated), then it should be cleaned up and commented properly. Sure it's tedious, but everyone on the project loves you afterwards because they can suddenly understand the code! If there are bugs and it's obvious the implementation should have been done a different way (for speed, usability, modularity, whatever), then a rewrite might be in order.

      (and of course, as you mention, as time goes on the code starts looking "bad" or "old" again - time for hopefully another cleanup rather than a rewrite)
    • Are you kidding? (Score:5, Insightful)

      by Anonymous Coward on Saturday July 14 2007, @08:20PM (#19863141)
      Boost is what I call "template madness". It uses template metaprogramming to the max, which (in the real world) means three things:

            (1) It's impossible to debug. You can't read the code. The debugger can't unravel the templated variables and stuff in any meaningful way for you. You can't even step through code, that's doing a supposedly simple operation like memory allocation!
            (2) Some compilers will choke on the code, or compile it wrong in subtle ways due to differing interpretations of some obscure section of the enormous C++ language spec.
            (3) The error messages from the compiler are useless. You have to run them through a filter to even figure out what they mean.
            (3) Bugs in the library are very difficult to fix. Template metaprograms are essentially programs written in a functional language, except one that has horrible syntax. This is not the stuff that normal C++ programs are made of.

      Your mileage may vary. My day job is working on a game engine for an upcoming Xbox360 game. Engines are hard enough without impractical crap like template metaprogramming in them. Give me straight-line C/C++ code any day.
      • by JNighthawk (769575) <NihirNighthawk AT aol DOT com> on Saturday July 14 2007, @08:40PM (#19863301)
        Mod up. AC knows what he's talking about.

        Even beyond that, Boost fills up the symbol table quick as hell, because of how templated it is. I worked on a project that used LuaBind, which requires Boost, extesnively. We eventually had to swap over from Visual Studio 2003 to 2005, because of Boost's templating filling up the symbol table. Visual Studio would just fail to compile. Lua's hard enough to debug as it is, but tossing Boost on top of it made it impossible.
    • by r00t (33219) on Saturday July 14 2007, @08:46PM (#19863335) Journal
      At least you admit to being uninformed.

      I haven't looked either, but I happen to know that BOOT::Python often does NOT work. It has thread-related problems.

      At for the rest of BOOST, I've looked at a good chunk. BOOST makes decent programmers cry. The other follow-up post by the Anonymous Coward Xbox developer has it all correct.

      I'll add:

      BOOST is full of butt-ugly hacks. Check out the, uh, template things, named _0 through _9 being used as stand-in dummy arguments. Eeeeeew!!!

      BOOST looks easy to dumb-ass programmers, but these programmers leave bugs that are difficult for expert programmers to find.

      BOOST makes compilers run very very slow, and often breaks the optimizer anyway.