• (cs) in reply to CornedBee
    CornedBee:
    ammoQ:

    For example, in Austria, the social security number should be unique; but there are a few cases where two people got the same number. If you build a system that relies on the SSN being unique, it may work perfectly through 1000000 test cases but fail in production.


    Interesting detail, especially as right now I'm building a system that does use Austrian SSNs as keys. But then - how DO you correctly find identity between two persons entered by different people?


    Compare their names? I don't think there is a "perfect" solution for this dillema.
  • (cs) in reply to Drak
    Drak:

    First of all, I didn't read all of the posts.

    Secondly, there's nothing wrong in returning an exception, and here's why:

    If you use the Invoke method to invoke methods from an assembly you loaded into memory (like a plugin) and this method throws an exception all you will ever get back is 'Invocation threw an exception' or some such message. The original exception gets lost. So you declare the return type as an object, return either what you want, or an exception. Then you can check after your invoke if the return value is of the exception type and throw the right exception.

    I've used this in various places, but mostly only to propagate real exceptions ie:

    Try
      ...
    Catch ex as Exception
      Return ex
    End Try
    Return RealValue

    Drak



    From your code example, that looks to be .NETish...and that may be how it works in .NET (don't remember, it's been so long).

    In Java, you'll get an InvocationTargetException which will contain the original exception that was thrown (getTargetException()).  So it's still a WTF because you could have just as easily done...

    try {
        return method.invoke(this, null);
    } catch(InvocationTargetException itex) {
        throw new MyApplicationBusinessException(itex.getTargetException()));
    }

    which is much cleaner than returning the exception.

  • (cs) in reply to Alex Papadimoulis
    Alex Papadimoulis:

    strongarm:

    Also, if everything in the system uses the same key type...i.e. a long or a UUID it's a whole lot easier to write generic lookup code (i.e. test for existence, retrieve a single record, delete a record etc.).

    I say, if you're going to play CODASYL, you may as well use CODASYL. It becomse so much easier that way because you get all these great things like functions to help you walk pointer-chains ...



    I'm assuming sarcasm.  When are you going to get the sarcasm tag added to this forum?  ;O)

    From scanning through some of the topics I know we're miles apart on data architecture which is alright.  Our experiences have led us to different conclusions is all.
  • BogusDude (unregistered) in reply to Rick
    Rick:
    Initializing a local variable to null in Java code IS bad practise. Java will warn you during compilation if you don't initialize all local variables somewhere in your code. Initializing to null is bad practise because it eliminates this check.

    But not all bad practises are WTFs. I think the test for a WTF should be, "Would that issue alone justify posting on thedailywtf.com?" Initializing to null clearly fails that test.


    May I just say that in C++, initialising variables to NULL (or any other sane value) is a GOOD THING (Tm).
    The reason is that variables aren't initialised in C++ (unless it's a class with a default constructor, in which case the default constructor gets called.)
    If you don't initialise your C++ variables (take pointers for example), you get some very strange errors. However if you initialise them you might still get errors, but this time you'll know that you didn't set the variable somewhere (accessing a NULL pointer will cause a GPF and you should then be able to see your pointer is null, whereas if you didn't initialise it, it might look like a valid pointer. There is a programming idiom called Resource Acquisition is Initialisation. In C++ you have to implement this yourself where in Java, C#, VB (.NOT or otherwise) this is done for you.
  • szeryf (unregistered) in reply to pete_norm

    Just to make clear: it isn't a code that I wrote. Someone asked me to do some corrections and patches to a web app that was written for them by some student, I think, and they cannot contact him :-)

    Seeing mess like that I instantly declined, but they were kind enough to let me copy this gem :-)

  • Thomas Magle Brodersen (unregistered) in reply to Schol-R-LEA

    >Rev. First Speaker Schol-R-LEA;2 ELF JAM LCF BiWM MGT GS

    So, what happened to your first clone? ;-)

  • (cs) in reply to dubwai

    I'm not a java bod, but it appears that it is a framework function.

  • fatgeekuk (unregistered)

    Ok, so, do you say TLA as a word or as T-L-A.

     

    If the latter, then TLA is not an acronym. An acronym is some abbreviation which is pronounched as a word...

     

    RADAR, SCUBA, LOC, FUD all acronyms

    T.L.A, R.P.M not.

    So, while TLA refers to Acronyms it is not one itself.

  • Jon (unregistered) in reply to Drak
    Drak:
    If you use the Invoke method to invoke methods from an assembly you loaded into memory (like a plugin) and this method throws an exception all you will ever get back is 'Invocation threw an exception' or some such message. The original exception gets lost.
    Actually, it's still there in the InnerException property. WTF were you thinking? :-)
  • Ebbe Kristensen (unregistered)

    Alex Papadimoulis:
    ** Three Letter Acronym, which happens to be the best self-describing thing ever.

    Is it now? How about ACRONYM?

    As in Abbreviated Coded Rendition Of Name Yielding Meaning

  • (cs) in reply to Sridhar
    Anonymous:
    Well few things that i figured out were:

    <font>1.public Object</font> findRecord(<font>String</font> table, int i) {
    2. <font>Object</font> r = <font>null</font>;
    3. r = executeQuery(<font>"select * from "</font> + table + <font>" where id = "</font> + i);
    4. <font>if</font> (r == <font>null</font>) r = <font>new</font> <font>ClassNotFoundException</font>();
    5. <font>return</font> r;
    6.}

    a)in line 3 you are concatenating Strings, "select * from", and "table" are static strings. What internally is being done is that four objects are created everytime the query string is formed. So if you have 1000 query you would have the overhead of creating 5000 objects , i.e. 1000 for each String + 1000 for each object returned. Using StringBuffer will be a lot less resource intensive.

    b) we r returning <font>ClassNotFoundException</font>()... how can the caller figure out whether it is returned by java or the database??

    It would be great if the author enlightens us about the exact nature of those >7 errors



    Using StringBuffer would not change anything at all in this context.

    From the Java Documentation:


    String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

         x = "a" + 4 + "c"

    is compiled to the equivalent of:

         x = new StringBuffer().append("a").append(4).append("c")
    .toString()




    b) The JVM throws a ClassNotFoundException, this function returns it. That's a difference!
  • (cs) in reply to Ebbe Kristensen
    Is it now? How about ACRONYM?

    As in Abbreviated Coded Rendition Of Name Yielding Meaning


    That'd be a "backronym"... :D

  • Jon (unregistered) in reply to yawmark
    yawmark:
    Is it now? How about ACRONYM?

    As in Abbreviated Coded Rendition Of Name Yielding Meaning


    That'd be a "backronym"... :D
    So what does BACKRONYM stand for? ;-)

  • (cs)

    Since a lot of you found some WTFs, I'll give it a try myself... (Note: due to the way of naming, I assume it's a Java snipplet.)

    • The name... it doesn't only 'find' the record, it also returns it. Therefor, the name should be 'getRecord'. Not a real WTF, but a style thingie: name your methods for what they really do.
    • Since this method returns a record, it should have the correct return type -> WTF?!
    • He assumes, that all tables in the database have got the column "id" type int. Maybe he's right, but it's BAD.
    • Initializing the return variable is a waste in this case, because he stores data in it right in the next statement. The initialization might be a waste, but I think it's better.
    • He implements a method called "executeQuery" in this class, which (hopefully) handles the connection to the database, reading the record(s), and returning the result of the query. Nasty, but not a real WTF.
    • The called method seems to do exception handling itself. Why? Because in Java you have to declare exception passing (throws Exception). So this method kills not only the exception, but also doesn't tell the calling method about the reason of the "not found", like "no database connection", "table name is null", "unkown table", "unknown column" or "record not found" -> WTF?!
    • I hope, that the shown method won't be called too often, otherwise the String concatination with "+" will fill the heap. Better: StringBuffer or (with Java 1.5) StringBuilder.
    • The select statement returns all records. I think it's excusable, since the method doesn't know the columns of the desired table.
    • Not putting the statement block of the if-statement in curly braces is no good style, but not a WTF.
    • Now to the mega WTF: He instanciates an exception (ClassNotFoundException) and assings it to the method result instead of throwing it! Gaah! That hertz!
    • The exception he uses doesn't fit to the error -> WTF?!
    • He returns either the found record or the exception, leaving it to the calling method to distinguish -> WTF?!
    My result: 5 WTFs, or 4, if you'd count the last one and the mega WTF as one.

    And yes: LOC is a real TLA. The language with the highest LOC level is COBOL.
  • (cs) in reply to joejoe
    Anonymous:
    You guys missed the biggest one ...

    executeQuery THROWS and exception itself!

    Also, there's zero differentiation between a "Database has been destroyed by haxors!" error and a "zero records found" error.

    Not necessarily, because he implemented the method himself (hint: which class does the method belong to?). And if this is Java (Java code convetions recommend, that "methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized." C# on the other hand recommend Pascal case method names), you have to handle exception for yourself, or you have to declare exception passing ("throws Exception" at the method header), otherwise the compiler would whine.

  • Hank Miller (unregistered) in reply to Jeff S
    Jeff S:

    What should the primary key be of a table listing U.S. States?



    The two letter post office abbreviation, or the full name spelled correctly.

    Do not use a number!   States were signed into being in order.  It may seem like trivia, but to some this order is important.  Someone will assume meaning of your numbers when it doesn't exist.  Calling Alaska anything other than the 50th state (49th?   I wasn't born then and can't remember) would be wrong.  

    You cannot use this number as any key.  There is no 40th state, both North Dakota and South Dakota claim 39.   (The president covered their names before he signed them into being, and then shuffeled the papers before revealing the names)

    This is always the problem wish assigning something meaningless as a primary key - someone may assume meaning you did not intend.
  • (cs) in reply to Hank Miller
    Anonymous:
    Jeff S:

    What should the primary key be of a table listing U.S. States?



    The two letter post office abbreviation, or the full name spelled correctly.

    Do not use a number!   States were signed into being in order.  It may seem like trivia, but to some this order is important.  Someone will assume meaning of your numbers when it doesn't exist.  Calling Alaska anything other than the 50th state (49th?   I wasn't born then and can't remember) would be wrong.  

    You cannot use this number as any key.  There is no 40th state, both North Dakota and South Dakota claim 39.   (The president covered their names before he signed them into being, and then shuffeled the papers before revealing the names)

    This is always the problem wish assigning something meaningless as a primary key - someone may assume meaning you did not intend.


    Why on earth would you expose an identity key to the user?  Identities are not generally meant for the user to see, it is to make it easier for relationships, joins, etc.
  • (cs) in reply to ammoQ
    ammoQ:
    Anonymous:

    a)in line 3 you are concatenating Strings, "select * from", and "table" are static strings. What internally is being done is that four objects are created everytime the query string is formed. So if you have 1000 query you would have the overhead of creating 5000 objects , i.e. 1000 for each String + 1000 for each object returned. Using StringBuffer will be a lot less resource intensive.


    Using StringBuffer would not change anything at all in this context.

    From the Java Documentation:


    String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

         x = "a" + 4 + "c"

    is compiled to the equivalent of:

         x = new StringBuffer().append("a").append(4).append("c")
    .toString()


    While this is correct in the context of this thread, it's a bit of a WTF that the StringBuffer documentation gives an example of code that will not be runtime concatenated with a StringBuffer, don't you?

  • (cs) in reply to diGriz
    diGriz:
    • I hope, that the shown method won't be called too often, otherwise the String concatination with "+" will fill the heap. Better: StringBuffer or (with Java 1.5) StringBuilder.


    How much better would StringBuffer instead of string concatination "+" do?

    "select * from "+ table + " where id = " + i

    compiles to

     new StringBuffer().append("select * from").append(table).append("where id =").append(i).toString()

    how would you improve that using StringBuffer explicitely?
    Do you really think one or two temporary string obects matter when you run a query against a database? executeQuery will probably create hundreds of temporary objects along it's way to the database and back!
  • (cs) in reply to Sridhar

    Anonymous:
    a)in line 3 you are concatenating Strings, "select * from", and "table" are static strings. What internally is being done is that four objects are created everytime the query string is formed. So if you have 1000 query you would have the overhead of creating 5000 objects , i.e. 1000 for each String + 1000 for each object returned. Using StringBuffer will be a lot less resource intensive.

    First of all, the Strings are not 'static', they are 'literal'.  And no, it will not create four Objects everytime the String is concatenated.  It creates one StringBuffer and one String, just like it would if you did it yourself.

    This is my biggest pet peeve in the Java world.  This advice is so wrong and given so often.

  • (cs) in reply to dubwai
    dubwai:

    While this is correct in the context of this thread, it's a bit of a WTF that the StringBuffer documentation gives an example of code that will not be runtime concatenated with a StringBuffer, don't you?



    Well, you are right that in the given example the compliler will most likely do the concatenation and no StringBuffer at all is used at runtime.
  • (cs) in reply to ammoQ

    ammoQ:

    how would you improve that using StringBuffer explicitely?
    Do you really think one or two temporary string obects matter when you run a query against a database? executeQuery will probably create hundreds of temporary objects along it's way to the database and back!

    Another great point.  Not only that, any DB communication is going to about 1000 times slower than creating a temporary Object or two.

    Also, creating and removing temporary Objects in newer versions of Java is very cheap because of generational GC and other features.

  • (cs) in reply to ammoQ
    ammoQ:
    dubwai:

    While this is correct in the context of this thread, it's a bit of a WTF that the StringBuffer documentation gives an example of code that will not be runtime concatenated with a StringBuffer, don't you?



    Well, you are right that in the given example the compliler will most likely do the concatenation and no StringBuffer at all is used at runtime.

    According the JLS, it will be compile time concatenated but I guess there may be non-compliant compilers out there.

  • (cs) in reply to ammoQ
    ammoQ:
    diGriz:
    • I hope, that the shown method won't be called too often, otherwise the String concatination with "+" will fill the heap. Better: StringBuffer or (with Java 1.5) StringBuilder.



    How much better would StringBuffer instead of string concatination "+" do?

    "select * from "+ table + " where id = " + i

    compiles to

     new StringBuffer().append("select * from").append(table).append("where id =").append(i).toString()

    how would you improve that using StringBuffer explicitely?

    Another point on this.  In JDK 1.5 the compiler uses StringBuilder for runtime concatenations.  So if you are one of these people who has insisted on using StringBuilder manually, you won't get that benefit when you upgrade but people who used + will.

  • M.C. Skwared (unregistered) in reply to diGriz

    diGriz:
    And yes: LOC is a real TLA. The language with the highest LOC level is COBOL.

    Not Assembly Language??!!??!!

  • (cs) in reply to M.C. Skwared
    Anonymous:

    diGriz:
    And yes: LOC is a real TLA. The language with the highest LOC level is COBOL.

    Not Assembly Language??!!??!!


    Believe me, I wrote programs in both languages, and COBOL programs tend to bloat. They need an excessive header (most of it is obsolete, but the compiler whines, if you don't do it), global variables which you need to redefine in order to access parts of it, limited sizes of variables (131,072 bytes, which can kill you, if you need a big array, because you have to adjust every element of the array to 2^n bytes, so you can attach several of those array to build 1 big array, because COBOL doesn't do bounds checking), they don't have a stack (which leads to 'interesting' conding, when you'd really need it), the length of lines are limited (IIRC from the 7th to the 79th column, which really bloats everything, so you need to continue some of your statements in the next line because of the talkative syntax), max. 1 statement per line (IIRC), and a few other things. I really prefer assembler, if I have to choose. Believe me, I regret, that I stopped assembler programming, but I'm still relieved I gave up COBOL.
  • luis (unregistered) in reply to bugsRus
    bugsRus:
    I think he meant that executeQuery possiblly THROWS an exception. It's part of the API -- see http://java.sun.com/j2se/1.3/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)

    Sure, java.sql.Statement.executeQuery() throws java.sql.SQLException. But I doubt the code in this submission is using that method-- it's using some method executeQuery() in the same class or up its inheritance graph. (The exception to this would be if the class where they WTF code resides implements the java.sql.Statement interface...)

  • luis (unregistered) in reply to Single Point of Failure
    Anonymous:
    and as many pointed out I didn't even think about the fact that the code didn't use a preparedStatement earlier..

    That's not a WTF, come on. There's no reason not to use and un-prepared Statement if that gets the job done. Using a PreparedStatement is more verbose and involved, doesn't necessarily get you a performance gain, and you might not care about the performance gain you get the times when it does.

  • (cs) in reply to luis

    Anonymous:
    bugsRus:
    I think he meant that executeQuery possiblly THROWS an exception. It's part of the API -- see http://java.sun.com/j2se/1.3/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
    Sure, java.sql.Statement.executeQuery() throws java.sql.SQLException. But I doubt the code in this submission is using that method-- it's using some method executeQuery() in the same class or up its inheritance graph. (The exception to this would be if the class where they WTF code resides implements the java.sql.Statement interface...)

    Assuming the code compiles, the executeMethod called in this WTF cannot be a Statement.executeQuery implementation precisely because that method throws a checked exception.  This method doesn't throw or catch an exception.

  • (cs) in reply to Anonymous
    Anonymous:
    I'm not sure about Java, but I cannot think of a good reason to initialize an object to null... ever.  Maybe someone could provide a better example?

    I'm not so sure about Java either, but in languages like C it is very advisable to initialize any and all pointer variables to NULL for roughly the same reasons why you should not do that in Java, as far as I have gathered from this thread.

    If you don't initialize a pointer in C, it just might contain any old bit pattern, which just might point to something. So using a non-initialized pointer can appear to work correctly while insidiously destroying some completely unrelated part of memory. If you use a pointer that has been set to NULL, it will blow up in your face. At least it will not corrupt anything or read random data out.

  • (cs) in reply to luis

    Anonymous:
    Anonymous:
    and as many pointed out I didn't even think about the fact that the code didn't use a preparedStatement earlier..
    That's not a WTF, come on. There's no reason not to use and un-prepared Statement if that gets the job done. Using a PreparedStatement is more verbose and involved, doesn't necessarily get you a performance gain, and you might not care about the performance gain you get the times when it does.

    You should reconsider that position.  PrepareStatement isn't just for performance, it will also protect you from SQL injection techniques and unescaped apostrophes and a lot of other problems that can come from running raw SQL created by code.

  • luis (unregistered) in reply to Sridhar
    Anonymous:
    a)in line 3 you are concatenating Strings, "select * from", and "table" are static strings. What internally is being done is that four objects are created everytime the query string is formed. So if you have 1000 query you would have the overhead of creating 5000 objects , i.e. 1000 for each String + 1000 for each object returned. Using StringBuffer will be a lot less resource intensive.

    That's not a WTF. There's no good reason not to concatenate Strings that way in a method that's not an actual performance bottleneck, demonstrated by profiling the execution of the program. And this method, after all, is executing a database query; guess which is more likely to dominate execution time for this method, the string concatenation, or the database query.

  • (cs) in reply to dubwai

    Anonymous:
    imo, there's nothing inherently wrong with using "select * ".

    if the database is designed properly, and the query is limiting the select correctly with WHERE statements, it is fully possible and even reasonable that returning the data in every column in the particular table is what is actually desired.

    This is why you use Stored Procedures in the first place.  The problem with putting SQL into your code is that you've technically hardcoded the structure of system A (the database) into system B (the app) and these are 2 entirely endependant things that might/will change in the future.

    And I don't even need to bring up the issue of SQL Injection, you can google for that.

    But if you want to nit lick, technically, listing your columns is faster than saying * as far as I've heard but I haven't explicitly benchmarked this myself but would love to hear the results of somebody testing it if they do it properly.

  • Hank Miller (unregistered) in reply to Ytram
    Ytram:


    Why on earth would you expose an identity key to the user?  Identities are not generally meant for the user to see, it is to make it easier for relationships, joins, etc.


    Not the end user.  The next programmer who has to maintain this thing.  

    Many identity keys are exposed to the end user though.   SSN for example, is an identity key required because names are not unique, and addresses change.  (though of course they screwed up issued the same key to several people a few times)
  • (cs) in reply to travisowens
    travisowens:

    But if you want to nit lick, technically, listing your columns is faster than saying * as far as I've heard but I haven't explicitly benchmarked this myself but would love to hear the results of somebody testing it if they do it properly.

    'Nit lick' is a new phrase to me.  I think I like it.

    I played around with this once when comparing drivers.  I found that for JDBC-ODBC, selecting a sigle column took just as long as select *.  For an native driver, selecting specific columns was significantly faster.  I don't know if it was the ODBC or the JDBC but that driver blows.

  • (cs) in reply to Hank Miller
    Hank Miller:
    Jeff S:

    What should the primary key be of a table listing U.S. States?



    The two letter post office abbreviation, or the full name spelled correctly.

    So when the company goes international and this table is extended to provide administrative regions for all countries instead of just states, you have to redo your key architecture.  No, for this examlpe you should use a meaningless key which is not exposed to the user.  A developer mistaking a sequence column with any external meaning is a WTF in itself.
  • (cs) in reply to Hank Miller
    Hank Miller:
    Ytram:


    Why on earth would you expose an identity key to the user?  Identities are not generally meant for the user to see, it is to make it easier for relationships, joins, etc.


    Not the end user.  The next programmer who has to maintain this thing.  

    Many identity keys are exposed to the end user though.   SSN for example, is an identity key required because names are not unique, and addresses change.  (though of course they screwed up issued the same key to several people a few times)


    Well I'd have to say that a programmer who doesn't understand the concept of an identity field has bigger problems than worrying about code maintenance.

    As for SSN, it should never be used as a primary key in a table because it at some point in time, the entry of SSN has to be made by a user, and users are the most incompetent people on earth.

    And let me restate what I said earlier, in general, identity fields do not need to be seen by the user.  There are of course going to be cases where it might be useful to them.
  • (cs) in reply to Anonymous
    Anonymous:
    Anonymous:

    Object obj /*= null */;
    try
    {
       ...
       obj = someFunctionOrAnother(...);
    } finally {
       if(obj!=null) doReleaseStuff(obj);
    }

     

    Would this not be better written as:

    <FONT face="Courier New" size=2>Object obj /*= null */;
    try
    {
       obj = someFunctionOrAnother(...);
    </FONT><FONT face="Courier New"><FONT size=2>} catch {
       obj = null;</FONT>
    </FONT><FONT face="Courier New" size=2>} finally {
       if(obj!=null) doReleaseStuff(obj);
    }</FONT>

    Or more likely:

    <FONT face="Courier New" size=2>


    Object obj = someFunctionOrAnother(...);
    try
    {
       ...
    } finally {
       doReleaseStuff(obj);
    }

    I'm not sure about Java, but I cannot think of a good reason to initialize an object to null... ever.  Maybe someone could provide a better example?</FONT>

    No, this would not.

    Java is pedantic about local objects; if it's not been initialized and you try to check the value, the compiler will yell at you. For example:

    String foo;
    if(bar) { foo = "bar"; }
    else { foo = "foo"; }
    System.out.println(foo);

    This code will cause a compiler error; foo may not have been initialized. Lets take your examples.

    <FONT face="Courier New" size=2>Object obj /*= null */;
    try
    {
       obj = someFunctionOrAnother(...);
    </FONT><FONT face="Courier New"><FONT size=2>} catch {
       obj = null;</FONT>
    </FONT><FONT face="Courier New" size=2>} finally {
       if(obj!=null) doReleaseStuff(obj);
    }</FONT>

    In the catch, why are you setting obj to null? Lets say that obj contains a critical resource that has to specifically be unlocked before it can be used again. If obj is not null, then you MUST unlock it with doReleaseStuff(obj).

    In your second example, if someFunctionOrAnother(...) throws an exception, it's not in the try block. And if you put the object declaration in the try block, then outside of the try/catch/finally, it will be out of scope. This could be awkward if you're going to do something else with it.

    Suffice to say, the fact that he's setting the object to null isn't a bad practice in and of itself; it's that he's setting it to null for no reason since the object will always be initialized in a way that the compiler will recognize, and that furthermore he's checking to see if it's null later on.

    Someone correct me if I'm wrong, but the way I've programmed java includes declaring objects initialized to null if their real initialization occurs in a further if, try, or other such scope.

  • (cs) in reply to algorythm

    OK, forums screwed that one up. Lets try again.

    Anonymous:
    Anonymous:

    Object obj /*= null */;
    try
    {
       ...
       obj = someFunctionOrAnother(...);
    } finally {
       if(obj!=null) doReleaseStuff(obj);
    }

     

    Would this not be better written as:

    <FONT face="Courier New" size=2>Object obj /*= null */;
    try
    {
       obj = someFunctionOrAnother(...);
    </FONT><FONT face="Courier New"><FONT size=2>} catch {
       obj = null;</FONT>
    </FONT><FONT face="Courier New" size=2>} finally {
       if(obj!=null) doReleaseStuff(obj);
    }</FONT>

    Or more likely:

    <FONT face="Courier New" size=2>


    Object obj = someFunctionOrAnother(...);
    try
    {
       ...
    } finally {
       doReleaseStuff(obj);
    }

    I'm not sure about Java, but I cannot think of a good reason to initialize an object to null... ever.  Maybe someone could provide a better example?</FONT>

    No, this would not.

    Java is pedantic about local objects; if it's not been initialized and you try to check the value, the compiler will yell at you. For example:

    String foo; if(bar) { foo = "bar"; } else { foo = "foo"; } System.out.println(foo);

    This code will cause a compiler error; foo may not have been initialized. Lets take your examples.

    <FONT face="Courier New" size=2>Object obj /*= null */;
    try
    {
       obj = someFunctionOrAnother(...);
    </FONT><FONT face="Courier New"><FONT size=2>} catch {
       obj = null;</FONT>
    </FONT><FONT face="Courier New" size=2>} finally {
       if(obj!=null) doReleaseStuff(obj);
    }</FONT>

    In the catch, why are you setting obj to null? Lets say that obj contains a critical resource that has to specifically be unlocked before it can be used again. If obj is not null, then you MUST unlock it with doReleaseStuff(obj).

    In your second example, if someFunctionOrAnother(...) throws an exception, it's not in the try block. And if you put the object declaration in the try block, then outside of the try/catch/finally, it will be out of scope. This could be awkward if you're going to do something else with it.

    Suffice to say, the fact that he's setting the object to null isn't a bad practice in and of itself; it's that he's setting it to null for no reason since the object will always be initialized in a way that the compiler will recognize, and that furthermore he's checking to see if it's null later on.

    Someone correct me if I'm wrong, but the way I've programmed java includes declaring objects initialized to null if their real initialization occurs in a further if, try, or other such scope.

  • (cs) in reply to Volmarias

    Ah, heck, I give up :(

  • (cs) in reply to Volmarias
    Volmarias:
    OK, forums screwed that one up. Lets try again.
    Anonymous:
    Anonymous:

    Object obj /*= null */;
    try
    {
       ...
       obj = someFunctionOrAnother(...);
    } finally {
       if(obj!=null) doReleaseStuff(obj);
    }

     

    Would this not be better written as:

    <FONT face="Courier New" size=2>Object obj /*= null */;
    try
    {
       obj = someFunctionOrAnother(...);
    </FONT><FONT face="Courier New"><FONT size=2>} catch {
       obj = null;</FONT>
    </FONT><FONT face="Courier New" size=2>} finally {
       if(obj!=null) doReleaseStuff(obj);
    }</FONT>

    Or more likely:

    <FONT face="Courier New" size=2>


    Object obj = someFunctionOrAnother(...);
    try
    {
       ...
    } finally {
       doReleaseStuff(obj);
    }

    I'm not sure about Java, but I cannot think of a good reason to initialize an object to null... ever.  Maybe someone could provide a better example?</FONT>

    No, this would not. Java is pedantic about local objects; if it's not been initialized and you try to check the value, the compiler will yell at you. For example: String foo; if(bar) { foo = "bar"; } else { foo = "foo"; } System.out.println(foo); This code will cause a compiler error; foo may not have been initialized. Lets take your examples.

    <FONT face="Courier New" size=2>Object obj /*= null */;
    try
    {
       obj = someFunctionOrAnother(...);
    </FONT><FONT face="Courier New"><FONT size=2>} catch {
       obj = null;</FONT>
    </FONT><FONT face="Courier New" size=2>} finally {
       if(obj!=null) doReleaseStuff(obj);
    }</FONT>

    In the catch, why are you setting obj to null? Lets say that obj contains a critical resource that has to specifically be unlocked before it can be used again. If obj is not null, then you MUST unlock it with doReleaseStuff(obj). In your second example, if someFunctionOrAnother(...) throws an exception, it's not in the try block. And if you put the object declaration in the try block, then outside of the try/catch/finally, it will be out of scope. This could be awkward if you're going to do something else with it. Suffice to say, the fact that he's setting the object to null isn't a bad practice in and of itself; it's that he's setting it to null for no reason since the object will always be initialized in a way that the compiler will recognize, and that furthermore he's checking to see if it's null later on. Someone correct me if I'm wrong, but the way I've programmed java includes declaring objects initialized to null if their real initialization occurs in a further if, try, or other such scope.

    If you can get avoid initializing to null, then you are better off not doing it, even if the initialization is much later in the method.  Actually, it especially true in that case.  The reason being that if you messed up and there is a path that will not initialize the variable, the code will not compile.  You should try not to set the variable to null on declaration if possible.

  • elsif (unregistered) in reply to Ytram

    Is a victim of identity thieft able to get a new SSN ? I think I've read that it is possible.

  • (cs) in reply to dubwai

    I'm curious what you suggest then.

    String foo;

    ...

    try { foo = null; foo = thisThrowsAnException(); ..... } catch { if(foo == null) ..... }

    Something to that extent? It seems somewhat messy to declare the variable, then set it equal to null, then assign it a value (or not), rather than just declaring it as null and assigning it a value (or not) later. Or would you prefer

    try { foo = blah(); ... } catch (SpecificException e) { foo = null }

    which seems fraught with its own problems, particularly if blah isn't the only method called that will throw a SpecificException.

    Besides, I usually don't assign null to variables unless the compiler complains about me, and if I do assign them to null I'm pretty good about making sure they actually get real values (or not) later.

  • (cs) in reply to Volmarias

    Volmarias:
    I'm curious what you suggest then. String foo; ... try { foo = null; foo = thisThrowsAnException(); ..... } catch { if(foo == null) ..... } Something to that extent? It seems somewhat messy to declare the variable, then set it equal to null, then assign it a value (or not), rather than just declaring it as null and assigning it a value (or not) later. Or would you prefer try { foo = blah(); ... } catch (SpecificException e) { foo = null } which seems fraught with its own problems, particularly if blah isn't the only method called that will throw a SpecificException. Besides,

    I don't have any idea why you would do the first thing.  It make no sense at all.

    If you can, you should declare foo inside the try block.  That makes a lot of that uneccesary.

    The one glaring case that has no good work around is when you need to cleanup in the finally block  People have suggested different syntax rules that might resolve that but I'm not aware of anything that is widely accepted or addresses the root issue.

    Volmarias:
    I usually don't assign null to variables unless the compiler complains about me

    That's all I am suggesting.  Well, that and considering resolving the compilation in other ways than assigning null.

  • (cs)

    I believe this is the WTF with the highest response per line of code ratio. And Alex, how did those two guys post comments weeks or months before you did? That's pretty impressive.

  • (cs) in reply to Manni
    Manni:

    I believe this is the WTF with the highest response per line of code ratio. And Alex, how did those two guys post comments weeks or months before you did? That's pretty impressive.



    It's actually  not the only post with comments prior to Alex's.. I think there's a couple more like that too.
  • (cs) in reply to JThelen

    What's also impressive, since i can't edit the post, is that the two prior replies happened one and six months prior.

  • (cs) in reply to FrostCat
    FrostCat:
    dubwai:
    Anonymous:

    Alex Papadimoulis:
    ** Three Letter Acronym, which happens to be the best self-describing thing ever.

    Wanna know something really geeky?

    It's actually 'Three Letter Abbreviation'. An 'acronymn' is an abbreviation that forms a word, like 'laser' or 'radar'.

    Grammar geekiness rules! [:D]

    Cheers,
    mabster

    http://merriamwebster.com/cgi-bin/dictionary?va=acronym

    http://merriamwebster.com/cgi-bin/dictionary?book=Dictionary&va=abbreviation

    examples from these:

    acronym: FBI

    abbreviation: amt (for amount)

    Remember, kids, all acronyms are abbreviations, but not all abbreviations are acronyms.  Quick test:  in set theory, how do we define that relationship?

    If we want to be really anal about it, "FBI" is an initialism. An acronym can be pronounced as a word, while an initialism is pronounced as discrete letters. "LED" should be an acronym, since "ledd" is perfectly pronounceable, but for some odd reason people pronounced it "ell-ee-dee". Compare that to a true acronym like "fubar" or "snafu".

  • (cs) in reply to Manni
    Manni:

    And Alex, how did those two guys post comments weeks or months before you did? That's pretty impressive.

    I noticed the clock on the server was four minutes off, so I went to update it. I accidently changed the month to January, so I changed it to the correct month (June). Then I realized that it is, in fact, July.

  • (cs) in reply to rogthefrog
    rogthefrog:
    FrostCat:
    dubwai:
    Anonymous:

    Alex Papadimoulis:
    ** Three Letter Acronym, which happens to be the best self-describing thing ever.

    Wanna know something really geeky?

    It's actually 'Three Letter Abbreviation'. An 'acronymn' is an abbreviation that forms a word, like 'laser' or 'radar'.

    Grammar geekiness rules! [:D]

    Cheers,
    mabster

    http://merriamwebster.com/cgi-bin/dictionary?va=acronym

    http://merriamwebster.com/cgi-bin/dictionary?book=Dictionary&va=abbreviation

    examples from these:

    acronym: FBI

    abbreviation: amt (for amount)

    Remember, kids, all acronyms are abbreviations, but not all abbreviations are acronyms.  Quick test:  in set theory, how do we define that relationship?

    If we want to be really anal about it, "FBI" is an initialism. An acronym can be pronounced as a word, while an initialism is pronounced as discrete letters. "LED" should be an acronym, since "ledd" is perfectly pronounceable, but for some odd reason people pronounced it "ell-ee-dee". Compare that to a true acronym like "fubar" or "snafu".



    fubar and snafu are by far the two best acronyms ever. 

    Here's a fairly comprehensive Wiki of other acronyms and initialisms.

    http://en.wikipedia.org/wiki/List_of_acronyms_and_initialisms

Leave a comment on “Exception Disfunction”

Log In or post as a guest

Replying to comment #:

« Return to Article