classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

style question


From: Eric Blake
Subject: style question
Date: Sun, 24 Feb 2002 23:41:26 -0700

I'm looking at fixing a bug in Long.decode(), and came across a style
question.

Which is prefered, performing array bound checks throughout a method, or
enclosing the algorithm in a try-catch block which converts an
IndexOutOfBoundsException into a NumberFormatException?  Using a
try-catch block emits less bytecode, and if decode() is used on valid
strings as the common case, it reduces overhead to not check the
bounds.  In the exceptional case, my proposal must create and discard an
IndexOutOfBoundsException, while bounds checking avoids that, but the
method fails in either case.

Here's a diff, (not quite to GNU coding standards, to preserve
indentation), that illustrates my question:

Index: java/lang/Long.java
===================================================================
RCS file: /cvsroot/classpath/classpath/java/lang/Long.java,v
retrieving revision 1.14
diff -u -r1.14 Long.java
--- java/lang/Long.java 25 Feb 2002 01:36:03 -0000      1.14
+++ java/lang/Long.java 25 Feb 2002 06:38:54 -0000
@@ -355,27 +355,25 @@
[...]
   public static Long decode(String str)
   {
+try
+  {
     boolean isNeg = false;
     int index = 0;
     int radix = 10;
-    final int len;
-
-    if ((len = str.length()) == 0)
-      throw new NumberFormatException();
+    final int len = str.length();
 
     // Negative numbers are always radix 10.
     if (str.charAt(0) == '-')
@@ -405,10 +403,13 @@
           radix = 8;
       }
 
-    if (index >= len)
-      throw new NumberFormatException();
-
+    // Change parseLong to throw IndexOutOfBoundsException...
     return new Long(parseLong(str, index, len, isNeg, radix));
+  }
+catch (IndexOutOfBoundsException e)
+  {
+    throw new NumberFormatException();
+  }
   }
 
   /**
-- 
This signature intentionally left boring.

Eric Blake             address@hidden
  BYU student, free software programmer



reply via email to

[Prev in Thread] Current Thread [Next in Thread]