473,573 Members | 2,950 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python less error-prone than Java

You will often hear that for reasons of fault minimization, you should
use a programming language with strict typing:
http://turing.une.edu.au/~comp284/Le...ure/node1.html

I just came across a funny example in which the opposite is the case.

The following is a binary search algorithm in Java. It searches a value
in an ordered array a of ints:

public static int binarySearch(in t[] a, int key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}

Now the same thing, directly converted to Python:

def binarySearch(a, key):
low = 0
high = len(a) - 1
while low <= high:
mid = (low + high) / 2
midVal = a[mid]
if midVal < key:
low = mid + 1
elif midVal > key:
high = mid - 1;
else:
return mid # key found
return -(low + 1) # key not found.

What's better about the Python version? First, it will operate on *any*
sorted array, no matter which type the values have.

But second, there is a hidden error in the Java version that the Python
version does not have.

See the following web page if you dont find it ;-)
http://googleresearch.blogspot.com/2...it-nearly.html

-- Christoph
Jun 3 '06 #1
26 3207
Actually, you're wrong on all levels.

First: It's perfectly simple in Java to create a binary sort that sorts
all arrays that contain objects; so wrong there.

Secondly: The bug has nothing to do with static typing (I'm guessing
that's what you meant. Both Python and Java are strongly typed). The
problem is that ints are bounded in Java. They could easily have been
ints and then automatically coerced to (equivalent to) longs when they
got bigger; that they aren't is more a design fault than anything to do
with static typing. The equivalent in Python would have been if an
overflow exception was raised when the int got too big. It might have
been that way, typing or no typing.

Christoph Zwerschke wrote:
You will often hear that for reasons of fault minimization, you should
use a programming language with strict typing:
http://turing.une.edu.au/~comp284/Le...ure/node1.html

I just came across a funny example in which the opposite is the case.

The following is a binary search algorithm in Java. It searches a value
in an ordered array a of ints:

public static int binarySearch(in t[] a, int key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}

Now the same thing, directly converted to Python:

def binarySearch(a, key):
low = 0
high = len(a) - 1
while low <= high:
mid = (low + high) / 2
midVal = a[mid]
if midVal < key:
low = mid + 1
elif midVal > key:
high = mid - 1;
else:
return mid # key found
return -(low + 1) # key not found.

What's better about the Python version? First, it will operate on *any*
sorted array, no matter which type the values have.

But second, there is a hidden error in the Java version that the Python
version does not have.

See the following web page if you dont find it ;-)
http://googleresearch.blogspot.com/2...it-nearly.html

-- Christoph


Jun 3 '06 #2
Simon Percivall <pe*******@gmai l.com> wrote:
...
with static typing. The equivalent in Python would have been if an
overflow exception was raised when the int got too big. It might have
been that way, typing or no typing.


Indeed, it _used_ to be that way --
<http://docs.python.org/lib/module-exceptions.html > STILL says...:

exception OverflowError

Raised when the result of an arithmetic operation is too large to be
represented. This cannot occur for long integers (which would rather
raise MemoryError than give up). Because of the lack of standardization
of floating point exception handling in C, most floating point
operations also aren't checked. For plain integers, all operations that
can overflow are checked except left shift, where typical applications
prefer to drop bits than raise an exception.
Actually, the docs are obsolete on this point, and an int becomes a long
when that's necessary:
sys.maxint+1

2147483648L

but, this operation _would_ have raised OverflowError in old-enough
versions of Python (not sure exactly when the switch happened...).
Alex
Jun 4 '06 #3
In article <e5**********@o nline.de>,
Christoph Zwerschke <ci**@online.de > wrote:
You will often hear that for reasons of fault minimization, you should
use a programming language with strict typing:
http://turing.une.edu.au/~comp284/Le...ure/node1.html

I just came across a funny example in which the opposite is the case.

Jun 4 '06 #4
Simon Percivall wrote:
First: It's perfectly simple in Java to create a binary sort that
sorts all arrays that contain objects; so wrong there.
My point was that the *same* Java source example, directly converted to
Python would *automatically* accept all kinds of arrays. No need to make
any extra efforts. By the way, how would you do it in Java? With
function overloading? I would not call that perfectly simple.
Secondly: The bug has nothing to do with static typing (I'm guessing
that's what you meant. Both Python and Java are strongly typed). The
problem is that ints are bounded in Java. They could easily have been
ints and then automatically coerced to (equivalent to) longs when they
got bigger; that they aren't is more a design fault than anything to
do with static typing. The equivalent in Python would have been if an
overflow exception was raised when the int got too big. It might have
been that way, typing or no typing.


Yes, sorry, I meant static typing, not strict typing. But I still do
think that the bug has to do with static typing. You're right, the
direct cause is that ints are bounded in Java, and not bounded in
Python, and that it could well be the other way round. However, doing it
the other way round would not be so clever and appropriate for the
respective language due to the difference in static typing.

Java could coerce the result to long, but then it would still crash when
the result is stored back to the statically typed variable. So that
would not be very clever.

And Python could produce an overflow error (and did in the past), but
taking advantage of the possibilities of dynamic typing and
automatically producing longs is a cleverer solution for Python, and
that's why it was proposed and accepted in PEP237.

So the difference in static typing is actually the deeper reason why
ints were made to behave differently in the two languages.

-- Christoph
Jun 4 '06 #5
Cameron Laird wrote:
So, here's my summary: Python's a nice language--a very nice one.
It's safer to use than Java in many ways. Python's typing is
STRICTER than Java's, but it's also dynamic, so people get to argue
for decades about which is a better model. Anyone who thinks typing
is a first-order determinant of code quality is making a big mistake
though, anyway.


Yes, sorry. It has nothing to do with strict, but with static typing.
And I should not have chosen such a general subject line (I just meant
to be funny, but sounded more like a troll). I had just noticed that the
direct translation of that Java program to Python would not have that
subtle bug and found that this was worth mentioning.

-- Christoph
Jun 4 '06 #6
In article <e5**********@o nline.de>,
Christoph Zwerschke <ci**@online.de > wrote:
Simon Percivall wrote:
First: It's perfectly simple in Java to create a binary sort that
sorts all arrays that contain objects; so wrong there.
My point was that the *same* Java source example, directly converted to
Python would *automatically* accept all kinds of arrays.


And the same code converted to SML would automatically work on all
kinds of arrays and SML is statically typed. It's a language issue,
not a typing issue.
No need to make any extra efforts.
By the way, how would you do it in Java? With
function overloading? I would not call that perfectly simple.


Since Java doesn't allow function overloading that clearly can't be
the way. J2SE 5.0 allows generic classes and functions that operate
on generic containers. There are some gotchas, but it's not drastically
more complex than the original int-only java code.

Alan
--
Defendit numerus
Jun 4 '06 #7
Alan Morgan wrote:
Since Java doesn't allow function overloading that clearly can't be
the way. J2SE 5.0 allows generic classes and functions that operate
on generic containers. There are some gotchas, but it's not drastically
more complex than the original int-only java code.


Doesn't Java restrict generics to only operate on reference types so
you can't produce a generic binary search that operates on arrays where
the item type may be int?

Neil
Jun 4 '06 #8
In article <3V************ ***@news-server.bigpond. net.au>,
Neil Hodgson <ny************ *****@gmail.com > wrote:
Alan Morgan wrote:
Since Java doesn't allow function overloading that clearly can't be
the way. J2SE 5.0 allows generic classes and functions that operate
on generic containers. There are some gotchas, but it's not drastically
more complex than the original int-only java code.


Doesn't Java restrict generics to only operate on reference types so
you can't produce a generic binary search that operates on arrays where
the item type may be int?


Yup, you have to wrap int (and double and float and...). Blame type
erasure.

Alan
--
Defendit numerus
Jun 4 '06 #9
Christoph Zwerschke <ci**@online.de > writes:
What's better about the Python version? First, it will operate on
*any* sorted array, no matter which type the values have.

But second, there is a hidden error in the Java version that the
Python version does not have.


While I can see your point, I'd say you are totally in the wrong level
here.

With Java generics you can sort a list and still keeping the type of
the contents defined. This is makes the code less error-prone. But why
would you implement binary search as the standard library already has
it for both arrays and lists? This is one big thing that makes code
less error-prone: using existing well made libraries. You can find
binary search from python standard library too (but actually the API
in Java is a bit better, see the return values).

Well, you can say that the binary search is a good example and in real
code you would use the stuff from the libraries. I'd say it is not
good example: How often will you write such algorithms? Very rarely.

Integer overflows generally are not those errors you run into in
programs. The errors happening most often are from my point of view:

1. null pointer errors
2. wrong type (class cast in Java, some weird missing attribute in python)
3. array/list index out of bounds

First and third ones are the same in about every language. The second
one is one where the typing can make a difference. If in the code
level you know the type all the way, there is much less changes of it
being wrong. (The sad thing in the Java generics is that it is a
compile time only thing and that causes some really weird stuff, but
that is too off topic to here.)

In python passing sequences for a function and also from a function is
very easy. You can very easily pass a sequence as argument list. You
can also very easily return a sequence from the function and even
split it to variables directly. This is very powerful tool, but it has
a problem too: How can you change what you return without breaking the
callers? There are many cases where passing an object instead of a
sequence makes the code much easier to develop further.

What's the point? The point is that neither with Java or Python you
want to be doing things in the low level. You really want to be doing
stuff with objects and using existing libraries as much as possible.
And in that level Java might be less error-prone as it does restrict
the ways you can shoot yourself more.

--
Ilpo Nyyssönen # biny # /* :-) */
Jun 4 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1568
by: Juergen R. Plasser | last post by:
Hi, I have installed libxml2-2.5.7, libxslt-1.0.30 from source and the bindings libxml2-python-2.5.7. Everything seems to compile fine, but when I try to import the libxml2 library in python I get the following error: Python 2.1.3 (#1, Feb 10 2003, 10:37:44) on linux2
0
1563
by: Sebastien de Menten | last post by:
I am trying to use ScriptControl under Excel (Windows XP) with the code: Global sc As New MSScriptControl.ScriptControl Public Function os_getcwd() sc.Language = "python" sc.ExecuteStatement ("import os") os_getcwd = sc.Eval("os.getcwd()") End Function
2
2283
by: Christian | last post by:
Hello, i have an apache 1.3 server with python on debian. Python works fine but the scripts wont´t work. This easy script i want to do on apache: #!/usr/bin/python import os os.getcwd()
3
9677
by: Rakesh | last post by:
In my Python code fragment, I want to write a code fragment such that the minimum element of a tuple is subtracted from all the elements of a given tuple. When I execute the following python script I get the following interpreter error.
5
4374
by: Madhu R. Vajrala | last post by:
Hello All, I am very new to Python, trying to install it from source (ftp://ftp.sunfreeware.com/pub/freeware/SOURCES/python-2.3.3.tar.gz) on Sun Solaris-9 (SPARC). But getting the below error message during configure. Also while uncompressing, it is returning the checksum doesnt match error as well. Configure Error:
3
3155
by: yaffa | last post by:
hey folks i get this error: Python interpreter error: unsupported operand type(s) for |: when i run this line of code: for incident in bs('tr', {'bgcolor' : '#eeeeee'} | {'bgcolor' : 'white'} ): any idea what i'm doing wrong here?
7
4606
by: Xah Lee | last post by:
Python doc problem: http://python.org/doc/2.4.2/lib/os-file-dir.html makedirs( path) Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Throws an error exception if the leaf directory already exists or cannot be created. The default mode is 0777...
3
2404
by: Martin P. Hellwig | last post by:
Hey all, I'd like to wrap libpam so that I can use that for authentication and password management. I build ctypes (0.9.9.6) on my platform via ports. Now according to OpenPAM documentation all sessions start with pam_start(). According to the man page it should contain this: pam_start(const char *service, const char *user, const struct...
0
1397
by: benjamin.grant | last post by:
can configure, make and install everything fine. I'm using python 2.4 I have ubuntu dapper drake. I am trying to install hplip which requires python. When I do this, this also works but while running the following error occurs: Traceback (most recent call last): File "/usr/local/bin/hp-setup", line 31, in ? import readline, gzip...
2
1627
by: redefined.horizons | last post by:
I've written a few classes that I have been testing in IDLE. However, every time I make a change to the classes based on the testing I have to walk through all he steps of preparing the classes for testing again. So I wrote a script that does all the set-up work for me. The only problem is when I run this script using the Python interpreter...
0
7781
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7699
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8027
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
5594
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5292
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3733
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2216
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1304
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1041
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.