Try-ing code



  • Here's one you'll enjoy ... this is one of several database access patterns that was repeated copy/pasted over time after this initial model was created:

    public boolean shutdown = false;
    public static final boolean connectionRequestTimeout = true; // value actually read from config file
    public static final int connectionRefusalCount = 5; // value actually read from config file
    .
    .
    .

    public final boolean storeItem(ItemType item) {

    Connection conn = null;
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rstId = null;
    int requestCounter = 0;
    boolean itemInsert = false;
    boolean gotConn = false;

    while(!gotConn && !shutdown) {
    try {
    conn = pool.getConnection();
    gotConn = true;
    } catch (OutOfConnectionsException e) {
    requestCounter++;
    if (requestCounter > connectionRefusalCount) {
    if (connectionRequestTimeout) {
    throw new OutOfConnectionsException("no connections currently available");
    }
    }
    System.err.println("no available connections, trying again");
    } catch (Exception e) {
    handleUnanticipatedOccurance("DB_DOWN", e);
    return false;
    }
    }

    // if we get here, then we've successfully retrieved a
    // SQL connection from the connection pool

    try {
    stmt = conn.createStatement();
    stmt.setMaxRows(MAX_ROWS);
    stmt.setFetchSize(FETCH_SIZE);
    } catch (SQLException e) {
    try {
    conn.close();
    } catch (SQLException ex) {
    // nothing to do here
    }
    handleUnanticipatedOccurance("DB_DOWN", e);
    return false;
    }

    // okay, so by here, we have successfully created a
    // connection and a statement

    if (item.getKey() < 0) {
    pstmt = createPreparedStatement("ItemInsert", conn);
    itemInsert = true;
    } else {
    pstmt = createPreparedStatement("ItemUpdate", conn);
    itemInsert = false;
    }

    try {
    pstmt.setFloat(1, item.getValue1() );
    } catch (SQLException e) {
    try {
    stmt.close();
    pstmt.close();
    conn.close();
    handleUnanticipatedOccurance("BAD_QUERY_CODE", e);
    return false;
    } catch (SQLException ee) {
    handleUnanticipatedOccurance("DB_DOWN, ee);
    return false;
    }
    }

    try {
    pstmt.setFloat(2, item.getValue2() );
    } catch (SQLException e) {
    try {
    stmt.close();
    pstmt.close();
    conn.close();
    handleUnanticipatedOccurance("BAD_QUERY_CODE", e);
    return false;
    } catch (SQLException ee) {
    handleUnanticipatedOccurance("DB_DOWN, ee);
    return false;
    }
    }

    .
    .
    .

    try {
    pstmt.setString(101, item.getValue101() );
    } catch (SQLException e) {
    try {
    stmt.close();
    pstmt.close();
    conn.close();
    handleUnanticipatedOccurance("BAD_QUERY_CODE", e);
    return false;
    } catch (SQLException ee) {
    handleUnanticipatedOccurance("DB_DOWN, ee);
    return false;
    }
    }

    if ( item.getKey() > 0) {
    try {
    pstmt.setInt(102, item.getKey() );
    } catch (SQLException e) {
    try {
    stmt.close();
    pstmt.close();
    conn.close();
    handleUnanticipatedOccurance("BAD_QUERY_CODE", e);
    return false;
    } catch (SQLException ee) {
    handleUnanticipatedOccurance("DB_DOWN, ee);
    return false;
    }
    }
    } else {
    try {
    rstId = stmt.executeQuery("select ITEM_ID_SEQ.nextVal from dual");
    rstId.next();
    intItemId = rstId.getInt(1);
    pstmt.setInt(102, intItemId );
    } catch (SQLException e) {
    try {
    stmt.close();
    pstmt.close();
    conn.close();
    handleUnanticipatedOccurance("BAD_QUERY_CODE", e);
    return false;
    } catch (SQLException ee) {
    handleUnanticipatedOccurance("DB_DOWN, ee);
    return false;
    }
    }
    }

    // prepared statement is all set up!

    try {
    pstmt.executeUpdate();
    conn.commit();
    } catch (SQLException e) {
    try {
    conn.commit(); // try again, just in case?
    stmt.close();
    pstmt.close();
    conn.close();
    handleUnanticipatedOccurance("BAD_QUERY_CODE", e);
    return false;
    } catch (SQLException ee) {
    handleUnanticipatedOccurance("DB_DOWN", ee);
    return false;
    }
    }

    try {
    conn.commit(); // once more with feeling
    stmt.close();
    pstmt.close();
    conn.close();
    } catch (SQLException e) {
    handleUnanticipatedOccurance("DB_DOWN", e);
    return false;
    }

    return true;

    }

    public void handleUnanticipatedOccurance(String errorCode, Exception e) {
    boolean success;
    if (!aborted) {
    System.err.println(new java.util.Date().toString() + " (" + errorCode + ")" );
    e.printStackTrace(system.err);
    }
    }

    public PreparedStatement createPreparedStatement(String idString, Connection conn) {
    PreparedStatement pstmt = null;

    if ( idString.equalsIgnoreCase("ItemInsert") ) {
    try {
    pstmt = conn.prepareStatement("INSERT INTO ITEMS ( value1, value2, value3, value4, ... value102 ) " +
    " values ( ?, ?, ?, ?, ?, ... ? )";
    } catch (SQLException e) {
    e.printStackTrace();
    return null;
    }
    } else if ( idString.equalsIgnoreCase("ItemUpdate") ) {
    try {
    pstmt = conn.prepareStatement("UPDATE ITEMS SET value1 = ?, value2 = ?, " +
    "value3 = ?, value4 =?, ... value101 = ? " +
    "WHERE ITEM_ID = ?" );
    } catch (SQLException e) {
    e.printStackTrace();
    return null;
    }
    } else if ...

    .
    . repeat 28 or so more times, for each possible table and action ...
    .

    } else {
    return null;
    }

    return pstmt;
    }

    Note that the actual method does a few more things (handling child records in associated tables) after the pstmt.executeUpdate(). This method starts at line 363. The final closing brace is on line 3289.



  •  Oh come on give the guy a break! Who hasn't written a 3k line single file ORM and copied the contents around 10 or 20 times in their lifetime??!!??



  • @trwww said:

    Filed under: sure it sucks but I know how to use it!
    That's what she said!



  • @zelmak said:

    handleUnanticipatedOccurance

    I am never naming a method handleErrors again.

    @zelmak said:

    public void handleUnanticipatedOccurance(String errorCode, Exception e) {
    boolean success;
    if (!aborted) {
    System.err.println(new java.util.Date().toString() + " (" + errorCode + ")" );
    e.printStackTrace(system.err);
    }
    }
    What?

     

     



  • @Zecc said:

    @zelmak said:

    handleUnanticipatedOccurance

    I am never naming a method handleErrors again.

    @zelmak said:

    public void handleUnanticipatedOccurance(String errorCode, Exception e) {
    boolean success;
    if (!aborted) {
    System.err.println(new java.util.Date().toString() + " (" + errorCode + ")" );
    e.printStackTrace(system.err);
    }
    }

    What?
     

    Yeah, it should've been called unanticipatedOccurrenceHandling.

     



  • @zelmak said:

    // prepared statement is all set up!

     

    Can we all agree that exclaimation points in code comments is a major red flag?



  • @frits said:

    @zelmak said:

    // prepared statement is all set up!

     

    Can we all agree that exclaimation points in code comments is a major red flag?

    Surely, you've simply lost all sense of the joy of coding!


  • @frits said:

    Can we all agree that exclaimation points in code comments is a major red flag?
    Yep, agreed!  If I used one of those, it would be either a desperate cry for help (in stupidly-complex problem domains) or a warning to maintainers that dragons lurk here, waiting to eat them.

    Just off the top of my head, I know I have a few exclamation points around some Excel COM interop code that uses a stack to ensure that FinalReleaseComObject gets called on each object and in the correct order.  Something like "DO NOT MODIFY UNLESS YOU KNOW REFERENCE-COUNTING IN COM!"  If some maintainer comes along and references a COM object without adding it to the GarbageCan stack, Excel will never close and indeed, will duplicate its processes until the inevitable system crash.



  • @frits said:

    @zelmak said:

    // prepared statement is all set up!

     

    Can we all agree that exclaimation points in code comments is a major red flag?

    There are no comments in the actual code ... that was me editorializing.



  • @zelmak said:

    There are no comments in the actual code

    Oh.  That makes it pretty similar to my own code, then.  Carry on.



  • @frits said:

    Filed under: comments are for sissies

    Unless the comment succinctly states,

    // This should never happen
    , or,
    /** this is bad coding - but i'm assuming this will never happen anyways **/
    . In which case, it is acceptable.



  • @dohpaz42 said:

    @frits said:
    Filed under: comments are for sissies
    Unless the comment succinctly states,
    // This should never happen
    , or,
    /** this is bad coding - but i'm assuming this will never happen anyways **/

    . In which case, it is acceptable.

    You forgot

    // Do nothing

    and

    // TODO: Add logic here


  • @C-Octothorpe said:

    You forgot

    // Do nothing

    and

    // TODO: Add logic here

    Well, in my defense, it's because I haven't come across it in my codebase yet. They exist - I use those comments as place holders or "documentation".



  • @frits said:

    @zelmak said:

    // prepared statement is all set up!

     

    Can we all agree that exclaimation points in code comments is a major red flag?

     

     

    Not as bad (IMHO)  as using them in error messages, where they are the equivalent of writing "you idiot!" at the end of the message:

    •       Date must be in dd/mm/yy format!
    •      No matching records found!

     

    Worse still in success message, e.g. testing an ODBC SQL datasource:

    • TESTS COMPLETED SUCCESSFULLY!

    So are we supposed to be impressed?  Surprised? (Extra points for ALL CAPS)

     

     

     

     



  • @Cantabrigian said:

     

    Not as bad (IMHO)  as using them in error messages, where they are the equivalent of writing "you idiot!" at the end of the message:

    •       Date must be in dd/mm/yy format!
    •      No matching records found!

     

    Worse still in success message, e.g. testing an ODBC SQL datasource:

    • TESTS COMPLETED SUCCESSFULLY!

    So are we supposed to be impressed?  Surprised? (Extra points for ALL CAPS)

     

     

     

     

    At least those messages are descriptive of the actual event. The absolute worst (aside of no message at all) is the generic "An error occurred", and nothing else. Was it me? The server? Because today is Thursday?



  • @dohpaz42 said:

    ... Because today is Thursday?

    I never could get the hang of Thursdays.



  • @dohpaz42 said:

    At least those messages are descriptive of the actual event. The absolute worst (aside of no message at all) is the generic "An error occurred", and nothing else. Was it me? The server? Because today is Thursday?

    Of all the things that pissed me off about Lotus Notes, its maddeningly vague error messages were the thing that pissed me off the most. "An operation failed on an object." WHICH operation? WHICH object!? GRAHSUAYHDSUAHRFEIHR IU@! H#IU! HDG IY!

    See I haven't used it in years, and it still causes rage.



  • @blakeyrat said:

    See I haven't used it in years, and it still causes rage.

    Not only do I not believe that Lotus Notes could cause rage, I don't believe that you of all people would get angry.  No, sir, I find this story wholly unbelievable.



  • @dohpaz42 said:

    Because today is Thursday?

     

    Nah, they have that covered:

    "DAY MUST BE WEDNESDAY!"



  • @hoodaticus said:

    @frits said:

    Can we all agree that exclaimation points in code comments is a major red flag?
    Yep, agreed!  If I used one of those, it would be either a desperate cry for help (in stupidly-complex problem domains) or a warning to maintainers that dragons lurk here, waiting to eat them.

    Just off the top of my head, I know I have a few exclamation points around some Excel COM interop code that uses a stack to ensure that FinalReleaseComObject gets called on each object and in the correct order.  Something like "DO NOT MODIFY UNLESS YOU KNOW REFERENCE-COUNTING IN COM!"  If some maintainer comes along and references a COM object without adding it to the GarbageCan stack, Excel will never close and indeed, will duplicate its processes until the inevitable system crash.

    I hate Excel interop.  Nothing worse than having an orphaned Excel process continuously prevent the user from viewing the client portion of the window.



  • @Ilya Ehrenburg said:

    @Zecc said:

    @zelmak said:

    handleUnanticipatedOccurance
    I am never naming a method handleErrors again.

    @zelmak said:

    public void handleUnanticipatedOccurance(String errorCode, Exception e) {
      boolean success;
      if (!aborted) {
        System.err.println(new java.util.Date().toString() + " (" + errorCode + ")" );
        e.printStackTrace(system.err);
      }
    }

    What?
     

    Yeah, it should've been called unanticipatedOccurrenceHandling.

    I created a quite similar method in my own code while troubleshooting ... I named it "handleExceptionPoorly" ...



  • @frits said:

    Nothing worse than having an orphaned Excel process continuously prevent the user from viewing the client portion of the window.
    Or crashing the cough server cough.  The oft-featured "Gary" that used to work for me did that.  Every week or so when I had occasion to look at Task Manager on that web server, there would be a hundred or so Excel processes sitting there turning my PowerEdge into an e-Machine.



  • @hoodaticus said:

    I know I have a few exclamation points around some Excel COM interop code that uses a stack to ensure that FinalReleaseComObject gets called on each object and in the correct order.

    Can't you just use some reference counting smart pointers like _com_ptr_t or CComPtr? (Obviously, I wouldn't dare touch your code)

     

    @frits said:

    I hate Excel interop.

    IMO, all COM interop is a hellish nightmare of unreadable code. Just use the VS code wizard to generate an empty class and look at the boilerplate code it generates for you. Really makes you go "WTF is this shit? How is anybody supposed to write this crap by hand?" if you are used to sane looking C++.

     



  • @frits said:

    @zelmak said:

    // prepared statement is all set up!

     

    Can we all agree that exclaimation points in code comments is a major red flag?

    Yes, it means that the programmer's 12 years old (or at least, that's his mental/emotional age) and he's just written his first exciting program!



  • @dohpaz42 said:

    The absolute worst (aside of no message at all) is the generic "An error occurred", and nothing else. Was it me? The server? Because today is Thursday?

    At least you know it was an error. Far worse are Microsoft products, when they give you a message that can mean almost anything [i]except[/i] what it says: "The operation completed successfully."



  • @zelmak said:

    @dohpaz42 said:

    ... Because today is Thursday?

    I never could get the hang of Thursdays.

    Arthur Dent, FTW! +42



  • @Seahen said:

    @dohpaz42 said:
    The absolute worst (aside of no message at all) is the generic "An error occurred", and nothing else. Was it me? The server? Because today is Thursday?

    At least you know it was an error. Far worse are Microsoft products, when they give you a message that can mean almost anything except what it says: "The operation completed successfully."

    Funny because this is not limited to just Microsoft. I was copying a couple gigs of files over the network from my work Linux machine, which is Ubuntu 10.something running Gnome, and there were a few "errors" with details of "Success". But, then again, the destination was a Microsoft machine, so who knows. Either way, definitely WTFry.



  • @Seahen said:

    @dohpaz42 said:
    The absolute worst (aside of no message at all) is the generic "An error occurred", and nothing else. Was it me? The server? Because today is Thursday?
    At least you know it was an error. Far worse are Microsoft products, when they give you a message that can mean almost anything except what it says: "The operation completed successfully."

    NSS Server liked to throw this at me: "There was an unknown error in an unnamed file." Closely followed by "Service  on Host  is not running".

    Yeah, those are double spaces where the service name and hostname should have been. The empty service isn't running on the NULL-host. Nice to know i guess.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.