password
username
Sponsored by CakeMail, an email marketing software
Newsletter preview

Javalobby logo image
Tuesday, January 15, 2008 

Make Applications More Valuable with Caché

Breakthrough database technology combines objects and robust SQL, eliminating object-relational mapping. Built-in RAD environment brings your innovations to market faster.

Download InterSystems Caché for free now.

 Perspective


Just Released!
SOA Security

Click to Save 30%
Enter code JLSOA30



Be sure and
check out a
No Fluff Just Stuff
Java conference
coming your way!

2/08-2/10 San Jose 2/29-3/02 Milwaukee
3/07-3/09 St. Louis
3/14-3/16 Minneapolis
3/28-3/30 Omaha
4/04-4/06 Boston
4/11-4/13 San Diego
4/11-4/13 Portland
4/18-4/20 Jersey City

 
 A Developer's Perspective
 Next section
David Brady has been programming professionally for nearly 20 years, split about evenly between Win32/C++ and programming for the web in PHP, Python and Ruby. An avid proponent of agile methodologies, David is rabid about unit testing and delivering "stuff that works". He currently works as a software consultant in Salt Lake City, Utah.

Rick Ross, JavaLobby FounderDishonest Programming
By David Brady

There's a good part of Computer Science that's like magic. Unfortunately there's a bad part of Computer Science that's like religion.— Hal Abelson
I tend to view things differently than most people. This causes me grief in unusual places: today at the grocery store I recited my 11-digit "Fresh Values" card number to the cashier from memory, then stared right at the PIN pad, which was asking me to swipe my card, and attempted to hand my card to the cashier. A friend who was with me laughed at my simultaneous display of brilliance and retardation. I nodded and said, "I face a... unique set of challenges in life."

But sometimes my different views are really beneficial. My greatest strength, I think, is being able to give a team of really brilliant programmers a completely different way of thinking about a problem. Hal's comment triggered a return to a pattern of thinking I started having about a year ago, about how religion and morality are two different things... and about whether we can apply the notion of morality to programming.

I first surprised myself with this thought one day as I was pair programming with a brilliant but inexperienced developer. He was very clever and could think through extremely complicated designs and, while holding them firmly in his head, go implement them. As we were coding, he had a brilliant but deceptive idea. There is a well-known design pattern that has an obvious purpose and an implicit side effect; Ross wanted the reverse of the implicit side effect so he started writing the design pattern backwards. It was neat, it was clever, and I was certain that Ross could implement the code and get it working without bugs.

I also knew that anybody maintaining the code would never notice that the design pattern was implemented backwards until they modified it and it suddenly stopped working. I thought hard for a moment, and then quietly asked, "Ross, are we being dishonest here? Anybody reading this code will think you're doing this, but what you're really doing is that." I remembered this because it's the only argument I ever won with Ross without a fight. He stopped, leaned his head to one side and said, "Umm... yeah, you're right. Okay, how should we do this?" We went on to write some much better code that afternoon, some much more honest code.

How do you teach honesty in coding? I'm not really sure. Yesterday I reviewed some code that was dishonest from top to bottom. In our application's accounting subsystem, you can create subaccounts and then link inventory to those accounts instead of the default general accounts they start with. For example, there is a general account called "Revenue". For each service in your catalog, you can put its revenue into a different subaccount if you wish, so you could put all your Grand Canyon trips in a subaccount called "Grand Canyon Revenue". At the end of the year you can examine your revenue accounts and see which areas of your company are the most profitable.

So, there's a bug in our code. It turns out you can assign a trip to more than one subaccount at a time. You could accidentally put your Grand Canyon trips into "Grand Canyon Revenue" and "Hummer Safari Revenue", and while the accounting system would put all the revenue into only one of those accounts, you don't know which account the system will pick. So I asked two of my coders to fix this bug.

In my mind, this logic is really clear: before linking a charge item to a subaccount, you need to check to see if that charge item already has a link to a subacount of the same base account. (Every trip touches Accounts Receivable, Sales Tax Liability, and Revenue; you can override all three of these if you wish, so long as you don't try to override the same base account twice.) So the pseudocode for this is straight up:

    // in event handler for onCreateLink:
    if ( hasOverride(chargeItem, baseAccount) ) {
        // already overridden. Warn user and ask if they want to replace override
    } else {
        createOverride(chargeItem, baseAccount);
    }
The code for hasOverride() would be maybe 10 lines long; createOverride() is 1 probably line of code wrapped in 4 lines of error handling.

What was submitted for review was about 30 lines long. Not terrible, but far enough off to warrant further inspection. The REAL warning sign was that the code didn't work and one of the developers who wrote it was really having trouble thinking through it to debug it. His partner had left for the day, so I sat and we began to review.


Problem number one, the event handler, which I would call onCreateLink, was called createLink. It's a simple difference, just one word. Is it important? You tell me: this function can exit normally, without throwing an exception or raising an error, without creating a link. The method doesn't create a link; the method creates a link IF it thinks it should. This is not createLink(). This is createLinkMaybe(), or perhaps createLinkIfYouFeelLikeIt().
Honesty Tip #1: Name functions for what they really do. You've been taught to write foo munging code by drawing a box on the paper and labeling it fooMunger() and then writing the code. Okay, but when you're done, go back and read your code. Is it really fooMunging code, or does it also do something else? If you're spending 80% of your method checking error conditions, your method is clearly less concerned with munging foos than determining whether it should munge foos. Congratulations--you've written an event handler. Rename it to onMungeFoo() or handleFooMungeRequest() or whatever, and extract the code that ONLY munges foos to mungeFoo().
Number two. There was no hasOverride() method, but rather a function called containsSimilar() that took the list of account overrides already loaded in the UI. What the heck does "similar" mean? Looking at the code is a pile of compare methods, none of which actually check the charge item or base account. The author had determined that if you created the new account override without checking it, you could compare it to the already created overrides. If you found a similar one already created, you knew that the override was illegal.

Honesty Tip #2: Let your yea mean yea and your nil mean nil. Don't set up code to cleverly create side effects. EVERY effect is a side effect! Name your code for the intended side effect and document any other side effects. Don't name your code for the unintended effect, especially if you think you're cleverly creating an abstraction. (If the abstraction is really good AND other code will use it unchanged, you may create an abstracted method but you should still not use the abstraction in your other code. Write a wrapper method that explains your intended effect, like:
bool isLegalOverride(Foo a, Bar b) { return !areSimilar(a, b); }
Number three. Once containsSimilar() had approved the accountOverride, the override was added to the list by violating the Law of Demeter:

setupModel.getOverrides().add(accountOverride);
setupModel was a systemwide object, and getOverrides() was a list that was publicly accessible. Do you know what that makes SetupModel.accountOverrides? A global variable. Now, there are exceptions to the rule "never use globals", but this is exactly the kind of global they were talking about when they made the rule in the first place.

Honesty Tip #3: Don't pee on my leg and tell me it's raining, and don't write a public accessor to a private member and tell me that member is still private. If an object is completely and utterly accessible from anywhere in the application, it's a global variable.
I finally rejected the entirety of the code submitted by these developers, because once we cleared up the dishonesty in the code, it became clear that the timing and placement of the code was such that it was too late to stop and ask the user to confirm or abort the override sequence. In other words, they had been so cleverly writing code to construct side effects, that they had spent four hours writing code that did not do what the original objective requested.

I see programmers get rolling and they act like they're trying to carefully sneak up on the problem without letting the compiler know what's going on. Don't do that! Start by writing down what you want to accomplish. Now write high-level methods to state that purpose. As you move forward writing the code, always write code that clearly shows what it is you're trying to do. Don't make me decode your side effects to attempt to infer your purpose.

Honesty Tip #4: Don't try to trick the compiler into giving you what you want. You'll only trick your coworkers (and probably yourself). Tell the compiler what you want and write code that makes it give it to you.
Deceptive code is immoral code. You CAN write moral code--it means simply being honest with yourself, with the compiler, and with your coworkers.

Any time you feel yourself being clever, ask yourself a key question: are you being deceptively simple, or simply deceptive?

Until next time,
David Brady
http://chalain.livejournal.com/

 
 DZ Top Links
 
 DZone Top Links
 Next section
 Back to top
most clicked this week from dzone.com

dzone

Most-clicked links this week

 
 Popular at JL
 
 Popular at Javalobby
 Next section
 Back to top
A recap of some of the most popular and active Javalobby.org discussions this week.
Catching multiple exceptions: good or bad?

Does the proposed feature improve code readability and correctness? or does it simply promote abuse?

Full Discussion Posted By: cowwoc - (44 Replies)

SWT's Role in Modern Java

I've been noticing a trend recently which seems to represent a new leaf in the Swing vs SWT war: interoperation.

Full Discussion Posted By: Daniel Spiewak - (36 Replies)

Thanks Zed, Java evolution, Ruby and Scala Pimple Pimping

Thanks to Zed, Ruby related posts on jroller are at an all time low. Sun please drop JRuby support. Take that money and spend it on Groovy which has a compatible syntax to Java. Thoughts on Scala.

Full Discussion Posted By: Rick Hightower (ArcMind Inc.) - (31 Replies)

Native Web Browser, Flash Player for Swing applications

Swing does not currently have a proper integration solution to embbed native components. Fortunately, there is a solution now: the DJ Project - Native Swing.

Full Discussion Posted By: Christopher Deckers - (28 Replies)

Absolutist: Java - Evolutionary Dead End

There seems to be a LOT of absolutist discussion like this lately, and absolutist perspectives tend to raise a flag of skepticism in me.

Full Discussion Posted By: Stephen Strenn - (22 Replies)

 White Papers & Announcements
 
 Product Announcements
 Next section
 Back to top
Product and service announcements for Java developers.
Desiderata releases Jaxcent (Java AJAX) for the Internet

V1 of Jaxcent (Java AJAX API) provided access to DOM from Java, but was restricted to intranets. V2 works with standard servlet containers, and provides unrestricted access to DOM from Java.

Full Announcement & Discussion Posted By: Desiderata Software - (0 Replies)

Syncro SVN Client V.3.0

Syncro Soft Ltd, the producer of Syncro SVN Client, has announced the immediate availability of version 3.0 of its Subversion (SVN) client.

Full Announcement & Discussion Posted By: SyncRo Soft - (0 Replies)

OpenSpaces.org developer community site launced

The OpenSpaces framework leverages the Spring Framework and GigaSpaces for building scale-out applications.

Full Announcement & Discussion Posted By: Geva Perry - (0 Replies)

DesignerVista 1.0 Launched - GUI Design Tool

DesignerVista is a Graphic User Interface(GUI) design Tool. It helps you to design GUI Mockups, GUI screen shots, GUI prototypes and Simple Web Page prototypes.

Full Announcement & Discussion Posted By: Kumaravel - (0 Replies)

HDIV (HTTP Data Integrity Validator) 2.0.3 Released

HDIV 2.0.3 has just been released including new features.. HDIV project is an Apache-licensed Java Web Application Security Framework.

Full Announcement & Discussion Posted By: Gorka Vicente - (0 Replies)

DJ Native Swing 0.9.2 - Web Browser, Flash Player and more!

DJ Native Swing allows to easily integrate some native components (Web Browser, Flash Player) into Swing applications, and provides some native utilities to enhance Swing's APIs.

Full Announcement & Discussion Posted By: Christopher Deckers - (0 Replies)

Sketsa SVG Editor 5.1 Released

KIYUT just released Sketsa SVG Editor 5.1, a cross platform vector drawing application based on SVG.

Full Announcement & Discussion Posted By: Kiyut - (0 Replies)

Released 1.4.1 version of OpenSwing

Released an update of OpenSwing suite of graphics components based on Swing toolkit. Below you can see the most recently news.

Full Announcement & Discussion Posted By: mauro carniel - (0 Replies)

WfXML XPDL Workflow For JBoss 2.1-1 package released

The WfXML XPDL Workflow for JBoss package based on 2.1-1 version of open source workflow engine Enhydra Shark is released.

Full Announcement & Discussion Posted By: Sasa Bojanic - (0 Replies)

Enhydra Shark 2.1-1, open source workflow engine, released

The 2.1-1 version of open source workflow engine Enhydra Shark is released. Enhydra Shark is flexible and extensible WfMC and OMG Wf Management Facility compliant embeddable Java Workflow Engine

Full Announcement & Discussion Posted By: Sasa Bojanic - (0 Replies)

Lobo Browser 0.97.5

Lobo is an open source web browser that is written entirely in Java. It is being developed with the aim to support HTML 4, Javascript and CSS2.

Full Announcement & Discussion Posted By: The Lobo Project - (0 Replies)

Luntbuild 1.5.4 is available for download

Luntbuild development team is proud to announce release of Luntbuild 1.5.4. Luntbuild 1.5.4 is available on Javaforge: http://www.javaforge.com/proj/doc.do?doc_id=41660

Full Announcement & Discussion Posted By: Lubos Pochman - (0 Replies)

Eclipse Plugin RSS View now LGPL

RSS View is an Eclipse Plugin for viewing RSS/Atom feeds directly in Eclipse. This is the first open source (LGPL) release since its first release in April 2004.

Full Announcement & Discussion Posted By: Markus Junginger - (0 Replies)

800 Mock Questions for SCJP 1.6

We have released Java based exam simulator - JQPlus V6 for SCJP 6 / 1.6 (about 800 questions)!!! Contains questions on Console, NavigableMap, NavigableSet, and finalize()

Full Announcement & Discussion Posted By: Enthuware Support - (0 Replies)

View providers driven applications framework - Web client added

VPDA is pure java framework all tiers application framework with complete infrastructure and client abstraction. Client can be swing desktop and now web client using WingS web framework was added.

Full Announcement & Discussion Posted By: Roman Kitko - (0 Replies)

RIA and business applications: Zurich, Feb 1, 2008

If you're based in Switzerland, Austria or southern Germany, this 1 day course on Rich Internet Applications and AJAX may be of interest.

Full Announcement & Discussion Posted By: Sandra Wendland - (0 Replies)

Access HL7 from .NET & Java - DataDirect XML Converters 3.1 Released

Support of HL7 and other EDI standards in DataDirect XML Converters 3.1, in addition to scalability & performance enhancements further simplifies HL7 data integration with Java and/or Microsoft .NET.

Full Announcement & Discussion Posted By: I. Pedruzzi - (0 Replies)

AjaxSwing - AJAX front end for Swing applications

AjaxSwing automatically converts Java Swing and AWT applications into fully-functional HTML and AJAX websites. The same application can be run as thick Swing client or as thin AJAX rich client.

Full Announcement & Discussion Posted By: Alex Kalinovsky - (3 Replies)

MagicDraw 15.0 Adds the Latest UML Support

No Magic has just released a new version of MagicDraw now fully compliant with the UML® 2.1.2 standard. Additionally, multiple usability enhancements were added.

Full Announcement & Discussion Posted By: Saulius Zukauskas - (0 Replies)

Easy Swing GUI Testing with FEST-Swing 0.8

FEST-Swing is a Java library that provides a fluent interface for functional Swing GUI testing. This library provides an easy-to-use API that makes creation and maintenance of GUI tests easy.

Full Announcement & Discussion Posted By: Alex Ruiz - (1 Replies)

 Your Account
 
 Your Account
 Next section
 Back to top
Manage your account info for this and other Javalobby publications.
Manage your Javalobby membership details

Click on the following links to:


 Contact Info
 Next section
 Back to top
Here's how to reach us, we love to hear from you.
Email us
Send news items to editor@javalobby.org
Send questions, complaints, or suggestions to feedback@javalobby.org
Send advertising inquiries to advertise@javalobby.org
 
Call us
Our number is (919) 678-0300. We'd love to hear from you!

 Legal
 Back to top
The fine print we'd rather avoid completely.
Feel free to redistribute this newsletter in part or in full to your friends.

Javalobby News is a service mark of DZone, Inc.
Copyright ©2001-2008 DZone, Inc.

Thank you for your continued support of Javalobby. If you prefer not to receive the Javalobby weekly newsletter, send an e-mail to ***-jlnews@javalobby.org and please ensure the actual email address to be removed is present.
Javalobby.org, 113 Legault Drive, Cary NC 27513 USA