Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Java vs. C++ vs. ??? for cross-platform application?

0 views
Skip to first unread message

Mike Rupke

unread,
Sep 4, 2002, 11:55:01 AM9/4/02
to
I seek the collective wisdom of the programming specialists in this
newsgroup.

A client recently expressed interest in my company building a
cross-platform commercial application. The platforms/OS include
Unix/Linux, Windows, and Mac. Linux support includes the small
PDA-like and TabletPC-like Linux devices now under development. The
application will be fairly resource-intensive, processing and
rendering XML documents, among other things. It is important to note
that our company comprises several XML experts in the areas of
interest to the client, the main reason they approached us, but we
have no one on staff at this time with any commercial software
development experience.

At this stage, we only need to provide the client with an approximate,
first order estimate of the time and cost to develop the application,
along with a pre-conceptual architectural design of the application's
end-user interface. Right now we prefer not to hire any seasoned
software-development programmers (and development leaders) for a
project that may never get funded, but obviously we do intend to get
some consulting help, especially for the programming-side of things.

One fundamental consideration in our group is what core programming
language to use for this application. It is certainly contentious:
some of our people are advocating Java, while others favor C++ or
other language. This needs to be resolved early on, if for no other
reason group harmony. I suspect that even among the consultants we
hire we will get similar differences of opinion.

An important requirement to the client is that the application must be
very compact, very fast, and be portable to the above-listed OS and
associated devices. It does greatly help in that we may build and
distribute application executables specifically optimized for a
particular platform/OS. So we can have a Windows version, a Mac
version, a Linux desktop version, a "John Doe Linux PDA device"
version, etc. Obviously we need to be able to port the application as
new Linux devices come on the market. Additionally, support for other
OS besides Windows, Mac OS X and Unix/Linux may be added in the
future.

To my lay perspective, and contrary to what I perceive as the popular
wisdom of the day, this requirement tends not to favor Java, at least
when using Java code natively to be compiled by the end-user at
run-time (vs. precompiled for a specific platform/OS, assuming there
is such a thing as OS-specific precompiled Java---is there?)

My perspective is further strengthened by anecdotal observation that
native Java applications generally tend to run very slow even on fast
desktops. If this observation is overall true, I hate to imagine
trying to run a native Java application on a PDA-like device.

It is very likely I have not provided enough information to get any
sort of definitive answers, but your thoughts and opinions are
certainly welcome. Any online information sources delving into the
topic of Java vs. C++ vs. ??? are certainly desired.

Thanks.

Mike

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]
[ about comp.lang.c++.moderated. First time posters: do this! ]

Francis Glassborow

unread,
Sep 5, 2002, 5:33:39 AM9/5/02
to
In article <b0ddddf5.02090...@posting.google.com>, Mike Rupke
<mike_...@hotmail.com> writes

>An important requirement to the client is that the application must be
>very compact, very fast, and be portable to the above-listed OS and
>associated devices.

Very fast suggests you need to hit the metal which would generally
favour C++. Very compact means that you need to consider both the
quality of the optimisers and the runtime overhead. For example if a JVM
is built into a platform you only need to consider the code size for the
Java itself, but if you have to have a JVM then that could add a great
deal of extra overhead.

However the most important element is going to be the availability of
skilled, professional programmers. These are scarce in both C++ and
Java.

--
Francis Glassborow ACCU
64 Southfield Rd
Oxford OX4 1PA +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

Reed Hedges

unread,
Sep 5, 2002, 6:12:34 AM9/5/02
to
Hi, I recommend checking out the availability of cross-platform C++
libraries and tools you may need (e.g. wxWindows
http://www.wxwindows.org), and use C++ if possible. If not, then Java
will probably work, with certain limitations on speed, size, language
features, and cumbersome execution requirements (running in the
interpreter/VM). In my (small amount of) experience, Java can be
useful for some things, especially prototyping, but eventually can
present some problems.

reed
http://interreality.org

Hyman Rosen

unread,
Sep 5, 2002, 6:14:35 AM9/5/02
to
Mike Rupke wrote:
> I seek the collective wisdom of the programming
> specialists in this newsgroup.

I suggest you get paid up front, and do no work for
this client "on spec". The project sounds like a
disaster in the making.

Michiel Salters

unread,
Sep 5, 2002, 9:16:40 AM9/5/02
to
mike_...@hotmail.com (Mike Rupke) wrote in message news:<b0ddddf5.02090...@posting.google.com>...

> I seek the collective wisdom of the programming specialists in this
> newsgroup.
>
> A client recently expressed interest in my company building a
> cross-platform commercial application. The platforms/OS include
> Unix/Linux, Windows, and Mac. Linux support includes the small
> PDA-like and TabletPC-like Linux devices now under development. The
> application will be fairly resource-intensive, processing and
> rendering XML documents, among other things.
[ SNIP ]

> My perspective is further strengthened by anecdotal observation that
> native Java applications generally tend to run very slow even on fast
> desktops. If this observation is overall true, I hate to imagine
> trying to run a native Java application on a PDA-like device.

With the current crop of desktops, Java is often fast enough. Certainly
if you're not developing for the shrink-wrap market, you can just
demand beefier hardware.

However, once you get to laptops and PDAs Java speed start to hurt.
Worse, battery life suffers. Memory use may suffer, but there is
a tradeoff between the fixed JVM size and possibly smaller (byte)code.
Small applications therefore suffer most.

In a recent project I knew rather well, my company ran into the same
problem when the actual PDA's became available. The Java app was
easily fast enough on the desktop, but couldn't be made fast enough
for the PDA. The result was that a full rewrite in C or C++ is
now required.

James Kanze

unread,
Sep 5, 2002, 5:21:49 PM9/5/02
to
mike_...@hotmail.com (Mike Rupke) wrote in message
news:<b0ddddf5.02090...@posting.google.com>...

[...]


> One fundamental consideration in our group is what core programming
> language to use for this application. It is certainly contentious:
> some of our people are advocating Java, while others favor C++ or
> other language. This needs to be resolved early on, if for no other
> reason group harmony. I suspect that even among the consultants we
> hire we will get similar differences of opinion.

I don't quite understand why. I'd think that the decision regarding
language wouldn't be necessary until at least the high level design was
done. Also, I don't see why everything has to be in one language. I
know a lot of applications which use Java for the GUI work, C++ for the
server side, some C, or even Cobol at the host level, and some perl or
different shell scripts to hold everything together.

> To my lay perspective, and contrary to what I perceive as the popular
> wisdom of the day, this requirement tends not to favor Java, at least
> when using Java code natively to be compiled by the end-user at
> run-time (vs. precompiled for a specific platform/OS, assuming there
> is such a thing as OS-specific precompiled Java---is there?)

> My perspective is further strengthened by anecdotal observation that
> native Java applications generally tend to run very slow even on fast
> desktops. If this observation is overall true, I hate to imagine
> trying to run a native Java application on a PDA-like device.

Java's speed can vary widely. For some applications, it can be as fast
as C++, if not faster.

What is probably more important is that Java locks you into a certain
number of decisions. Thus, in the Java applications I've worked on,
performance has been a problem due to class loading; in C++, we'd have
just linked everything static, and been done with it.

> It is very likely I have not provided enough information to get any
> sort of definitive answers, but your thoughts and opinions are
> certainly welcome. Any online information sources delving into the
> topic of Java vs. C++ vs. ??? are certainly desired.

There are two major differences, at the highest level:

- Java makes a large number of decisions for you. With C++, you are
the boss. When the decisions Java has made are acceptable, it is
much easier to create the Java application; no matter what decisions
you make in C++, you have to implement them. Thus, my example using
dynamic class loading: it was the wrong solution for our
application, but Java didn't give us any choice.

One critical point here is robustness. Java defines a certain
level, and it is impossible to write programs that crash just
because someone looked at the keyboard. (It is, in fact, very
difficult to write programs that crash at all. Where C++ will
typically crash, Java just gives wrong results.) On the other hand,
the level of robustness defined by Java is very, very low, and it is
very difficult, if not impossible, to raise it. Whereas well
written C++ can be as robust as you want -- it's just a question of
how much work you want to put into it.

- Java is "in". That means that anyone trying to support the latest
"in" technology will support Java first. XML is rather in as well,
and there are probably more libraries to support it in Java than in
C++. (On the other hand, my experience with XML under Java is that
it is a real resource hog. The latest "in" libraries are rarely the
most efficient.)

At a lower level, while Java can be as fast as C++ for purely CPU
oriented work, the extra levels it adds will typically make it slower
for anything involving the system, and because of its dynamic link and
compile model and garbage collection, it will typically require a lot
more memory than the same application in C++. (On the other hand, C++
doesn't have garbage collection, which means that it is a lot easier to
leak memory. And an application which leaks memory ends up taking a lot
more memory than it should. There are, however, very good third party
tools, such as Purify, or the Boehm collector, which address this
problem.)

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

Carl Daniel

unread,
Sep 5, 2002, 5:25:24 PM9/5/02
to
"Mike Rupke" <mike_...@hotmail.com> wrote in message
news:b0ddddf5.02090...@posting.google.com...

> One fundamental consideration in our group is what core programming
> language to use for this application. It is certainly contentious:
> some of our people are advocating Java, while others favor C++ or
> other language. This needs to be resolved early on, if for no other
> reason group harmony. I suspect that even among the consultants we
> hire we will get similar differences of opinion.

Of course, this is a C++ newsgroup, so you can probably imagine how the
responses will be biased - I hope you've also posted this query to a similar
Java newsgroup to hear both sides.

That said, I would never advocate Java for such a project: the risks of one
or more of the desired platforms being completely unattainable are simply
too high (write-once, debug-and-rewrite-everywhere). As others have pointed
out, the performance of a well-written Java app on modern desktops is
usually acceptable, due in no small part to the aggressively optmiizing
JIT-compilers incorporated into modern JVMs. For small hand-held platforms,
however, you won't find such performance. These devices will likely be
based on the "J2ME", which uses the so-called "KVM" - a JVM which has been
optimized for small footprint and the resulting lousy performance - useful
for the toy applications that run on cell-phones only.

If the application truly needs to address such a broad variety of platforms
and has strict performance implications, I wouldn't even think of
implementing in anything other than C or C++. I'd favor C++, but I'd want
to do a thorough review of available compiler/library implementations for
each target platform before choosing C++ over C. While it's unfortunate and
often misguided, most embedded developers fear C++ - as a result, toolsets
for embedded work are much more likely to offer a high performance C
solution than C++.

Even if the target platforms where strictly modern desktop OSes, I still
wouldn't recommend Java. Re-distributing an end-user application that's
based on Java is nothing short of a nightmare, in my experience. There are
simply too many huge variables which are outside your control (the quality
of the JVM being the most important).

-cd

Robert Klemme

unread,
Sep 6, 2002, 4:57:51 AM9/6/02
to

some thoughts:

Mike Rupke schrieb:


>
> I seek the collective wisdom of the programming specialists in this
> newsgroup.
>
> A client recently expressed interest in my company building a
> cross-platform commercial application. The platforms/OS include
> Unix/Linux, Windows, and Mac. Linux support includes the small
> PDA-like and TabletPC-like Linux devices now under development. The
> application will be fairly resource-intensive, processing and
> rendering XML documents, among other things. It is important to note
> that our company comprises several XML experts in the areas of
> interest to the client, the main reason they approached us, but we
> have no one on staff at this time with any commercial software
> development experience.

pro Java:

XML handling is quite good supported in Java, this comprises
parsing, building DOM trees and custom trees

internationalization support is build into the language (all
chars are unicode), no additional libraries are needed and all
java apps can use it

from a software engineering perspective, Java is easier and
thus more effective

portable


pro C++:

faster, especially with gui applications

probably better supported on linux and exotic OS, although for
a gui based app you likely have to rewrite the whole UI if you
cannot use a cross platform library

less resource consuming, this could be a killer for java on
PDA's


both:

good support for communication (CORBA, Java has additionally
RMI)



> An important requirement to the client is that the application must be
> very compact, very fast, and be portable to the above-listed OS and
> associated devices. It does greatly help in that we may build and
> distribute application executables specifically optimized for a
> particular platform/OS. So we can have a Windows version, a Mac
> version, a Linux desktop version, a "John Doe Linux PDA device"
> version, etc. Obviously we need to be able to port the application as
> new Linux devices come on the market. Additionally, support for other
> OS besides Windows, Mac OS X and Unix/Linux may be added in the
> future.

this seems to hint towards C++. however, the criteria are a bit
soft, so it is not clear what "real fast" means. java
applications are not slow per se, but swing gui applications tend
to feel slow (apart from errors swing does have here and there).

> To my lay perspective, and contrary to what I perceive as the popular
> wisdom of the day, this requirement tends not to favor Java, at least
> when using Java code natively to be compiled by the end-user at
> run-time (vs. precompiled for a specific platform/OS, assuming there
> is such a thing as OS-specific precompiled Java---is there?)
>
> My perspective is further strengthened by anecdotal observation that
> native Java applications generally tend to run very slow even on fast
> desktops. If this observation is overall true, I hate to imagine
> trying to run a native Java application on a PDA-like device.

if you need a gui and use swing, then yes: that makes java slow.

regards

robert

Thore B. Karlsen

unread,
Sep 6, 2002, 8:00:53 AM9/6/02
to
On 5 Sep 2002 17:21:49 -0400, ka...@gabi-soft.de (James Kanze) wrote:

[...]

> One critical point here is robustness. Java defines a certain
> level, and it is impossible to write programs that crash just
> because someone looked at the keyboard. (It is, in fact, very
> difficult to write programs that crash at all. Where C++ will
> typically crash, Java just gives wrong results.)

I've had more Java programs (commercial and free) crash on me due to
uncaught exceptions (why can't people learn to catch nullpointer
exceptions) or buggy JVMs than I have ever had C or C++-programs crash
on me for any reason. Personally, I think the problem of writing robust
programs in C or C++ is blown way out of proportion, because in practice
I don't have many problems with it either with my code or the
applications I use. I have many more complaints about the robustness of
the Java software I've used.

--
Be seeing you.

Carl Daniel

unread,
Sep 6, 2002, 8:09:43 AM9/6/02
to
"James Kanze" <ka...@gabi-soft.de> wrote in message
news:d6651fb6.02090...@posting.google.com...

> - Java is "in". That means that anyone trying to support the latest
> "in" technology will support Java first. XML is rather in as well,
> and there are probably more libraries to support it in Java than in
> C++. (On the other hand, my experience with XML under Java is that
> it is a real resource hog. The latest "in" libraries are rarely the
> most efficient.)

Thanks in no small part to the W3C DOM, there are an adequate supply of XML
implementations for just about any imaginable platform. You're right about
them being resource hungry: in my experience, the available C++ solutions
are little or no better than the corresponding Java libraries (case in
point: Xerces-C++, which is a near-literal translation of Xerces-J into
C++).

For a recent project, I had cause to evaluate XML facilities available for
C, C++, C#, Java, JScript, VBScript and Visual Basic. Thanks to the model
provided by the W3C DOM, very similar facilities are available for each. Of
those environments, the one I was the most impressed with, and which, I
suspect, was the least resource intensive was the C solution provided by
libxml (www.xmlsoft.org). Unfortunately, the project didn't allow me the
opportunity to actually compare resources/performance among the platforms,
so that's just a gut feeling.

-cd

Pete Becker

unread,
Sep 6, 2002, 8:40:13 AM9/6/02
to
Robert Klemme wrote:
>
> internationalization support is build into the language (all
> chars are unicode), no additional libraries are needed and all
> java apps can use it

All chars in Java are Unicode 2.0. Unfortunately, Unicode is now at 3.2,
and Java's chars are too small.

--
Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)

Pete Becker

unread,
Sep 6, 2002, 8:40:38 AM9/6/02
to
"Thore B. Karlsen" wrote:
>
> (why can't people learn to catch nullpointer
> exceptions)

Because Java doesn't have pointers. <g>

--
Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Thorsten Ottosen

unread,
Sep 6, 2002, 11:34:54 PM9/6/02
to

"Robert Klemme" <bob....@gmx.net> wrote in message
news:3D778FBD...@gmx.net...
>
> some thoughts:

>
> pro Java:
>
> XML handling is quite good supported in Java, this comprises
> parsing, building DOM trees and custom trees
>

Any reason this stuff should not be part of C++ libraries from Borland or
Rougewave etc?

> internationalization support is build into the language (all
> chars are unicode), no additional libraries are needed and all
> java apps can use it

wrong. Internationalization requires intervention from the programmer and
definition of
resource files and calls via a resource loader instead of the string. I have
not done similar stuff in C++,
but I don't think the difference is large.

> from a software engineering perspective, Java is easier and
> thus more effective

Lee's put is this way: C++ allows library writers to create
faster/safer/smaller libraries whereas the
interface should be no more complicated than in a java version. Soon the
lack advanced feautures in java
(what you called "easier") becomes a bottleneck.

> portable
perhaps. If you think you can expect that an application will run the same
way over a wide range of virtual
machines, then think again.

>
> pro C++:
>
> faster, especially with gui applications
>
> probably better supported on linux and exotic OS, although for
> a gui based app you likely have to rewrite the whole UI if you
> cannot use a cross platform library

What about Qt? It has newly added support for some linux based handhelds.

regards

--Thorsten

James Kanze

unread,
Sep 7, 2002, 6:19:41 AM9/7/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D778FBD...@gmx.net>...
> some thoughts:

> Mike Rupke schrieb:

> > I seek the collective wisdom of the programming specialists in this
> > newsgroup.

> > A client recently expressed interest in my company building a
> > cross-platform commercial application. The platforms/OS include
> > Unix/Linux, Windows, and Mac. Linux support includes the small
> > PDA-like and TabletPC-like Linux devices now under development. The
> > application will be fairly resource-intensive, processing and
> > rendering XML documents, among other things. It is important to
> > note that our company comprises several XML experts in the areas of
> > interest to the client, the main reason they approached us, but we
> > have no one on staff at this time with any commercial software
> > development experience.

> pro Java:

> XML handling is quite good supported in Java, this comprises
> parsing, building DOM trees and custom trees

I would hope that there are also third party libraries for C++ which
handle this now. Also, when we tried to use Java for parsing XML (about
two years ago), we found that the libraries were real resource hogs.

> internationalization support is build into the language (all chars
> are unicode), no additional libraries are needed and all java apps can
> use it

Officially, Java and C++ are on equal footing here; I'd even say that
C++ has the advantage, because a C++ implementation can implement full
Unicode support, while Java can't. In practice, however, it depends. A
lot of C++ implementations come with almost no working locales, while
every Java implementation I've seen comes with the full set.

> from a software engineering perspective, Java is easier and thus
> more effective portable

Java is more portable than C++, although don't believe that it is 100%
portable either.

From a software engineering perspective, it is incredibly difficult to
write robust software in Java. C++ has an enormous edge here (but a lot
of applications don't seem to care about being really robust).

> pro C++:

> faster, especially with gui applications

Probably because its GUI libraries are more mature.

> probably better supported on linux and exotic OS, although for a gui
> based app you likely have to rewrite the whole UI if you cannot use a
> cross platform library

> less resource consuming, this could be a killer for java on PDA's

> both:

> good support for communication (CORBA, Java has additionally RMI)

> > An important requirement to the client is that the application must
> > be very compact, very fast, and be portable to the above-listed OS
> > and associated devices. It does greatly help in that we may build
> > and distribute application executables specifically optimized for a
> > particular platform/OS. So we can have a Windows version, a Mac
> > version, a Linux desktop version, a "John Doe Linux PDA device"
> > version, etc. Obviously we need to be able to port the application
> > as new Linux devices come on the market. Additionally, support for
> > other OS besides Windows, Mac OS X and Unix/Linux may be added in
> > the future.

> this seems to hint towards C++. however, the criteria are a bit soft,
> so it is not clear what "real fast" means. java applications are not
> slow per se, but swing gui applications tend to feel slow (apart from
> errors swing does have here and there).

In general, it will depend on what you are doing, AND where. The most
mature Java implementations can be very fast, but you only find them on
Windows and maybe Solaris. And they require a lot of memory for the
HotSpot compiler.

--
James Kanze mailto:jka...@caicheuvreux.com

Conseils en informatique oriente objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Carl Daniel

unread,
Sep 7, 2002, 11:05:12 AM9/7/02
to
"Robert Klemme" <bob....@gmx.net> wrote in message
news:3D778FBD...@gmx.net...
> pro Java:
>
> XML handling is quite good supported in Java, this comprises
> parsing, building DOM trees and custom trees

I'd actually put this in the "con" column for Java. Thanks to the W3C DOM
for XML, there is actually a great deal of standardization between XML
implementations across a wide range of platforms/languages. In a recent
project, I was able to compare:

- Xerces2+Xalan for Java
- MSXML on Windows (as seen from C, C++, JScript, VBScript and VB)
- System.Xml on .NET (as seen from C#)
- libxml for ANSI C

and in the past I've used:

- Xerces-C 1.7 / C++

Of these DOM implementations, Xerces+Xalan was the most difficult to use and
among the most resource intensive.

If you're on a Windows platform, it's hard to beat MSXML4, but for something
that's truly cross-platform and minimally resource intensive, I highly
recommend libxml and C. It should be straightforward to write a thin C++
wrapper for libxml for those who'd prefer a more C++ interface.

While it's a little off-topic for this NG, I hope the mods will agree that
there's been enough interest in this thread to indulge me a bit more here.

You can easily see that XML DOM availability is a non-starter when it comes
to language choice by examing some code snippets. The following snippets
all do exactly the same thing: create a DOM and populate it with a few
elements:

<Root>
<Authentication>
<SignOnID>text-signon-id</SignOnID>
<Password>text-password</Password>
</Authentication>
</Root>

C/C++/libxml:
---------------------
xmlDocPtr pDoc = xmlNewDoc("1.0");
xmlNodePtr pRoot = xmlNewDocNode(pDoc,NULL,"Root",NULL);
xmlNodePtr pAuth = xmlNewChild(pRoot, NULL, "Authentication", NULL);
xmlNodePtr pSignon = xmlNewTextChild(pAuth, NULL, "SignOnID", szSignon);
xmlNodePtr pPassword = xmlNewTextChild(pAuth, NULL, "Password",
szPassword);
xmlDocSetRootElement(pDoc,pRoot);

C++/MSXML (Windows specific):
----------------------
MSXML2::IXMLDOMDocument2Ptr pDoc;
pDoc.CreateInstance(L"Msxml2.DOMDocument.4.0");
MSXML2::IXMLDOMNodePtr pRoot =
pDoc->appendChild(pDoc->createElement(L"Root"));
MSXML2::IXMLDOMNodePtr pAuth = pRoot->appendChild(
pDoc->createElement(L"Authentication"));
pAuth->appendChild(pDoc->createElement(L"SignOnID"))->text =
m_strUserID.c_str();
pAuth->appendChild(pDoc->createElement(L"Password"))->text =
m_strPassword.c_str();

C#/System.Xml (.NET specific - System.Xml is included in Rotor and will be
in GNU.NET and the other open source .NET work-alike):
------------------------
XmlDocument doc = new XmlDocument();
XmlNode root = doc.AppendChild(doc.CreateElement("Root"));
XmlNode auth = root.AppendChild(doc.CreateElement("Authentication"));

auth.AppendChild(doc.CreateElement("SignOnID")).AppendChild(doc.CreateTextNo
de(m_strUserId));

auth.AppendChild(doc.CreateElement("Password")).AppendChild(doc.CreateTextNo
de(m_strPassword));

Java/Xerces:
-------------------------
Document doc =new DocumentImpl();
Node root = doc.appendChild(doc.createElement("Root"));
Node auth = root.appendChild(doc.createElement("Authentication"));

auth.appendChild(doc.createElement("SignOnID")).appendChild(doc.createTextNo
de(m_strUserName));

auth.appendChild(doc.createElement("Password")).appendChild(doc.createTextNo
de(m_strPassword));

JScript/MSXML:
--------------------------
var doc = new ActiveXObject("Msxml2.DOMDocument.4.0");
var root = doc.appendChild(doc.createElement("Root"));
var auth = root.appendChild(doc.createElement("Authentication"));
auth.appendChild(doc.createElement("SignOnID")).text = this.m_strUser;
auth.appendChild(doc.createElement("Password")).text = this.m_strPassword;

----------------------------

Other DOM manipulations are as similar. The various libraries differ more
in the way they offer XPath and XSLT support (all do) than in the core COM.
The biggest lack in the Xerces solution is the lack of a standard facility
for serializing a DOM. The same DOMWriter class is repeated in each & every
Xerces sample program since the library itself offers no such support. Of
course, there are other XML implementations for Java besides Xerces -
perhaps they do a better job.

I hope this has been sufficiently illustrative to be worth the bandwidth :)

-cd

Thorsten Ottosen

unread,
Sep 7, 2002, 11:05:39 AM9/7/02
to

"James Kanze" <ka...@gabi-soft.de> wrote in message
news:d6651fb6.02090...@posting.google.com...
[snip]

> From a software engineering perspective, it is incredibly difficult to
> write robust software in Java. C++ has an enormous edge here (but a lot
> of applications don't seem to care about being really robust).

Could you elaborate on this? How do you define "software engineering
perspective" and "robust"?
Could you give some examples?

Thanks

-Thorsten

Rob

unread,
Sep 8, 2002, 11:04:44 AM9/8/02
to
"Thorsten Ottosen" <nes...@cs.auc.dk> wrote in message
news:alamh4$626$1...@sunsite.dk...

>
> "Robert Klemme" <bob....@gmx.net> wrote in message
> news:3D778FBD...@gmx.net...
> >
> > some thoughts:
>
> >
> > pro Java:
> >
> > XML handling is quite good supported in Java, this comprises
> > parsing, building DOM trees and custom trees
> >

There are C++ XML parsers. Have a look at;

http://xml.apache.org/xerces-c/

for an example.

> Any reason this stuff should not be part of C++ libraries from Borland or
> Rougewave etc?
>
> > internationalization support is build into the language (all
> > chars are unicode), no additional libraries are needed and all
> > java apps can use it
> wrong. Internationalization requires intervention from the programmer and
> definition of
> resource files and calls via a resource loader instead of the string. I
have
> not done similar stuff in C++,
> but I don't think the difference is large.

Arguably, Java has the upper edge here. Most java implementations
I've seen have good internationalisation support. The quality of
support across C++ environments is more variable.

>
> > from a software engineering perspective, Java is easier and
> > thus more effective
> Lee's put is this way: C++ allows library writers to create
> faster/safer/smaller libraries whereas the
> interface should be no more complicated than in a java version. Soon the
> lack advanced feautures in java
> (what you called "easier") becomes a bottleneck.

To be precise, the translation between "easier" and "effective"
depends on what you're trying to do. As a rough rule of thumb,
the more demanding requirements of your application, the more likely
you are to require more "advanced" language features. There are
certainly some application types that are more easily implemented
in Java, but there are also some that are more easily implemented
using C++. And quite a few in the middle ground where either
language is a sensible choice.

>
> > portable
> perhaps. If you think you can expect that an application will run the same
> way over a wide range of virtual
> machines, then think again.

Portability of a Java application really depends on quality of the
Java virtual machines on the systems you wish to target. And
the quality of these is variable. I have often seen people who
care about portability of a Java application refer to Java as
"write once, debug everywhere", and that is only *slightly*
tongue in cheek. For critical applications, the only way to give
a solid assurance of portability --- in C++ or Java --- is to
design and test very carefully.

>
> >
> > pro C++:
> >
> > faster, especially with gui applications

With GUI? GUI in C++ invariably depends on third party
libraries, as GUI is not part of standard C++ at all.
As such, speed of GUI based applications depends on
the good graces of implementers of those libraries.

Robert Klemme

unread,
Sep 9, 2002, 9:17:57 AM9/9/02
to

advocatus diaboli (= java) speaking...

Thorsten Ottosen schrieb:


> > internationalization support is build into the language (all
> > chars are unicode), no additional libraries are needed and all
> > java apps can use it
> wrong. Internationalization requires intervention from the programmer and
> definition of
> resource files and calls via a resource loader instead of the string. I have
> not done similar stuff in C++,
> but I don't think the difference is large.

ok, formally speaking it's not part of the language. but it's
part of the stdlib - and that comes with every installation
whereas localization support is not equally well with every c++
installation.

> > from a software engineering perspective, Java is easier and
> > thus more effective
> Lee's put is this way: C++ allows library writers to create
> faster/safer/smaller libraries whereas the
> interface should be no more complicated than in a java version.

i doubt it. if you take the several different ways of argument
passing in c++ vs. only one (plus one for basic types) - this
makes interfaces more complex and more difficult to use.

> Soon the lack advanced feautures in java
> (what you called "easier") becomes a bottleneck.

in which cases? could you please give an example?

> > portable
> perhaps. If you think you can expect that an application will run the same
> way over a wide range of virtual
> machines, then think again.

well, at least there ARE these vms. a c++ application has to be
recompiled and often you need platform specific includes or
compiler switches and the like.

> > pro C++:
> >
> > faster, especially with gui applications
> >
> > probably better supported on linux and exotic OS, although for
> > a gui based app you likely have to rewrite the whole UI if you
> > cannot use a cross platform library
>
> What about Qt? It has newly added support for some linux based handhelds.

well, as i said: you have to rewrite the gui IF you cannot use a
cross platform library. i didn't say there are none. :-)

regards

robert

Robert Klemme

unread,
Sep 9, 2002, 9:20:03 AM9/9/02
to

James Kanze schrieb:


> > pro Java:
>
> > XML handling is quite good supported in Java, this comprises
> > parsing, building DOM trees and custom trees
>
> I would hope that there are also third party libraries for C++ which
> handle this now. Also, when we tried to use Java for parsing XML (about
> two years ago), we found that the libraries were real resource hogs.

which might depend on XML and usage of DOM tree builders as
well. if you don't handle strings carefully you can easily blow
memory usage because of repeated storing of similar strings (e.g.
element and attribute names). and often you can advise the
parser to really ignore ignorable white space and not store it.

> > internationalization support is build into the language (all chars
> > are unicode), no additional libraries are needed and all java apps can
> > use it
>
> Officially, Java and C++ are on equal footing here; I'd even say that
> C++ has the advantage, because a C++ implementation can implement full
> Unicode support, while Java can't. In practice, however, it depends. A
> lot of C++ implementations come with almost no working locales, while
> every Java implementation I've seen comes with the full set.

yep.

> > from a software engineering perspective, Java is easier and thus
> > more effective portable
>
> Java is more portable than C++, although don't believe that it is 100%
> portable either.
>
> From a software engineering perspective, it is incredibly difficult to
> write robust software in Java. C++ has an enormous edge here

why that?

> (but a lot of applications don't seem to care about being really robust).

well, that's another story... :-)

> > pro C++:
>
> > faster, especially with gui applications
>
> Probably because its GUI libraries are more mature.

possibly. there's a lot of criticism around for swing but SWT
(from IBM) as seen in eclipse does feel better.

> In general, it will depend on what you are doing, AND where.

yeah, it's a complex matter and probably we have too scarce
information.

regards

robert

James Kanze

unread,
Sep 9, 2002, 9:52:05 PM9/9/02
to
"Rob" <nos...@nonexistant.com> wrote in message
news:<3d7b409d$1...@news.iprimus.com.au>...

> "Thorsten Ottosen" <nes...@cs.auc.dk> wrote in message
> news:alamh4$626$1...@sunsite.dk...

> > > portable


> > perhaps. If you think you can expect that an application will run
> > the same way over a wide range of virtual machines, then think
> > again.

> Portability of a Java application really depends on quality of the
> Java virtual machines on the systems you wish to target. And the
> quality of these is variable. I have often seen people who care about
> portability of a Java application refer to Java as "write once, debug
> everywhere", and that is only *slightly* tongue in cheek. For
> critical applications, the only way to give a solid assurance of
> portability --- in C++ or Java --- is to design and test very
> carefully.

In this case, the only real problem with Java is that it has been
oversold. It is decidedly easier to write portable applications in Java
than in C++, but the difference is one of degree. You still have to
work for portability, including addressing a certain number of issues up
front. And the problem here with Java is not that there are a lot of
issues; there are a lot less than with C++. The problem is that it is
very difficult to obtain any information about them. The answer is
always: if it's Java, it's portable, which is ridiculous.

--
James Kanze mailto:jka...@caicheuvreux.com

Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 9, 2002, 9:54:04 PM9/9/02
to
"Thorsten Ottosen" <nes...@cs.auc.dk> wrote in message
news:<ald3bj$kqc$1...@sunsite.dk>...

> "James Kanze" <ka...@gabi-soft.de> wrote in message
> news:d6651fb6.02090...@posting.google.com...
> [snip]
> > From a software engineering perspective, it is incredibly difficult
> > to write robust software in Java. C++ has an enormous edge here
> > (but a lot of applications don't seem to care about being really
> > robust).

> Could you elaborate on this? How do you define "software engineering
> perspective" and "robust"? Could you give some examples?

Very simple. For Java, the definition of "robust" means that it doesn't
crash. And it is, in fact, very difficult to get a Java program to
crash, whereas with C++...

IMHO, however, just not crashing isn't sufficient. I also want the
correct results. To ensure that I get the correct results, it is
important to be able to instrument the code. There are many ways of
doing this, but one the most important is to ensure pre- and
post-conditions. Some languages (Eiffel) provide this as part of the
language. In C++, the idiom has developped in which the public
interface uses no virtual functions, but rather forwards to private (or
protected) virtual functions, wrapping the virtual function call with
instrumentation. Java's interfaces don't allow this.

With regards to crashing, of course, one of the best ways to crash is
via a version mismatch in a dynamically loaded part of the program.
Robust programs only use dynamic loading in a limited fashion, only
where it is appropriate, and separate the dynamically loadable parts
into large, coherent blocks. Java practically requires dynamic loading
on a class by class basis, which noticeably increases the risk of
getting a version mismatch. (Note that normally, a version mismatch
will be caught by the class loader, and so will not result in a core
dump. But I fail to see the difference between an exception from which
you cannot recover and a crash.)

I'd add that the Java libraries are incredibly underdocumented, and
often, the only way of knowing what a function does is to look at its
sources. But much of the Java library has no equivalent in standard
C++, and I rather suspect that a lot of third party C++ libraries aren't
much better.

--
James Kanze mailto:jka...@caicheuvreux.com

Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 9, 2002, 9:55:31 PM9/9/02
to
"Thore B. Karlsen" <s...@6581.com> wrote in message
news:<8fjfnu8vsainkio9c...@4ax.com>...

> On 5 Sep 2002 17:21:49 -0400, ka...@gabi-soft.de (James Kanze) wrote:

> [...]

> > One critical point here is robustness. Java defines a certain
> > level, and it is impossible to write programs that crash just
> > because someone looked at the keyboard. (It is, in fact, very
> > difficult to write programs that crash at all. Where C++ will
> > typically crash, Java just gives wrong results.)

> I've had more Java programs (commercial and free) crash on me due to
> uncaught exceptions (why can't people learn to catch nullpointer
> exceptions) or buggy JVMs than I have ever had C or C++-programs crash
> on me for any reason.

But an uncaught exception doesn't crash. There's no core dump. :-)

In fact, I agree, and for the user, there really isn't much difference
between an exception from which you cannot recover, and a core dump.
Unless, maybe, the exception occurs when handling a Swing event -- in
that case, it just silently disappears, and the user has no idea that
something is wrong:-).

> Personally, I think the problem of writing robust programs in C or C++
> is blown way out of proportion, because in practice I don't have many
> problems with it either with my code or the applications I use.

I'm not sure I'd agree. Writing robust programs in any language takes
skill, and knowing what you are doing, and IMHO has been downplayed far
too much in all languages. Less, certainly, in C++ than with Java, but
even in C++, we still need more effort before the issue is treated with
the seriousness it deserves.

> I have many more complaints about the robustness of the Java software
> I've used.

Sort of confirms my experience.

To be fair to Java, part of this is due to the marketing hype
surrounding the language, and not the language itself. (The problem
with null pointers, for example, is entirely due to marketing hype and
poor documentation -- the language itself is just as capable of handling
it as C++.)

But only part of it, and globally, even skipping the hype, where
reliability is essential, I'd go with C++ any day over Java.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 10, 2002, 5:24:32 PM9/10/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D7C5DA1...@gmx.net>...

> advocatus diaboli (= java) speaking...

> Thorsten Ottosen schrieb:
> > > internationalization support is build into the language (all
> > > chars are unicode), no additional libraries are needed and all
> > > java apps can use it
> > wrong. Internationalization requires intervention from the
> > programmer and definition of resource files and calls via a resource
> > loader instead of the string. I have not done similar stuff in C++,
> > but I don't think the difference is large.

> ok, formally speaking it's not part of the language. but it's part of
> the stdlib - and that comes with every installation whereas
> localization support is not equally well with every c++ installation.

Both Java and C++ provide all of the necessary hooks for localization in
their libraries, or almost: Java locks you out of ISO 10646, because the
character type must be exactly 16 bits, and C++ is missing positionnal
formatting. (I'm tempted to say that both are killer criteria. At
least in C++, I can work around the problem, but at an incredible
effort.)

In practice, of course, the real question is how good is the support for
locales and external codes sets in your implementation. In this
regards, JDK has set a very high standard, and very few C++
implementations come near to it -- perhaps the Dinkumware library, but
certainly not g++.

> > > from a software engineering perspective, Java is easier and thus
> > > more effective
> > Lee's put is this way: C++ allows library writers to create
> > faster/safer/smaller libraries whereas the interface should be no
> > more complicated than in a java version.

> i doubt it. if you take the several different ways of argument
> passing in c++ vs. only one (plus one for basic types) - this makes
> interfaces more complex and more difficult to use.

I don't think so. The lack of out parameters, for example, requires
additional types, etc., in Java, which can render the interface more
complicated. The fact that you never know when a null pointer is
legitimate, and when it isn't, nor the function might modify your
variable, or when it might not, is also a minus for Java.

In both languages, however, the real complexity in the interfaces comes
from poor design. In both languages, too, the standard libraries have
some blatent examples of this. (std::string, or java.awt.Dimension,
come to mind.)

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 10, 2002, 5:26:34 PM9/10/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D7C5BED...@gmx.net>...

> > From a software engineering perspective, it is incredibly difficult
> > to write robust software in Java. C++ has an enormous edge here

> why that?

I gave a few exemples in another response, but I think the real answer
lies in a criticism of C++ by David Chase, that I read some years back.
I think he hit the nail on the head with regards to C++: it has all of
the wrong defaults. Of the defaults he cited, however, Java only
changes two of them: garbage collection by default, and array bounds
checking on by default. Both of these changes are improvements. But
there remain the other problems AND several issues that weren't issues
when he wrote the article: Java uses threads (almost) by default, and
Java uses dynamic loading by default.

The result is that in any robust program, you are constantly working to
avoid the defaults. Which usually isn't that difficult in C++. The
language is open, and allows an incredible amount of flexibility, not
only to shoot yourself in the foot, but also to create firewalls, and
defend yourself against coding errors. In Java, it is almost
impossible: you can't implement programming by contract, and you can't
avoid dynamic loading (and the problems of version management it
entails), for example. You can't declare anything const. You have
absolute dynamic typing everywhere: you can't (or you couldn't until
recently) easily limit the types you put into a standard collection
(except for an array). (One place where C++ actually has the correct
default -- containers are normally typesafe, and when you need variable
types, you need to take extra programming steps to get them.)

--
James Kanze mailto:jka...@caicheuvreux.com

Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Thorsten Ottosen

unread,
Sep 11, 2002, 8:15:43 AM9/11/02
to

"Robert Klemme" <bob....@gmx.net> wrote in message
news:3D7C5DA1...@gmx.net...

>
> advocatus diaboli (= java) speaking...
>
> Thorsten Ottosen schrieb:

> > Lee's put is this way: C++ allows library writers to create


> > faster/safer/smaller libraries whereas the
> > interface should be no more complicated than in a java version.
>
> i doubt it. if you take the several different ways of argument
> passing in c++ vs. only one (plus one for basic types) - this
> makes interfaces more complex and more difficult to use.
>
> > Soon the lack advanced feautures in java
> > (what you called "easier") becomes a bottleneck.
>
> in which cases? could you please give an example?

of course. try writing a procedure that swaps the reference of two objects
or two integers for that sake, I would like to use
your code then.

I often need to define foo( int ). A little later I need foo(Object) and I
have to replicate the code each time because the
language lacks templates. And the I need to define foo(string)...

In general I don't need to worry about memory, but I always have to close
somthing, If I don't I might get a memory
leak in some obscure way (yes, memory leaks exist in java too, and the
virtual machine could leak too!). I have to
close files, database, locks (in fact, every resource) manually, which is
tedious and leads to more errors.

> > > portable
> > perhaps. If you think you can expect that an application will run the
same
> > way over a wide range of virtual
> > machines, then think again.
>
> well, at least there ARE these vms. a c++ application has to be
> recompiled and often you need platform specific includes or
> compiler switches and the like.

sure, that is an inherent property of any bytecode.

The real problem is the implementation of the virtual machine. Since you
don't know exactly
which virtual machine your program will run on, it is _really_ hard to test
for that platform. Basically, you
need to test any potential vm on every os, right. Moreover, snall
differences in the implementation
of vms could produce really hard to find bugs. Eg., it is well known that
atomicity properties differ
from vm to vm.


> > > pro C++:
> > >
> > > faster, especially with gui applications
> > >
> > > probably better supported on linux and exotic OS, although for
> > > a gui based app you likely have to rewrite the whole UI if you
> > > cannot use a cross platform library
> >
> > What about Qt? It has newly added support for some linux based
handhelds.
>
> well, as i said: you have to rewrite the gui IF you cannot use a
> cross platform library. i didn't say there are none. :-)

But then it is hypothetical "have to" and as such irrelevant.

regards

--Thorsten

Thorsten Ottosen

unread,
Sep 11, 2002, 8:16:23 AM9/11/02
to

"James Kanze" <ka...@gabi-soft.de> wrote in message
news:d6651fb6.02090...@posting.google.com...
> "Thorsten Ottosen" <nes...@cs.auc.dk> wrote in message
> news:<ald3bj$kqc$1...@sunsite.dk>...
> > "James Kanze" <ka...@gabi-soft.de> wrote in message
> > news:d6651fb6.02090...@posting.google.com...
> > [snip]
> > > From a software engineering perspective, it is incredibly difficult
> > > to write robust software in Java. C++ has an enormous edge here
> > > (but a lot of applications don't seem to care about being really
> > > robust).
>
> > Could you elaborate on this? How do you define "software engineering
> > perspective" and "robust"? Could you give some examples?
>
> Very simple. For Java, the definition of "robust" means that it doesn't
> crash. And it is, in fact, very difficult to get a Java program to
> crash, whereas with C++...
I guess that is right. However, I recently crashed the NetBeans ide totally.
The virtual machine can crash too.

I think "robustness" covers exception-safety. In this area C++ is more
mature
than Java.


> IMHO, however, just not crashing isn't sufficient. I also want the
> correct results. To ensure that I get the correct results, it is
> important to be able to instrument the code. There are many ways of
> doing this, but one the most important is to ensure pre- and
> post-conditions. Some languages (Eiffel) provide this as part of the
> language. In C++, the idiom has developped in which the public
> interface uses no virtual functions, but rather forwards to private (or
> protected) virtual functions, wrapping the virtual function call with
> instrumentation. Java's interfaces don't allow this.

That is a very good idiom which I haven't thought about. And postconditions
can still
be checked in each virtual function, if one wants to. But I guess you could
do it in Java, albeit
less elegant.

--
Thorsten

A. G. McDowell

unread,
Sep 11, 2002, 8:18:28 AM9/11/02
to
{The answer to the latter part of this post would be off topic here as
it is about how to do something in Java, so if you want to respond to
that please move it to a java newsgroup. -mod/fwg}

In article <d6651fb6.02090...@posting.google.com>, James
Kanze <ka...@gabi-soft.de> writes


...
>
>IMHO, however, just not crashing isn't sufficient. I also want the
>correct results. To ensure that I get the correct results, it is
>important to be able to instrument the code. There are many ways of
>doing this, but one the most important is to ensure pre- and
>post-conditions. Some languages (Eiffel) provide this as part of the
>language. In C++, the idiom has developped in which the public
>interface uses no virtual functions, but rather forwards to private (or
>protected) virtual functions, wrapping the virtual function call with
>instrumentation. Java's interfaces don't allow this.
>

...
Let me guess that what you are doing here is allowing subclasses to
override methods without allowing them to call those methods directly.
The methods in the public interface of the superclass work by checking
pre-conditions, calling the overridden methods, and then checking post-
conditions.

Would it be possible to provide similar accessibility restrictions in
Java by delegation?: e.g.

public interface Sort
{
void sort(Comparable[] s);
}

public class SortChecker
{
private Sort s;
SortChecker(Sort forS)
{
s = forS;
}
public void sort(Comparable[] toSort)
{
assert toSort != null;
s.sort(toSort);
for (int i = 1; i < toSort.length; i++)
{
assert toSort[i - 1].compareTo(toSort[i]) <= 0;
}
}
}

(N.B. compile with javac -source 1.4 to get
assert statement to work)
--
A. G. McDowell

Robert Klemme

unread,
Sep 11, 2002, 8:44:34 AM9/11/02
to

James Kanze schrieb:


> > Could you elaborate on this? How do you define "software engineering
> > perspective" and "robust"? Could you give some examples?
>
> Very simple. For Java, the definition of "robust" means that it doesn't
> crash. And it is, in fact, very difficult to get a Java program to
> crash, whereas with C++...
>
> IMHO, however, just not crashing isn't sufficient. I also want the
> correct results. To ensure that I get the correct results, it is
> important to be able to instrument the code. There are many ways of
> doing this, but one the most important is to ensure pre- and
> post-conditions. Some languages (Eiffel) provide this as part of the
> language. In C++, the idiom has developped in which the public
> interface uses no virtual functions, but rather forwards to private (or
> protected) virtual functions, wrapping the virtual function call with
> instrumentation. Java's interfaces don't allow this.

hm, maybe i did not exactly grasp what you mean by this. what's
the difference to having public methods in java, that do the
condition checking and forwarding the call to another private or
protected method? you can even go as far as to declare the
public method final which whould ensure, that no sub class will
supersede this.

or is your major point, that i cannot incorporate these checks
into an interface? then you could simply use abstract classes
for this.

> With regards to crashing, of course, one of the best ways to crash is
> via a version mismatch in a dynamically loaded part of the program.
> Robust programs only use dynamic loading in a limited fashion, only
> where it is appropriate, and separate the dynamically loadable parts
> into large, coherent blocks. Java practically requires dynamic loading
> on a class by class basis, which noticeably increases the risk of
> getting a version mismatch. (Note that normally, a version mismatch
> will be caught by the class loader, and so will not result in a core
> dump. But I fail to see the difference between an exception from which
> you cannot recover and a crash.)

the configuration of components is indeed a problem with java.
obviously sun discovered this topic not earlier than java 2,
which was when they included certain meta data into the manifes
file. but still there are problems: the packaging of the sax api
classes / interfaces and xml parsers is a good example. this is
awful...

> I'd add that the Java libraries are incredibly underdocumented, and
> often, the only way of knowing what a function does is to look at its
> sources. But much of the Java library has no equivalent in standard
> C++, and I rather suspect that a lot of third party C++ libraries aren't
> much better.

i can't judge on this, because i lack excessive experience with a
greater number of commercial c++ libs. from my experience with
java there are areas which are undocumented (unfortunately the
jdbc interfaces are among them) but most of the time you can get
along quite well with what you get.

just my 5cent

robert

Robert Klemme

unread,
Sep 11, 2002, 2:44:24 PM9/11/02
to

James Kanze schrieb:

otoh this makes things clearer, because you immediately know what
a method returns and don't have to scan the parameter list for
out parameters... then, if you omit exception specifications and
do not commment them in c++, the user has no other chance of
knowing which exceptions there might occur without looking at the
code.

> The fact that you never know when a null pointer is
> legitimate, and when it isn't, nor the function might modify your
> variable, or when it might not, is also a minus for Java.

well, you don't know in c++ either, do you? the only chance is
to put a comment there - in java and in c++. with the slight
advantage of java having a std mechanism (javadoc) to comment
things whereas there is a lot of tools that do so for c++. of
course some of these tools can do far more than javadoc can. but
a standard solution to commenting makes life easier.

> In both languages, however, the real complexity in the interfaces
comes
> from poor design. In both languages, too, the standard libraries have
> some blatent examples of this. (std::string, or java.awt.Dimension,
> come to mind.)

of course. it's just that i think that java makes life easier in
some aspects and from a pragmatic point of view has real
advantages.

regards

robert

Robert Klemme

unread,
Sep 11, 2002, 2:46:19 PM9/11/02
to

James Kanze schrieb:


>
> Robert Klemme <bob....@gmx.net> wrote in message
> news:<3D7C5BED...@gmx.net>...
>
> > > From a software engineering perspective, it is incredibly
difficult
> > > to write robust software in Java. C++ has an enormous edge here
>
> > why that?
>
> I gave a few exemples in another response, but I think the real answer
> lies in a criticism of C++ by David Chase, that I read some years
back.
> I think he hit the nail on the head with regards to C++: it has all of
> the wrong defaults. Of the defaults he cited, however, Java only
> changes two of them: garbage collection by default, and array bounds
> checking on by default. Both of these changes are improvements. But
> there remain the other problems AND several issues that weren't issues
> when he wrote the article: Java uses threads (almost) by default, and
> Java uses dynamic loading by default.

what method bindings? in c++ virtual is not default, which i
regard as a problem, too. in java it's only virtual. threads:
you don't have to bother about them if you don't use them.
dynamic loading is a problem, agreed.

> The result is that in any robust program, you are constantly working
to
> avoid the defaults. Which usually isn't that difficult in C++. The
> language is open, and allows an incredible amount of flexibility, not
> only to shoot yourself in the foot, but also to create firewalls, and
> defend yourself against coding errors.

true. i guess it's a kind of cultural question which of the two
ways one prefers. from my experience in a typical project you
don't have the same high standard of skills in every person and
an too open environment has more disadvantages.

> In Java, it is almost
> impossible: you can't implement programming by contract, and you can't
> avoid dynamic loading (and the problems of version management it
> entails), for example. You can't declare anything const.

but i think you have to admit, that there's a lot of discussion
around const here and in other places and using of const can be
really tricky. in java you have final and you have immutable
classes. these can be used to tackle a lot of the problems you
need const for.

> You have
> absolute dynamic typing everywhere: you can't (or you couldn't until
> recently) easily limit the types you put into a standard collection
> (except for an array). (One place where C++ actually has the correct
> default -- containers are normally typesafe, and when you need
variable
> types, you need to take extra programming steps to get them.)

in practice i had very little problems with this limitation.
often collections are used only inside some class and there you
can easily control their contents. otoh with collections beeing
interfaces and the base implementations java.util provides it's
easy to write some collection wrappers that ensure type safety.

i think the discussion points out that both sides have their
strengths and weaknesses and it heavily depends on the
preferrences and the situation you have which of the two is
better suited. not really new... :-)

regards

robert

Robert Klemme

unread,
Sep 11, 2002, 2:56:05 PM9/11/02
to

Thorsten Ottosen schrieb:


> > > Soon the lack advanced feautures in java
> > > (what you called "easier") becomes a bottleneck.
> >
> > in which cases? could you please give an example?
>
> of course. try writing a procedure that swaps the reference of two
objects
> or two integers for that sake, I would like to use
> your code then.

granted. is this needed often in java? i can't remember needing
such a method but maybe this is domain dependent.

> I often need to define foo( int ). A little later I need foo(Object)
and I
> have to replicate the code each time because the
> language lacks templates. And the I need to define foo(string)...

how about:

public void foo(int i) {
foo( new Integer( i ) );
}

public void foo(Object o) {
// code
}

or

public void foo( Number n ) {
// code
}

> In general I don't need to worry about memory, but I always have to
close
> somthing, If I don't I might get a memory
> leak in some obscure way (yes, memory leaks exist in java too, and the
> virtual machine could leak too!).

true. only that java prevents access of data that is freed
already which can produce hard to find errors.

> I have to
> close files, database, locks (in fact, every resource) manually, which
is
> tedious and leads to more errors.

otoh it's more explicit and not too difficult with "finally".

> The real problem is the implementation of the virtual machine. Since
you
> don't know exactly
> which virtual machine your program will run on, it is _really_ hard to
test
> for that platform. Basically, you
> need to test any potential vm on every os, right. Moreover, snall
> differences in the implementation
> of vms could produce really hard to find bugs. Eg., it is well known
that
> atomicity properties differ from vm to vm.

true, there are problems with the part of the language spec that
deals with multi threading. but from what i understand, if you
use properly synchronize then this is not an issue.

> > well, as i said: you have to rewrite the gui IF you cannot use a
> > cross platform library. i didn't say there are none. :-)
> But then it is hypothetical "have to" and as such irrelevant.

depends: since i'm not an expert at c++ gui libs - where they are
available, compatibility etc. - i put it in not to be forgotten.
i think this is legitimate.

regards

robert

Nicola Musatti

unread,
Sep 12, 2002, 2:02:44 PM9/12/02
to

Robert Klemme wrote:
[...]


> otoh this makes things clearer, because you immediately know what
> a method returns and don't have to scan the parameter list for
> out parameters...

However, this still doesn't prevent you from causing side-effects on
your arguments, while in C++ you can at least declare your parameters as
const.

> then, if you omit exception specifications and
> do not commment them in c++, the user has no other chance of
> knowing which exceptions there might occur without looking at the
> code.

Yet checked exceptions are a mixed blessing even in Java, the following
article explains why:

http://www.octopull.demon.co.uk/java/ExceptionalJava.html

> > The fact that you never know when a null pointer is
> > legitimate, and when it isn't, nor the function might modify your
> > variable, or when it might not, is also a minus for Java.
>
> well, you don't know in c++ either, do you? the only chance is
> to put a comment there - in java and in c++.

In C++ you can use the distinction between pointers and references to
specify and enforce the passing of valid objects.

Cheers,
Nicola Musatti

James Kanze

unread,
Sep 12, 2002, 2:14:52 PM9/12/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D7F01D9...@gmx.net>...
> James Kanze schrieb:

> > Robert Klemme <bob....@gmx.net> wrote in message
> > news:<3D7C5BED...@gmx.net>...

> > > > From a software engineering perspective, it is incredibly
> > > > difficult to write robust software in Java. C++ has an enormous
> > > > edge here

> > > why that?

> > I gave a few exemples in another response, but I think the real
> > answer lies in a criticism of C++ by David Chase, that I read some
> > years back. I think he hit the nail on the head with regards to
> > C++: it has all of the wrong defaults. Of the defaults he cited,
> > however, Java only changes two of them: garbage collection by
> > default, and array bounds checking on by default. Both of these
> > changes are improvements. But there remain the other problems AND
> > several issues that weren't issues when he wrote the article: Java
> > uses threads (almost) by default, and Java uses dynamic loading by
> > default.

> what method bindings? in c++ virtual is not default, which i regard
> as a problem, too.

Why. If your goal is to write robust software, non-virtual is
definitely the better default. (In my experience, both in Java and C++,
about 2/3 of all functions are non virtual.) In this case, C++ has the
better default, but it is so trivial to change (in both languages) that
it isn't really worth thinking about.

> in java it's only virtual.

Unless the function is declared final. Or unless it is private. In my
experience, in most classes, the only functions you want to make virtual
are private functions -- with regards to private functions, Java has the
right default, but you can't override it. Ideally, I'd like some
special category for functions that the derived class can override, so
that the person deriving my class doesn't have to look in the private
section. But its only purpose would be documentation. At present, I
generally have several private: declarations:

private: // To be overridden in the derived class...

private: // Except for X
friend class X ;

private: // Really...

But even then, the user has to look in "private: // Really", because
that is where I tell him that copy and assignment aren't allowed. (If I
think about it, I should probably declare a short private section with
the rest of the constructors, because this is where the information
belongs.)

> threads: you don't have to bother about them if you don't use them.

The problem is that you sometimes end up using them without really
wanting to. The second you use AWT, for example.

But generally, I would agree that it is more a problem with the culture
surrounding the language, rather than the language itself. It seems to
be taken for granted that every Java program should use threads. (This
may be partially due to the fact that Java isn't used very much outside
of the few domains where threads often are a good solution.)

> dynamic loading is a problem, agreed.

> > The result is that in any robust program, you are constantly working
> > to avoid the defaults. Which usually isn't that difficult in C++.
> > The language is open, and allows an incredible amount of
> > flexibility, not only to shoot yourself in the foot, but also to
> > create firewalls, and defend yourself against coding errors.

> true. i guess it's a kind of cultural question which of the two ways
> one prefers. from my experience in a typical project you don't have
> the same high standard of skills in every person and an too open
> environment has more disadvantages.

So close the environment. That is what coding guidelines and code
reviews are for.

IMHO, however, with good guidelines, correctly enforced, even below
average programmers can produce very good code. Require documentation
of design patterns used, for example, and insist that all of the design
patterns use a canonical format. Categorize classes, and make
requirements according to category:

value objects:
No non-const functions other than assignment. No virtual
functions. Assignment and copy supported.

entity objects:
Derived from interface. No public virtual functions in
interface. Naming convention for the private virtual functions
which implement the interface. Pre- and post-conditions
specified in the interface, and enforced in the public
functions. No copy and assignment (but eventually clone).

agents:
Pure interface, à la Java. Virtual destructor implemented
inline; all other functions virtual (and public).

...

You can do the same thing in Java. (It's amazing how much our code
improved in Java when we required all value objects to be immutable and
final.) Partially: try and find a way to implement the equivalent of
the entity objects, above, in Java. Especially since some entity
objects will implement several entity interfaces.

Note that neither language gives you much support for this at the
language level. Which is, I think, correct, because I don't think we
really know enough yet to fix it into the language level. (New
categories of class still need to be defined, for example.) But C++
gives you the flexibility to do it, when you want. And at least one
tool, Rational Rose, gives you the possibility of generating much of the
framework automatically. (What I call categories, they call
stereotypes.)

> > In Java, it is almost impossible: you can't implement programming by
> > contract, and you can't avoid dynamic loading (and the problems of
> > version management it entails), for example. You can't declare
> > anything const.

> but i think you have to admit, that there's a lot of discussion around
> const here and in other places and using of const can be really
> tricky. in java you have final and you have immutable classes. these
> can be used to tackle a lot of the problems you need const for.

Immutable classes are, of course, essential for value objects. And I
would agree that const has sometimes been oversold. But I do find it
nice that I can impose immutability at the function level, even when the
class itself isn't immutable: it's another post-condition, but a
post-condition that the compiler can verify.

> > You have absolute dynamic typing everywhere: you can't (or you
> > couldn't until recently) easily limit the types you put into a
> > standard collection (except for an array). (One place where C++
> > actually has the correct default -- containers are normally
> > typesafe, and when you need variable types, you need to take extra
> > programming steps to get them.)

> in practice i had very little problems with this limitation. often
> collections are used only inside some class and there you can easily
> control their contents. otoh with collections beeing interfaces and
> the base implementations java.util provides it's easy to write some
> collection wrappers that ensure type safety.

It's not too difficult, but it has to be done. Whereas IMHO, the type
safety should be the default. (There are times when you want the
flexibility. Although even then, most of the time, the best solution is
to regroup all of the acceptable types and have them derive from a base
class. When possible: one of the cases I encounter from time to time is
a recursive structure, where I have a collection which can contain X's,
or collections meeting the same conditions -- if I go into all of the
collections recursively, I always end up with all X's at the deepest
level. What I'd like, both in C++ and Java, is some way of defining a
type to be a collection (or a collection interface) in which all
elements are one of a set of types -- typically, the set will be X, or
the type I am currently defining.)

> i think the discussion points out that both sides have their strengths
> and weaknesses and it heavily depends on the preferrences and the
> situation you have which of the two is better suited. not really
> new... :-)

I think that the two languages were designed to meet different goals.
And I fear that writing robust software wasn't really a goal in either
case.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Alain Miniussi

unread,
Sep 12, 2002, 8:27:41 PM9/12/02
to
Robert Klemme wrote:
> James Kanze schrieb:
>>
>> Robert Klemme <bob....@gmx.net> wrote in message
>> news:<3D7C5DA1...@gmx.net>...
>> > advocatus diaboli (= java) speaking...
>> The fact that you never know when a null pointer is
>> legitimate, and when it isn't, nor the function might modify your
>> variable, or when it might not, is also a minus for Java.
>
> well, you don't know in c++ either, do you?

Dangling references are not legitimates in C++, you can use that when
null is not an option, there is no Java equivalent.
Const can be used to tell if your variable will be modified or not.

In both cases, of course, you can lie, but the tool is there.

>> In both languages, however, the real complexity in the interfaces
> comes
>> from poor design. In both languages, too, the standard libraries have
>> some blatent examples of this. (std::string, or java.awt.Dimension,
>> come to mind.)
>
> of course. it's just that i think that java makes life easier in
> some aspects and from a pragmatic point of view has real
> advantages.

The main adavantage that I can remember for Java was the uniformity
of development environment (eg: the language is not that great, but at
least it is implemented by most availables compiler). I don't know
how the situation as evolved.
I also remember a lot of inconvenients, most of them have already be
mentioned (except one maybe: the delay between failure and sanction
which is much longer in Java and allow production of large quantities
of poor code (because as long as "it doesn't crash", you can
concentrate on functionnalities :-).
Otoh, I have seen very persistent poor developpers in C++ too, but
it requires more efforts and so most of them swicth to managment sooner :-).

Regards,

Alain

James Kanze

unread,
Sep 12, 2002, 8:35:37 PM9/12/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D7F6134...@gmx.net>...

> Thorsten Ottosen schrieb:
> > > > Soon the lack advanced feautures in java
> > > > (what you called "easier") becomes a bottleneck.

> > > in which cases? could you please give an example?

> > of course. try writing a procedure that swaps the reference of two
> > objects or two integers for that sake, I would like to use your code
> > then.

> granted. is this needed often in java? i can't remember needing such
> a method but maybe this is domain dependent.

The need occurs occasionally not infrequently when implementing basic
algorithms like sort. In Java, you have to write the routine each time,
in line.

Given the frequency most programmers have to write such algorithms, I
don't consider it a real problem. A slight nuisance for a small
percentage of programmers, at the most.

> > I often need to define foo( int ). A little later I need foo(Object)
> > and I have to replicate the code each time because the language
> > lacks templates. And the I need to define foo(string)...

> how about:

> public void foo(int i) {
> foo( new Integer( i ) );
> }

> public void foo(Object o) {
> // code
> }

> or

> public void foo( Number n ) {
> // code
> }

I think the real issue isn't so much replicating code: deriving
everything from Object, as Java does, solves that very well. (It would
solve it better, of course, if the basic types weren't bastardized.)
The real problem is enforcing pre- and post-conditions and invariants
involving the type system. In a class like Stack, there is an obvious
condition in the use that the pop'er pops the same type as the push'er
pushes. Or expressed otherwise, that the push'er only pushes what the
pop'er wants. In C++, templates allow this to be a compile time check;
in Java, unless you rewrite the Stack class for every type, it is a
run-time check.

> > In general I don't need to worry about memory, but I always have to
> > close somthing, If I don't I might get a memory leak in some obscure
> > way (yes, memory leaks exist in java too, and the virtual machine
> > could leak too!).

> true. only that java prevents access of data that is freed already
> which can produce hard to find errors.

Memory management is also simpler with garbage collection. You still
have to deal with lifetime of object issues, and you can still access
objects which are logically dead, but garbage collection frees you from
a lot of the nitty gritty low level implementation details once your
design has addressed the high level issues.

> > I have to close files, database, locks (in fact, every resource)
> > manually, which is tedious and leads to more errors.

> otoh it's more explicit and not too difficult with "finally".

It's also not too difficult to forget a finally in a critical case:-).
Destructors and the RAII pattern are one of C++'s real strong points.

> > The real problem is the implementation of the virtual machine. Since
> > you don't know exactly which virtual machine your program will run
> > on, it is _really_ hard to test for that platform. Basically, you
> > need to test any potential vm on every os, right. Moreover, snall
> > differences in the implementation of vms could produce really hard
> > to find bugs. Eg., it is well known that atomicity properties differ
> > from vm to vm.

> true, there are problems with the part of the language spec that deals
> with multi threading. but from what i understand, if you use properly
> synchronize then this is not an issue.

I think the issue is a different one. As a matter of basic principle, I
don't ship software untested in the environment in which it is going to
run. With Java, in theory, I don't know the environment in which it is
actually going to run. Of course, with Java, in theory, the environment
is the JVM, which is exactly the same everywhere. In practice, both
theories are at least partially wrong. Efficient JVM's only exist for a
handful of machines, and my software won't run without an efficient
JVM, so I am really only concerned about a handful of environments
(basically Windows, the big five Unix, and maybe Mac). On the other
hand, it seems to be par for the course that software which works with
version i of the JVM doesn't work with version i + 1. So we're back
where we started from. I sometimes happens that software in C or C++
works with version i of the OS, but not with version i + 1. While this
was pretty frequent with early versions of Solaris and Linux, the
situation seems to be greatly improved now. (I've heard that this is
sometimes a problem with Windows, but don't have enough experience with
the platform to comment.)

> > > well, as i said: you have to rewrite the gui IF you cannot use a
> > > cross platform library. i didn't say there are none. :-)
> > But then it is hypothetical "have to" and as such irrelevant.

> depends: since i'm not an expert at c++ gui libs - where they are
> available, compatibility etc. - i put it in not to be forgotten. i
> think this is legitimate.

They're available, and some of them are really quite good. The only
real problem is that they aren't standard. When I did my first GUI with
Java, I used Swing. When I do the next, I will also use Swing, and will
be effective from the first day. The last GUI project in C++ I worked
on used ILog Views. If the next one uses something else, I have to pay
a second learning curve.

In practice, the "standard" GUI for C++, at least outside of the Windows
world, seems to be Swing with CORBA:-).

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Thorsten Ottosen

unread,
Sep 12, 2002, 8:37:54 PM9/12/02
to

"Robert Klemme" <bob....@gmx.net> wrote in message
news:3D7F6134...@gmx.net...

>
>
> Thorsten Ottosen schrieb:
> > > > Soon the lack advanced feautures in java
> > > > (what you called "easier") becomes a bottleneck.
> > >
> > > in which cases? could you please give an example?
> >
> > of course. try writing a procedure that swaps the reference of two
> objects
> > or two integers for that sake, I would like to use
> > your code then.
>
> granted. is this needed often in java? i can't remember needing
> such a method but maybe this is domain dependent.
It would be a great help when one is trying to write exception safe code in
Java.


> > I often need to define foo( int ). A little later I need foo(Object)
> and I
> > have to replicate the code each time because the
> > language lacks templates. And the I need to define foo(string)...
>
> how about:
>
> public void foo(int i) {
> foo( new Integer( i ) );
> }
>
> public void foo(Object o) {
> // code
> }
>
> or
>
> public void foo( Number n ) {
> // code
> }

Such code is not type safe and it will be a pain in the a*** to let
foo(Object) do type inqueries should it handle a wide variaty of types.
It simply doesn't solve the problem. You have to wait for true generics.

>
> > In general I don't need to worry about memory, but I always have to
> close
> > somthing, If I don't I might get a memory
> > leak in some obscure way (yes, memory leaks exist in java too, and the
> > virtual machine could leak too!).
>
> true. only that java prevents access of data that is freed
> already which can produce hard to find errors.

Not really. A proper tool like Rational Purify is pretty good at finding
leaks.

> > I have to
> > close files, database, locks (in fact, every resource) manually, which
> is
> > tedious and leads to more errors.
>
> otoh it's more explicit and not too difficult with "finally".

No, its not difficult. It just makes the program a lot larger
and a lot less maintainable.

regards

--Thorsten

James Kanze

unread,
Sep 12, 2002, 8:31:09 PM9/12/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D7EFF0A...@gmx.net>...
> James Kanze schrieb:
[...]

> > > > Lee's put is this way: C++ allows library writers to create
> > > > faster/safer/smaller libraries whereas the interface should be
> > > > no more complicated than in a java version.

> > > i doubt it. if you take the several different ways of argument
> > > passing in c++ vs. only one (plus one for basic types) - this
> > > makes interfaces more complex and more difficult to use.

> > I don't think so. The lack of out parameters, for example, requires
> > additional types, etc., in Java, which can render the interface more
> > complicated.

> otoh this makes things clearer, because you immediately know what a
> method returns and don't have to scan the parameter list for out
> parameters...

If you only need one out parameter (the return value), fine. If you
need more than one, what do you do? In C++, you declare an out
parameter (a non-const reference). In Java, you have to either pass an
array of one element, or define a new class, just in order to return
several values.

The number of out parameters needed should be clear from the semantics
of the function. And if you don't know the semantics of the function
enough to know how many values it returns, you really shouldn't be using
it. You do have to scan the list in order to know *which* parameter is
which, but this is no more of a problem than making sure that all of
your in parameters are in the correct order.

Note that depending on the semantics, Java does use out parameters,
since arrays and collections can be used to return values. In C++, it
is clear when this is the case, since the type is a non-const reference,
rather than a const reference.

> then, if you omit exception specifications and do not commment them in
> c++, the user has no other chance of knowing which exceptions there
> might occur without looking at the code.

This is a real problem with both languages. Generally, the really
important information is whether an exception can be raised or not. And
neither language offers a guarateed way of expressing this. The
"throw()" is not required (and is generally not used) in C++, and there
is simply no way in Java to say that a function won't throw an
exception. (Of course, since most objects are on the heap in Java,
functions which cannot throw an OutOfMemory exception are really
exceptional.)

Interestingly enough, the information is far more important in Java.
The typical C++ idiom is to put all of the clean-up code in the
destructor of a local object; it gets called whether there was an
exception or not. In Java, IF there is any possibility of an exception,
you need a finally block for the clean up code. Garbage collection
means that you need considerably less clean up code, but there are other
resources to be considered, and there are often issues of program
consistency which have to be addressed when a function is terminated in
the middle.

> > The fact that you never know when a null pointer is legitimate, and
> > when it isn't, nor the function might modify your variable, or when
> > it might not, is also a minus for Java.

> well, you don't know in c++ either, do you?

In C++, if my function takes a pointer as a parameter, it may be null.
It is as simple as that. Actually, there are exceptions for historical
reasons, and a char const* often may not be null. In this case, you are
back to the Java case. But for just about everything else, you use a
pointer if null is a legitimate possibility, and a reference otherwise.

> the only chance is to put a comment there - in java and in c++. with
> the slight advantage of java having a std mechanism (javadoc) to
> comment things whereas there is a lot of tools that do so for c++. of
> course some of these tools can do far more than javadoc can. but a
> standard solution to commenting makes life easier.

It would be even better if it were more flexible:-).

Seriously, I agree that it is better than nothing. But here again, Java
needs something, because it requires you to mix the external definition
and the implemention (a disaster in large projects, where different
people are typically responsible for the two aspects). In C++, my
header files *ARE* the class documentation; I don't need a special tool
to extract the information because it isn't buried in a mass of
irrelevant code.

How well this works depends on local conventions, of course, and I'll
admit even my own code could be better. I have seen places where the
C++ class definition (for a function in an entity object) looks
something like:

int
digitValue( char param )
{
Require( isdigit( param ) ) ;
int result = doDigitValue( param ) ;
Ensure( result >= 0 || result < 10 ) ;
}

The preconditions (Require) and postconditions and invariants (Ensure)
are actually part of the C++ code.

This is one of the most powerful tools I've found for writing robust
software, and it simply can't be done in Java.

> > In both languages, however, the real complexity in the interfaces
> > comes from poor design. In both languages, too, the standard
> > libraries have some blatent examples of this. (std::string, or
> > java.awt.Dimension, come to mind.)

> of course. it's just that i think that java makes life easier in some
> aspects and from a pragmatic point of view has real advantages.

Well, the compile and build cycle is somewhat simpler, but that's about
it. There are a few nice points: garbage collection, bounds checking by
default, and very little undefined behavior, but on the whole, I've
found that it inhibits good programming practices more than it
encourages them.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 12, 2002, 8:39:48 PM9/12/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D7DF6B3...@gmx.net>...

> James Kanze schrieb:
> > > Could you elaborate on this? How do you define "software
> > > engineering perspective" and "robust"? Could you give some
> > > examples?

> > Very simple. For Java, the definition of "robust" means that it
> > doesn't crash. And it is, in fact, very difficult to get a Java
> > program to crash, whereas with C++...

> > IMHO, however, just not crashing isn't sufficient. I also want the
> > correct results. To ensure that I get the correct results, it is
> > important to be able to instrument the code. There are many ways of
> > doing this, but one the most important is to ensure pre- and
> > post-conditions. Some languages (Eiffel) provide this as part of
> > the language. In C++, the idiom has developped in which the public
> > interface uses no virtual functions, but rather forwards to private
> > (or protected) virtual functions, wrapping the virtual function call
> > with instrumentation. Java's interfaces don't allow this.

> hm, maybe i did not exactly grasp what you mean by this. what's the
> difference to having public methods in java, that do the condition
> checking and forwarding the call to another private or protected
> method? you can even go as far as to declare the public method final
> which whould ensure, that no sub class will supersede this.

That's what we did in my last Java project (including declaring the
public method final). It works for simple cases. But as you say...

> or is your major point, that i cannot incorporate these checks into an
> interface? then you could simply use abstract classes for this.

You can only do it with abstract classes, not interfaces. Which means
that you cannot do it if the final objects are to implement more than
one interface (often the case).

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

JKB

unread,
Sep 12, 2002, 8:52:37 PM9/12/02
to

"James Kanze" <ka...@gabi-soft.de> wrote

> I generally have several private: declarations:
>
> private: // To be overridden in the derived class...
>
> private: // Except for X
> friend class X ;
>
> private: // Really...

I've also taken to having one for telling the compiler not to generate code:

private: // and unimplemented
myclass(); // no default ctor
myclass& operator= (const myclass&); // no assignment op


> > Robert Klemme <bob....@gmx.net> wrote


> there's a lot of discussion around const here and in other
> places and using of const can be really tricky.

But mostly because C++ presents const in a confusing way, with odd syntax.
If you just say "const is a promise not to use this name to modify things",
you have const pretty well covered. One needs to understand that it's a
promise made by code, not an attribute of the object. Also that it applies
to a declaration, not the object which that name refers to. That's const.

-- jkb

Alan Griffiths

unread,
Sep 13, 2002, 7:29:29 AM9/13/02
to
Nicola Musatti <Nicola....@objectway.it> wrote in message news:

>
> Yet checked exceptions are a mixed blessing even in Java, the following
> article explains why:
>
> http://www.octopull.demon.co.uk/java/ExceptionalJava.html

I'd currently express that differently: checked and unchecked
exceptions are different error reporting mechanisms and address
different design concerns.

The problems arise from developers that don't distinguish these
concerns and use the wrong mechanism. (And pedagogues that encourage
this confusion.)

This may be expressed better in:

http://www.octopull.demon.co.uk/sw-dev/IfProblemsArise.html
--
Alan Griffiths al...@octopull.demon.co.uk ACCU Chairman ch...@accu.org
http://www.octopull.demon.co.uk/ http://accu.org/

Shannon Barber

unread,
Sep 13, 2002, 1:31:55 PM9/13/02
to
mike_...@hotmail.com (Mike Rupke) wrote in message news:<b0ddddf5.02090...@posting.google.com>...
> I seek the collective wisdom of the programming specialists in this
> newsgroup.
>
> A client recently expressed interest in my company building a
> cross-platform commercial application. The platforms/OS include
> Unix/Linux, Windows, and Mac. Linux support includes the small
> PDA-like and TabletPC-like Linux devices now under development.
You need technical information about those "PDA-like" devices - and if
they are under developement, accurate information may be hard to come
by.
If performance and high-portability (PDA's?!) are important
architectural goals, then C++ may not even be a good choice - C is
arguably a superior choice since you require portibility to embedded
systems. Are these linux based PDA's the only ones you need to
support?
i.e. If it needs to run on a Palm, then C looks even better. Has gcc
been ported to those linux PDA's, do they even have a JVM written for
them?

If every system has a decent C++ compiler, then you can use C++. If
every system has a decent JVM available, then you can use Java. Right
now, it's not clear C++ or Java is actually a viable choice.

It is important to note
> that our company comprises several XML experts in the areas of
> interest to the client, the main reason they approached us, but we
> have no one on staff at this time with any commercial software
> development experience.
I fail to concieve of an XML expert that has not actually written
commerical code that uses it. How can this be?

I must concur with earlier estimations - how can you start work on
what sounds like a large scoped project without having any technical
expertise with any of the systems? This is a disaster in the making;
you may be better off finicially by dropping the contract now because
it is probable that this is a money sink. Odds are very good that you
will greatly under-estimate the complexity of the task at hand, will
underbid everyone else, will get the contract, and will lose your ass
on it or default.


The important Business Concern when choosing between C++ and Java, is
what your expert developers are most familar with, and whether C++
and/or
Java are supported on your target platforms. You have no expert
developers, and are not certain that they are both supported.

Forget about whether you're going to use C++, Java, .Net, dHTML,
etc... You have much more important problems to deal with (hiring
people who can actually architecture, design, and build this project).
Let them decide upon the technical merits of what tool(s) to use
where.

Robert Klemme

unread,
Sep 13, 2002, 1:44:30 PM9/13/02
to

Nicola Musatti schrieb:


>
> Robert Klemme wrote:
> [...]
> > otoh this makes things clearer, because you immediately know what
> > a method returns and don't have to scan the parameter list for
> > out parameters...
>
> However, this still doesn't prevent you from causing side-effects on
> your arguments, while in C++ you can at least declare your parameters as
> const.

true.

> > then, if you omit exception specifications and
> > do not commment them in c++, the user has no other chance of
> > knowing which exceptions there might occur without looking at the
> > code.
>
> Yet checked exceptions are a mixed blessing even in Java, the following
> article explains why:
>
> http://www.octopull.demon.co.uk/java/ExceptionalJava.html

thanks for that link.

> > > The fact that you never know when a null pointer is
> > > legitimate, and when it isn't, nor the function might modify your
> > > variable, or when it might not, is also a minus for Java.
> >
> > well, you don't know in c++ either, do you? the only chance is
> > to put a comment there - in java and in c++.
>
> In C++ you can use the distinction between pointers and references to
> specify and enforce the passing of valid objects.

i think, now i got your point (james mentioned this as well).

thanks!

robert

Robert Klemme

unread,
Sep 13, 2002, 1:44:52 PM9/13/02
to

JKB schrieb:


> > > Robert Klemme <bob....@gmx.net> wrote
> > there's a lot of discussion around const here and in other
> > places and using of const can be really tricky.
>
> But mostly because C++ presents const in a confusing way, with odd syntax.
> If you just say "const is a promise not to use this name to modify things",
> you have const pretty well covered. One needs to understand that it's a
> promise made by code, not an attribute of the object. Also that it applies
> to a declaration, not the object which that name refers to. That's const.

i was targeting more for the "philosophical" level: what is
really const? is an instance that does lazy initialization const
or not? the fact that the keyword "mutable" was introduced
points exactly to this issue. there might be times when you want
true constness (i.e. no change in physical instance state) or
logical constness (the observable logical state does not change,
but runtime performance and similar might). lazy init has the
other problem, that if the initialization can throw exceptions
you defer them to the accessor method, which might not be what
you wanted etc.

regards

robert

Robert Klemme

unread,
Sep 13, 2002, 5:43:23 PM9/13/02
to

James Kanze schrieb:


> > or is your major point, that i cannot incorporate these checks into
an
> > interface? then you could simply use abstract classes for this.
>
> You can only do it with abstract classes, not interfaces. Which means
> that you cannot do it if the final objects are to implement more than
> one interface (often the case).

yes. this must have to do with this multiple inheritance thingy,
which one hears so much about recently. :-)) it's true, mixin
and all the nice things that can be done with multiple
inheritance aren't possible in java as simple and elegant as in
c++.

regards

robert

Robert Klemme

unread,
Sep 13, 2002, 5:43:51 PM9/13/02
to

James Kanze schrieb:


> I think the real issue isn't so much replicating code: deriving
> everything from Object, as Java does, solves that very well. (It
would
> solve it better, of course, if the basic types weren't bastardized.)

how very true!

> The real problem is enforcing pre- and post-conditions and invariants
> involving the type system. In a class like Stack, there is an obvious
> condition in the use that the pop'er pops the same type as the push'er
> pushes. Or expressed otherwise, that the push'er only pushes what the
> pop'er wants. In C++, templates allow this to be a compile time
check;
> in Java, unless you rewrite the Stack class for every type, it is a
> run-time check.

that's true. as i pointed out elsewhere this is not a real issue
in practice - at least not from my experience.

> > otoh it's more explicit and not too difficult with "finally".
>
> It's also not too difficult to forget a finally in a critical case:-).
> Destructors and the RAII pattern are one of C++'s real strong points.

yes.

> I think the issue is a different one. As a matter of basic principle,
I
> don't ship software untested in the environment in which it is going
to
> run. With Java, in theory, I don't know the environment in which it
is

> actually going to run. [deleted]

yes, it's true that "write once, run everywhere" is a myth.
still i prefer the java approach to multiple platforms over the
c++ approach. both have their pros and cons but in my personal
judgement java wins.

> > depends: since i'm not an expert at c++ gui libs - where they are
> > available, compatibility etc. - i put it in not to be forgotten. i
> > think this is legitimate.
>
> They're available, and some of them are really quite good. The only
> real problem is that they aren't standard. When I did my first GUI
with
> Java, I used Swing. When I do the next, I will also use Swing, and
will
> be effective from the first day. The last GUI project in C++ I worked
> on used ILog Views. If the next one uses something else, I have to
pay
> a second learning curve.

true. but thanks to ibm java is steering to a similar situation,
too: now we have awt, swing and swt.

regards

robert

Robert Klemme

unread,
Sep 13, 2002, 5:44:15 PM9/13/02
to

Thorsten Ottosen schrieb:
> > > > > Soon the lack advanced feautures in java
> > > > > (what you called "easier") becomes a bottleneck.
> > > >
> > > > in which cases? could you please give an example?
> > >
> > > of course. try writing a procedure that swaps the reference of two
> > objects
> > > or two integers for that sake, I would like to use
> > > your code then.
> >
> > granted. is this needed often in java? i can't remember needing
> > such a method but maybe this is domain dependent.
> It would be a great help when one is trying to write exception safe
code in
> Java.

err, what has swapping of references to do with exception safe
code? did i miss something?

> Such code is not type safe and it will be a pain in the a*** to let
> foo(Object) do type inqueries should it handle a wide variaty of
types.
> It simply doesn't solve the problem. You have to wait for true
generics.

well, if the types have a lot in common they should typically
implement the same interface. alas, you substitute Object with
this interface and you're done. you don't always need generics,
although i would grant that you can't do certain things without
them. (james pointed this out.)

> > true. only that java prevents access of data that is freed
> > already which can produce hard to find errors.
> Not really. A proper tool like Rational Purify is pretty good at
finding
> leaks.

at least you need that extra tool...

> > otoh it's more explicit and not too difficult with "finally".
>
> No, its not difficult. It just makes the program a lot larger
> and a lot less maintainable.

well, we could argue about "a lot". i don't think it's a lot but
this certainly depends on the situation.

robert

James Kanze

unread,
Sep 13, 2002, 5:48:06 PM9/13/02
to
"Thorsten Ottosen" <nes...@cs.auc.dk> wrote in message
news:<alqktu$1j$1...@sunsite.dk>...

> "Robert Klemme" <bob....@gmx.net> wrote in message
> news:3D7F6134...@gmx.net...

> > Thorsten Ottosen schrieb:
> > > > > Soon the lack advanced feautures in java (what you called
> > > > > "easier") becomes a bottleneck.

> > > > in which cases? could you please give an example?

> > > of course. try writing a procedure that swaps the reference of two
> > > objects or two integers for that sake, I would like to use your
> > > code then.

> > granted. is this needed often in java? i can't remember needing
> > such a method but maybe this is domain dependent.

> It would be a great help when one is trying to write exception safe
> code in Java.

In what way?

In C++, we often use swap as a technique in implementing operator=. The
technique depends on C++ destructors, however (which Java doesn't have),
and is only relevant in the implementation of assignment operators
(which Java doesn't have).

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Shannon Barber

unread,
Sep 13, 2002, 5:49:21 PM9/13/02
to
ka...@gabi-soft.de (James Kanze) wrote in message
news:<d6651fb6.02091...@posting.google.com>...

I concur, but also take exception to the draconian garbage collector.
It is a liability to soft RT systems, which otherwise could operate on
desktop OSes without issue. Consider the effects of a collection on a
3D computer game, audio/video streaming, or a live mpeg(2) capture
application (a digital VCR sort of thing). While many applications
may benefit from GC, some applications are hampered by it.

Cannot array bounds can be verified offline, at compile time or by a
static analyze tool? I think it's largely a waste of resources to do
so at run-time. I do not mean that buffers should not be checked
(e.g. sprintf(buf, "%s", some_string) is a recipe for security holes
:)), but that they should not be checked during random access /by
default/. It may be reasonable to check some arrays upon every
access, but not all of them. At the very least, you would want to be
able to turn it off/ choose between two implementations.
For example, assuming a non-pathologically behaved do_something
function, "do_something(vector.begin(), vector.end())" will never
violate its bounds (assuming vector has no bugs, which it shouldn't by
now ;).

Nicola Musatti

unread,
Sep 13, 2002, 5:50:29 PM9/13/02
to

Alan Griffiths wrote:
>
> Nicola Musatti <Nicola....@objectway.it> wrote in message news:
> >
> > Yet checked exceptions are a mixed blessing even in Java, the
following
> > article explains why:
> >
> > http://www.octopull.demon.co.uk/java/ExceptionalJava.html
>
> I'd currently express that differently: checked and unchecked
> exceptions are different error reporting mechanisms and address
> different design concerns.
>
> The problems arise from developers that don't distinguish these
> concerns and use the wrong mechanism. (And pedagogues that encourage
> this confusion.)

I accept your point of view, but I'd put it a bit stronger: the
distinction between checked and unchecked exceptions in Java was
misdesigned. Now Java developers feel lucky that the language designers
had to leave unchecked exceptions in, even though you get the feeling
that they would have preferred otherwise.

Let this be a warning for those who wish to find the ultimate fix for
C++'s exception specifications: "exception transparent" functions are
important!

Cheers,
Nicola Musatti

Thorsten Ottosen

unread,
Sep 15, 2002, 9:14:27 AM9/15/02
to

"Robert Klemme" <bob....@gmx.net> wrote in message
news:3D81B083...@gmx.net...

>
>
> Thorsten Ottosen schrieb:
> > > > > > Soon the lack advanced feautures in java
> > > > > > (what you called "easier") becomes a bottleneck.
> > > > >
> > > > > in which cases? could you please give an example?
> > > >
> > > > of course. try writing a procedure that swaps the reference of two
> > > objects
> > > > or two integers for that sake, I would like to use
> > > > your code then.
> > >
> > > granted. is this needed often in java? i can't remember needing
> > > such a method but maybe this is domain dependent.
> > It would be a great help when one is trying to write exception safe
> code in
> > Java.
>
> err, what has swapping of references to do with exception safe
> code? did i miss something?

[also answer to JK]
Ok, sorry for the unclear msg. It's merely an opservation I made when I read
the last issue of Overload
and Jon Jagger's article "Even more Java exceptions". You'll find his code
full of swapping. What is worse,
one cannot reuse the mechanism presented in the article.

> > > true. only that java prevents access of data that is freed
> > > already which can produce hard to find errors.
> > Not really. A proper tool like Rational Purify is pretty good at
> finding
> > leaks.
>
> at least you need that extra tool...

Interestingly, you also need that for Java. In the latest issue of CV^u,
Roger Orr decribes his problems with detecting a memory
leak in Java.

regards

Thorsten

James Kanze

unread,
Sep 17, 2002, 6:12:07 AM9/17/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D81B43D...@gmx.net>...

> James Kanze schrieb:
> > > or is your major point, that i cannot incorporate these checks
> > > into an interface? then you could simply use abstract classes for
> > > this.

> > You can only do it with abstract classes, not interfaces. Which
> > means that you cannot do it if the final objects are to implement
> > more than one interface (often the case).

> yes. this must have to do with this multiple inheritance thingy,
> which one hears so much about recently. :-)) it's true, mixin and all
> the nice things that can be done with multiple inheritance aren't
> possible in java as simple and elegant as in c++.

If it were only a question of mixins. Mixins are occasionally useful,
but they aren't fundamental, and I can live without them. However, in
C++ as in Java, it is rather frequent for a class to implement several
interfaces. In C++, I can instrument those interfaces. In Java, I
can't.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Alan Griffiths

unread,
Sep 17, 2002, 7:07:01 AM9/17/02
to
Nicola Musatti <Nicola....@objectway.it> wrote in message news:<3D81FDAF...@ObjectWay.it>...

> Alan Griffiths wrote:
> >
> > I'd currently express that differently: checked and unchecked
> > exceptions are different error reporting mechanisms and address
> > different design concerns.
> >
> > The problems arise from developers that don't distinguish these
> > concerns and use the wrong mechanism. (And pedagogues that encourage
> > this confusion.)
>
> I accept your point of view, but I'd put it a bit stronger: the
> distinction between checked and unchecked exceptions in Java was
> misdesigned.

Don't get smug exception specs in C++ were misdesigned too. The only
good thing about the design is that you don't have to use them.

> Now Java developers feel lucky that the language designers
> had to leave unchecked exceptions in, even though you get the feeling
> that they would have preferred otherwise.

Java developers generally don't feel lucky about this:
http://www.mindview.net/Etc/Discussions/CheckedExceptions
http://www.mindview.net/Etc/Discussions/UnCheckedExceptionComments

> Let this be a warning for those who wish to find the ultimate fix for
> C++'s exception specifications: "exception transparent" functions are
> important!

Why is that a warning? It is simply a requirement that any "ultimate
fix" must address.

Personally, I'd like to see an additional error reporting mechanism in
C++ that can be used to ensure at compile time that errors are
handled. Some elements of the current exception handling design could
be reused to support this but I don't think that exception
specifications should be hijacked for the purpose. (Nor, for
non-technical reasons, do I expect it to happen.)

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 17, 2002, 7:18:19 AM9/17/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D81D704...@gmx.net>...

> JKB schrieb:
> > > > Robert Klemme <bob....@gmx.net> wrote
> > > there's a lot of discussion around const here and in other places
> > > and using of const can be really tricky.

> > But mostly because C++ presents const in a confusing way, with odd
> > syntax. If you just say "const is a promise not to use this name to
> > modify things", you have const pretty well covered. One needs to
> > understand that it's a promise made by code, not an attribute of the
> > object. Also that it applies to a declaration, not the object which
> > that name refers to. That's const.

> i was targeting more for the "philosophical" level: what is really
> const?

Whatever the programmer (or the designer) wants it to mean.

What does it mean in Java if I say (in the documentation) that a class
is ummutable? It's a design issue. The only difference is that code
which violates the design will trigger compile time errors in C++, where
as it will result in subtly wrong results in most other langages. Of
course, the way the language works by default encourages a certain
semantics of the design attribute, but it doesn't enforce it, and you
can certainly misuse const. But globally, it is an additional check
which is available if I want to use it. It's useful, although its
absence certainly isn't a killer criterion.

> is an instance that does lazy initialization const or not?

Has the "value" conceptually changed?

> The fact that the keyword "mutable" was introduced points exactly to
> this issue.

This was an issue when I started C++. We were still learning to use the
language, and there were great debates between bitwise const and logical
("Humpty-Dumpty") const. As often happens, experience has shown that
logical const is the answer, and it has been years since I've seen an
experienced C++ programmer suggest anything else.

> there might be times when you want true constness (i.e. no change in
> physical instance state) or logical constness (the observable logical
> state does not change, but runtime performance and similar might).

See above.

> Lazy init has the other problem, that if the initialization can throw


> exceptions you defer them to the accessor method, which might not be
> what you wanted etc.

Lazy initialization has this problem. In C++, in Java, and I feel
almost certain, in any other language. At some point, you "initialize",
and you are prepared for the error. Having initialized, you suppose
that everything is OK, and continue. When the error occurs, you are not
prepared to handle it.

The classical example is the lazy commit of some mallocs (or rather, of
the underlying OS requests). In case of error, malloc should return a
null pointer (or operator new throw a bad_alloc exception). Once the
call to malloc (or operator new) has passed, the system has no means
other than terminated the (or a) process in case of error.

Lazy initialization is acceptable if the initialization cannot fail,
from a conceptual point of view. For example, I've seen a lot of
programs written as though they conceptually always had enough memory.
Perfectly valid, if they arrange for some sort of fatal error if the
assumption fails.

The same as you would want a fatal error in case of arithmetic overflow:
you have generally written the program under the assumption that type
int is an integer. Good programmers are aware of the problem, and
validate input so that overflow cannot occur. Bad programmers give
wrong results. In this case, C++ is theoretically superior, since it
allows an implementation to generate a fatal error here (whereas Java
doesn't). The advantage is purely theoretical, of course, because in
fact, Java just standardized what all C++ implementations do.

--
James Kanze mailto:jka...@caicheuvreux.com

Conseils en informatique oriente objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Nicola Musatti

unread,
Sep 17, 2002, 5:04:39 PM9/17/02
to

Alan Griffiths wrote:
[...]


> > I accept your point of view, but I'd put it a bit stronger: the
> > distinction between checked and unchecked exceptions in Java was
> > misdesigned.
>
> Don't get smug exception specs in C++ were misdesigned too. The only
> good thing about the design is that you don't have to use them.

Oh, certainly. C++ developers should feel lucky that C++ exception
specifications were more misdesigned than Java ones! :-)

> > Now Java developers feel lucky that the language designers
> > had to leave unchecked exceptions in, even though you get the
feeling
> > that they would have preferred otherwise.
>
> Java developers generally don't feel lucky about this:
> http://www.mindview.net/Etc/Discussions/CheckedExceptions
> http://www.mindview.net/Etc/Discussions/UnCheckedExceptionComments

What do you mean? That unchecked exceptions should not be part of Java?
(I know this is not your point of view, but I'm not sure where the
misunderstanding is)

> > Let this be a warning for those who wish to find the ultimate fix
for
> > C++'s exception specifications: "exception transparent" functions
are
> > important!
>
> Why is that a warning? It is simply a requirement that any "ultimate
> fix" must address.

It is a warning in that devising that ultimate fix is very hard and just
making C++ exception specifications compile time checked would actually
cause worse problems than it solved.

> Personally, I'd like to see an additional error reporting mechanism in
> C++ that can be used to ensure at compile time that errors are
> handled. Some elements of the current exception handling design could
> be reused to support this but I don't think that exception
> specifications should be hijacked for the purpose. (Nor, for
> non-technical reasons, do I expect it to happen.)

Wouldn't design by contract be a more promising approach for this kind
of thing?

Cheers,
Nicola Musatti

Alexander Terekhov

unread,
Sep 17, 2002, 5:06:33 PM9/17/02
to

James Kanze wrote:
[...]

> The same as you would want a fatal error in case of arithmetic
overflow:
> you have generally written the program under the assumption that type
> int is an integer. Good programmers are aware of the problem, and
> validate input so that overflow cannot occur. Bad programmers give
> wrong results. In this case, C++ is theoretically superior, since it
> allows an implementation to generate a fatal error here (whereas Java
> doesn't). The advantage is purely theoretical, of course, because in
> fact, Java just standardized what all C++ implementations do.
^^^^^^^^^^^^^^^^^^^^^^^^^^

Unless you happen to have C++ implementation built ON TOP of
some *reasonable* POSIX {threaded} >>C<< implementation (with
C/SEH exceptions ;-) ... for some oveflows as well) along the
lines of:

http://www.tru64unix.compaq.com/docs/base_doc/DOCUMENTATION/V51_HTML/ARH
9RBTE/DOCU0011.HTM#excep_defs
(5.10 Exceptions Defined by the POSIX Threads Library)

"....
Exception object names that begin with the prefix pthread_
are raised within the runtime environment itself and are not
meant to be raised by your program code. Names of exception
objects that begin with pthread_exc_ are generic and belong
to the exceptions package or represent exceptions raised by
the underlying system.

Table 5-1 Names of Exception Objects Defined by the Threads
Library

pthread_cancel_e Thread cancelation in progress

pthread_exc_aritherr_e Unhandled floating-point exception signal
("arithmetic error")

pthread_exc_decovf_e Unhandled decimal overflow exception

pthread_exc_excpu_e "cpu-time limit exceeded"

pthread_exc_exfilsiz_e "File size limit exceeded"

pthread_exc_exquota_e Operation failed due to insufficient quota

pthread_exc_fltdiv_e Unhandled floating-point/decimal divide by
zero exception

pthread_exc_fltovf_e Unhandled floating-point overflow exception

pthread_exc_fltund_e Unhandled floating-point underflow exception

pthread_exc_illaddr_e Data or object could not be referenced

pthread_exc_illinstr_e Unhandled illegal instruction signal
("illegal instruction")

pthread_exc_insfmem_e Insufficient virtual memory for requested
operation

pthread_exc_intdiv_e Unhandled integer divide by zero exception

pthread_exc_intovf_e Unhandled integer overflow exception

pthread_exc_noexcmem_e Out of memory while processing an exception

pthread_exc_nopriv_e Insufficient privilege for requested
operation

pthread_exc_privinst_e Unhandled privileged instruction fault
exception

pthread_exc_resaddr_e Unhandled reserved addressing fault
exception

pthread_exc_resoper_e Unhandled reserved operand fault
exception

pthread_exc_SIGABRT_e Unhandled signal ABORT

pthread_exc_SIGBUS_e Unhandled bus error signal

pthread_exc_SIGEMT_e Unhandled EMT signal

pthread_exc_SIGFPE_e Unhandled floating-point exception signal

pthread_exc_SIGILL_e Unhandled illegal instruction signal

pthread_exc_SIGIOT_e Unhandled IOT signal

pthread_exc_SIGPIPE_e Unhandled broken pipe signal

pthread_exc_SIGSEGV_e Unhandled segmentation violation signal

pthread_exc_SIGSYS_e Unhandled bad system call signal

pthread_exc_SIGTRAP_e Unhandled trace or breakpoint trap
signal

pthread_exc_subrng_e Unhandled subscript out of range
exception

pthread_exc_uninitexc_e Uninitialized exception raised

pthread_exit_e Thread exiting using pthread_exit()

pthread_stackovf_e Attempted stack overflow was detected

...."

spe206.testdrive.compaq.com> cc -c -fptm u -pthread -o intovf_c.o
intovf.c
spe206.testdrive.compaq.com> cxx -pthread -o intovf intovf.cpp
intovf_c.o
spe206.testdrive.compaq.com> ./intovf

Go...

INT_MAX: 2147483647
++i: -2147483648
i = ++d:

Hi There! Unhandled integer overflow, I guess.

Exception: Integer overflow (dce / thd)

Indeed. ;-) Ha! >>C++ RAISE<<

C++ throw...
C++ catch: pthread_exc_intovf_e

Finished!

spe206.testdrive.compaq.com> cat intovf.c

#include <stdio.h>
#include <limits.h>
#include <pthread_exception.h>

extern void throw_overflow();

static double d = INT_MAX;
static int i = INT_MAX;

void operation()
{
printf( "INT_MAX: " );
printf( "%11d\n", i );
printf( " ++i: " );
printf( "%11d\n", ++i );
printf( "i = ++d: " );
printf( "%11d\n", i = ++d );
}

void go()
{
TRY {
printf( "\nGo...\n\n" );
operation();
}
CATCH_ALL {
printf( "\n\nHi There! Unhandled integer overflow, I guess.\n\n" );
pthread_exc_report_np( THIS_CATCH );
TRY {
RERAISE;
}
CATCH( pthread_exc_intovf_e ) {
printf( "\nIndeed. ;-) Ha! >>C++ RAISE<<\n\n" );
throw_overflow();
}
ENDTRY
}
ENDTRY
}

spe206.testdrive.compaq.com> cat intovf.cpp

#include <iostream>
using namespace std;

extern "C" void throw_overflow()
{
cout << "C++ throw...\n";
throw "pthread_exc_intovf_e";
}

extern "C" void go();

int main()
{
try {
go();
}
catch(const char* e) {
cout << "C++ catch: " << e << "\n";
}
cout << "\nFinished!\n\n";
}

spe206.testdrive.compaq.com>

regards,
alexander.

Alan Griffiths

unread,
Sep 18, 2002, 6:49:58 PM9/18/02
to
Nicola Musatti <Nicola....@ObjectWay.it> wrote in message
news:<3D87267E...@ObjectWay.it>...
> Alan Griffiths wrote:
> [...]

> > > Now Java developers feel lucky that the language designers
> > > had to leave unchecked exceptions in, even though you get the
> feeling
> > > that they would have preferred otherwise.
> >
> > Java developers generally don't feel lucky about this:
> > http://www.mindview.net/Etc/Discussions/CheckedExceptions
> >
http://www.mindview.net/Etc/Discussions/UnCheckedExceptionComments
>
> What do you mean? That unchecked exceptions should not be part of
Java?
> (I know this is not your point of view, but I'm not sure where the
> misunderstanding is)

Sorry, I think this is about the gap between what you intended to say
and what I thought I read. Can we agree on:

"Java developers *should* (but don't) feel lucky that the language
designers had to leave unchecked exceptions in."

[snip]


> > Personally, I'd like to see an additional error reporting mechanism
in
> > C++ that can be used to ensure at compile time that errors are
> > handled. Some elements of the current exception handling design
could
> > be reused to support this but I don't think that exception
> > specifications should be hijacked for the purpose. (Nor, for
> > non-technical reasons, do I expect it to happen.)
>
> Wouldn't design by contract be a more promising approach for this kind
> of thing?

Are these goals not synergistic? Isn't the contract of the form:

Given (preconditions) this function maintains (invariants) and
results in either (normal return) or (error report).

Checked and unchecked exceptions are two of the mechanisms for
propagating an error report - and either or both may be appropriate
for a specific function.

Checked exceptions are appropriate when there is a reasonable prospect
of the client code continuing in a meaningful manner - either to a
normal return or to a domain specific error report.

Unchecked exceptions are appropriate when the normal behaviour of the
client code will be to propagate the error to its client.

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 19, 2002, 5:47:43 AM9/19/02
to
Alexander Terekhov <tere...@web.de> wrote in message
news:<3D873ADF...@web.de>...
> James Kanze wrote:
> [...]

> > The same as you would want a fatal error in case of arithmetic
> > overflow: you have generally written the program under the
> > assumption that type int is an integer. Good programmers are aware
> > of the problem, and validate input so that overflow cannot occur.
> > Bad programmers give wrong results. In this case, C++ is
> > theoretically superior, since it allows an implementation to
> > generate a fatal error here (whereas Java doesn't). The advantage
> > is purely theoretical, of course, because in fact, Java just
> > standardized what all C++ implementations do.
> ^^^^^^^^^^^^^^^^^^^^^^^^^^

> Unless you happen to have C++ implementation built ON TOP of some
> *reasonable* POSIX {threaded} >>C<< implementation (with C/SEH
> exceptions ;-)

Are you trying to tell me that there are C++ implementations where
INT_MAX + 1 does something different from giving INT_MIN, without
signaling an error? I've never seen one. I generally take steps to
avoid such expressions, so I may have used one without noticing it, but
from what I know of current implementations, I'd be very surprised to
get an error.

> ... for some oveflows as well) along the lines of:

> http://www.tru64unix.compaq.com/docs/base_doc/DOCUMENTATION/V51_HTML/ARH
> 9RBTE/DOCU0011.HTM#excep_defs
> (5.10 Exceptions Defined by the POSIX Threads Library)

> "....
> Exception object names that begin with the prefix pthread_
> are raised within the runtime environment itself and are not
> meant to be raised by your program code. Names of exception
> objects that begin with pthread_exc_ are generic and belong
> to the exceptions package or represent exceptions raised by
> the underlying system.

> Table 5-1 Names of Exception Objects Defined by the Threads
> Library

[...]
> ...."

All very nice, but an implementation is not required to generate these
errors. All that is required is the IF it generates an error, the error
take the form specified.

> Go...

> Finished!

> spe206.testdrive.compaq.com> cat intovf.c

And where is the exception (or any other type of error)? From your
output above, this machine works exactly like every other machine I've
seen.

> printf( "i = ++d: " );
> printf( "%11d\n", i = ++d );

This uses the floating point unit. Traditionally, floating point units
DO verify errors. But I'm not about to convert all of my arithmetic
into floating point, just to get the errors. Especially since the
semantics of floating point arithmetic are different than those of
integral arithmetic.

> }

--
James Kanze mailto:jka...@caicheuvreux.com

Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Robert Klemme

unread,
Sep 19, 2002, 4:54:45 PM9/19/02
to

James Kanze schrieb:


> > i was targeting more for the "philosophical" level: what is really
> > const?
>
> Whatever the programmer (or the designer) wants it to mean.

:-)) salomonic answer...

> > The fact that the keyword "mutable" was introduced points exactly
to
> > this issue.
>
> This was an issue when I started C++. We were still learning to use
the
> language, and there were great debates between bitwise const and
logical
> ("Humpty-Dumpty") const. As often happens, experience has shown that
> logical const is the answer, and it has been years since I've seen an
> experienced C++ programmer suggest anything else.

so here a convention has emerged that reduces the complexity of
the language by clearly stating a certain usage as standard. i
guess this can be viewed as a parallel to the use of "immutable
classes" in java.

> Lazy initialization is acceptable if the initialization cannot fail,
> from a conceptual point of view. For example, I've seen a lot of
> programs written as though they conceptually always had enough memory.
> Perfectly valid, if they arrange for some sort of fatal error if the
> assumption fails.

agreed.

> The same as you would want a fatal error in case of arithmetic
overflow:
> you have generally written the program under the assumption that type
> int is an integer. Good programmers are aware of the problem, and
> validate input so that overflow cannot occur. Bad programmers give
> wrong results. In this case, C++ is theoretically superior, since it
> allows an implementation to generate a fatal error here (whereas Java
> doesn't).

sorry, i didn't get it. java creates a ArithmeticException for
division by zero, which is a fatal error, isn't it? otoh, you
can add two big integers and don't get an exception:
Integer.MAX_VALUE + Integer.MAX_VALUE = -2 :-))

regards

robert

Alexander Terekhov

unread,
Sep 19, 2002, 6:03:29 PM9/19/02
to

James Kanze wrote:
[...]

> Are you trying to tell me that there are C++ implementations where
> INT_MAX + 1 does something different from giving INT_MIN, without
> signaling an error?

No. To tell the truth, I couldn't resist not posting an
example generating integer overflow exception in *C/C++*
that could have killed Arian V. ;-)

> I've never seen one.

Me neither. And I've just failed to find some Tru64 C/C++
option that would cause generation of addlv ("Add Longword
(with overflow)") instead of addl ("Add Longword (without
overflow)") instructions (something similar to the "-fptm
u" option and *with overflow* cvttqvc/cvtqlv vs. *without
overflow* cvttqc/cvtql stuff). :-(

<from another version of intovf.c>

void operation1()
{
++i;
}

void operation2()
{
i = d;
}

with "-fptm u" (cc -c -S -pthread -o intovf_c.o intovf.c):

operation1:
.context full
ldah $gp, ($27)!gpdisp!1
unop
lda $gp, ($gp)!gpdisp!1
unop
.frame $sp, 0, $26
.prologue 1
L$46:
.loc 1 12
# 11 {
# 12 ++i;
ldq $3, $$2$i-8($gp)!literal!2
# 000012
lda $3, 8($3)!lituse_base!2
ldl $4, ($3)
addl $4, 1, $4
stl $4, ($3)
.loc 1 13
# 13 }
ret ($26)
# 000013
.end operation1
unop
unop
.loc 1 10
.loc 1 15
# 14
# 15 void operation2()
.globl operation2
.ent operation2
.loc 1 15
operation2:
.context full
ldah $gp, ($27)!gpdisp!3
unop
lda $gp, ($gp)!gpdisp!3
unop
.frame $sp, 0, $26
.prologue 1
L$44:
.loc 1 17
# 16 {
# 17 i = d;
ldq $3, $$1$d($gp)!literal!4
# 000017
ldt $f0, ($3)!lituse_base!4
cvttqvc $f0, $f0
unop
cvtqlv $f0, $f1
sts $f1, 8($3)!lituse_base!4
.loc 1 18
# 18 }
ret ($26)
# 000018
.end operation2
unop
.loc 1 15
.loc 1 37

without "-fptm u" (cc -c -S -pthread -o intovf_c.o intovf.c):

operation2:
.context full
ldah $gp, ($27)!gpdisp!3
unop
lda $gp, ($gp)!gpdisp!3
unop
.frame $sp, 0, $26
.prologue 1
L$44:
.loc 1 17
# 16 {
# 17 i = d;
ldq $3, $$1$d($gp)!literal!4
# 000017
ldt $f0, ($3)!lituse_base!4
cvttqc $f0, $f0
cvtql $f0, $f1
sts $f1, 8($3)!lituse_base!4
.loc 1 18
# 18 }
ret ($26)
# 000018
.end operation2
unop
unop
.loc 1 15
.loc 1 37

regards,
alexander.

Nicola Musatti

unread,
Sep 19, 2002, 6:04:30 PM9/19/02
to

Alan Griffiths wrote:
[...]


> Sorry, I think this is about the gap between what you intended to say
> and what I thought I read. Can we agree on:
>
> "Java developers *should* (but don't) feel lucky that the language
> designers had to leave unchecked exceptions in."

Absolutely.

> [snip]
> > > Personally, I'd like to see an additional error reporting mechanism
> in
> > > C++ that can be used to ensure at compile time that errors are
> > > handled. Some elements of the current exception handling design
> could
> > > be reused to support this but I don't think that exception
> > > specifications should be hijacked for the purpose. (Nor, for
> > > non-technical reasons, do I expect it to happen.)

I think I agree with you, but the effectiveness of such a mechanism
depends on what you exactly mean by "ensure". I would say that the major
problem with Java's exception checking is that it lets the called
function specify the behaviour of the called one. This is a breach of
encapsulation. To a certain extent when we write a Java method we have
to decide which type of exception to throw based on how *all* the
callers of our function should behave.

Ideally if I specify a set of exceptions to be statically checked what I
would like is the compiler to tell me if my function throws directly or
indirectly any other exception, without any constraint being imposed on
my function's callers, unless a static exception specification is
provided for those functions too.

This would make it possible to remove the distinction between checked
and unchecked exceptions.

>From a C++ point of view, setting aside the problem of backward
compatibility, from the programmers' point of view this would only
require making the current exception specifications enforced at compile
time, but keeping the current "no check" default.

I realize that performing the indirect check would be costly, so it
should probably be made optional when functions without exception
specifications are involved. Additional, lint-like tools could perform
the full check.

What do you think?

Cheers,
Nicola Musatti

Robert Klemme

unread,
Sep 19, 2002, 6:17:45 PM9/19/02
to

Shannon Barber schrieb:


> I concur, but also take exception to the draconian garbage collector.
> It is a liability to soft RT systems, which otherwise could operate on
> desktop OSes without issue. Consider the effects of a collection on a
> 3D computer game, audio/video streaming, or a live mpeg(2) capture
> application (a digital VCR sort of thing). While many applications
> may benefit from GC, some applications are hampered by it.

java 1.4.1 addresses this with new gc types that try to improve
performance of gc and reduce impact on the application.

see http://java.sun.com/j2se/1.4.1/ and
http://java.sun.com/j2se/1.4.1/changes.html

> Cannot array bounds can be verified offline, at compile time or by a
> static analyze tool?

not in every case. think of some application that receives a
user input and uses this as index. or think of a class library
that has public methods that receive an index. you have to
include runtime checks for these. there is a number of cases
where you could optimize them away. usage of an array solely
inside a method with full control of the index var etc.

> I think it's largely a waste of resources to do
> so at run-time. I do not mean that buffers should not be checked
> (e.g. sprintf(buf, "%s", some_string) is a recipe for security holes
> :)), but that they should not be checked during random access /by
> default/. It may be reasonable to check some arrays upon every
> access, but not all of them. At the very least, you would want to be
> able to turn it off/ choose between two implementations.
> For example, assuming a non-pathologically behaved do_something
> function, "do_something(vector.begin(), vector.end())" will never
> violate its bounds (assuming vector has no bugs, which it shouldn't by
> now ;).

i'm not completely sure but i think moder vm's can omit the check
if it is safe. they're doing a lot of optimizaions on the fly.

regards

robert

James Kanze

unread,
Sep 20, 2002, 1:31:16 PM9/20/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D899E20...@gmx.net>...

> > The same as you would want a fatal error in case of arithmetic
> > overflow: you have generally written the program under the
> > assumption that type int is an integer. Good programmers are aware
> > of the problem, and validate input so that overflow cannot occur.
> > Bad programmers give wrong results. In this case, C++ is
> > theoretically superior, since it allows an implementation to
> > generate a fatal error here (whereas Java doesn't).

> sorry, i didn't get it. java creates a ArithmeticException for
> division by zero, which is a fatal error, isn't it?

So do many C++ implementations.

> otoh, you can add two big integers and don't get an exception:
> Integer.MAX_VALUE + Integer.MAX_VALUE = -2 :-))

Which is what I am talking about. Most programmers use int as an
abstraction for the integers. It should be a fatal error if the
abstraction fails. And when talking about integers (and not int),
247483647 + 1 gives 247483648, not -247483648 as it does in Java (and in
all 32 bit C++ implementations I know). A good programmer validates
input before hand, to ensure ranges which cannot cause overflow.

Of course, the real problems comes with floating point values. Far too
many programmers use them as an abstraction for real numbers. Which is
simply wrong; there isn't even a closed range for which the abstraction
is valid.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 20, 2002, 2:21:54 PM9/20/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D8A016E...@gmx.net>...

> Shannon Barber schrieb:
> > I concur, but also take exception to the draconian garbage
> > collector. It is a liability to soft RT systems, which otherwise
> > could operate on desktop OSes without issue. Consider the effects
> > of a collection on a 3D computer game, audio/video streaming, or a
> > live mpeg(2) capture application (a digital VCR sort of thing).
> > While many applications may benefit from GC, some applications are
> > hampered by it.

Of course, such implementations would be hampered by any dynamic memory
allocation in the critical section -- malloc isn't deterministic in the
time it takes either.

> java 1.4.1 addresses this with new gc types that try to improve
> performance of gc and reduce impact on the application.

Will they allow choosing among several garbage collectors? (There exist
real-time garbage collectors, which are more deterministic than malloc.
Typically, their total run-time cost is higher than the more simple
collectors, so you probably only want to use them when you need the
guaranteed response time.)

Are there provisions for ensuring that garbage collection doesn't run
within a given interval (supposing no dynamic allocations in that
interval). The usual way of handling situations like video streaming in
C++ is to do all of the allocations up front, before starting the
streaming. This is far more difficult in Java, but can be done.
However, it is only useful if I can guarantee that the garbage collector
won't trigger on its own during the critical section.

> > Cannot array bounds can be verified offline, at compile time or by a
> > static analyze tool?

> not in every case. think of some application that receives a user
> input and uses this as index.

This is a question of what constitutes a correct program. To me, a
program which can have an array bounds error in function of input is
incorrect.

Practically speaking, of course, current compiler technology isn't
capable of determining in every case, so the runtime check remains
necessary.

> or think of a class library that has public methods that receive an
> index. you have to include runtime checks for these.

You mean precondition checks, right. Something that you can do in C++,
but not (generally) in Java.

> there is a number of cases where you could optimize them away. usage
> of an array solely inside a method with full control of the index var
> etc.

You can do a lot better than that.

The most important optimization can almost always be done. If you have
a loop (say from 0 to n), it is almost always possible to hoist the
check out of the loop. Depending on context, this may be more difficult
in C++ or in Java: C++ has a lot of extra aliasing that has to be
considered, whereas Java has defined semantics even in the case of the
bounds error which must be respected.

> > I think it's largely a waste of resources to do so at run-time. I
> > do not mean that buffers should not be checked (e.g. sprintf(buf,
> > "%s", some_string) is a recipe for security holes :)), but that they
> > should not be checked during random access /by default/. It may be
> > reasonable to check some arrays upon every access, but not all of
> > them. At the very least, you would want to be able to turn it off/
> > choose between two implementations. For example, assuming a
> > non-pathologically behaved do_something function,
> > "do_something(vector.begin(), vector.end())" will never violate its
> > bounds (assuming vector has no bugs, which it shouldn't by now ;).

> i'm not completely sure but i think moder vm's can omit the check if
> it is safe. they're doing a lot of optimizaions on the fly.

From what I've understood, modern VM's typically eliminate about 80% of
the checks. Most importantly, they eliminate all of the checks in tight
loops -- the usual tactic is to generate the loop assuming an adequate
precondition such that the test is not necessary, and to check the
precondition before entering the loop. IF it ever turns out to be
false, the code is regenerated supposing a weaker precondition.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Paavo Helde

unread,
Sep 23, 2002, 11:09:26 AM9/23/02
to

James Kanze wrote:
> Of course, the real problems comes with floating point values. Far
too
> many programmers use them as an abstraction for real numbers. Which
is

So what do you suggest as an abstraction for real numbers then? ;-)

> simply wrong; there isn't even a closed range for which the
abstraction
> is valid.

Because any range of real axis (except of one-point ranges) contains
infinitely many real numbers, then even the whole universe cannot
represent it exactly (assuming finite universe). So there...

regards
Paavo

Robert Klemme

unread,
Sep 23, 2002, 6:02:49 PM9/23/02
to

James Kanze schrieb:


> > java 1.4.1 addresses this with new gc types that try to improve
> > performance of gc and reduce impact on the application.
>
> Will they allow choosing among several garbage collectors? (There exist
> real-time garbage collectors, which are more deterministic than malloc.
> Typically, their total run-time cost is higher than the more simple
> collectors, so you probably only want to use them when you need the
> guaranteed response time.)

yes, you can choose among them:
http://java.sun.com/j2se/1.4.1/changes.html#vm

> Are there provisions for ensuring that garbage collection doesn't run
> within a given interval (supposing no dynamic allocations in that
> interval). The usual way of handling situations like video streaming in
> C++ is to do all of the allocations up front, before starting the
> streaming. This is far more difficult in Java, but can be done.
> However, it is only useful if I can guarantee that the garbage collector
> won't trigger on its own during the critical section.

well, i guess you can achieve this nearly since you can asl the
gc to run with System.gc() (although this is not a guarantee that
it runs) and by choosing the concurrent mark sweep collector that
looks out for low cpu utilization. of course you will have to
give your application enough mem.

> > not in every case. think of some application that receives a user
> > input and uses this as index.
>
> This is a question of what constitutes a correct program. To me, a
> program which can have an array bounds error in function of input is
> incorrect.

well, yes. but still i prefer a program that terminates
gracefully with a runtimeexception (including a stack trace -
most important!) than a program that simply does something in the
range from crashing "proper" continuation.

> Practically speaking, of course, current compiler technology isn't
> capable of determining in every case, so the runtime check remains
> necessary.

i think so.

> > or think of a class library that has public methods that receive an
> > index. you have to include runtime checks for these.
>
> You mean precondition checks, right. Something that you can do in C++,
> but not (generally) in Java.

si.

> > i'm not completely sure but i think moder vm's can omit the check if
> > it is safe. they're doing a lot of optimizaions on the fly.
>
> From what I've understood, modern VM's typically eliminate about 80% of
> the checks. Most importantly, they eliminate all of the checks in tight
> loops -- the usual tactic is to generate the loop assuming an adequate
> precondition such that the test is not necessary, and to check the
> precondition before entering the loop. IF it ever turns out to be
> false, the code is regenerated supposing a weaker precondition.

thanks for this elaboration! i think the runtime overhead then
is neglectable with this considerations and one does not
necessarily need to be able to switch the check off.

regards

robert

Drew Hall

unread,
Sep 23, 2002, 6:18:28 PM9/23/02
to

"Paavo Helde" <firs...@ebi.ee> wrote in message
news:3D8B6B97...@ebi.ee...

>
>
> James Kanze wrote:
> > Of course, the real problems comes with floating point values. Far
> too
> > many programmers use them as an abstraction for real numbers. Which
> is
> > simply wrong; there isn't even a closed range for which the
> abstraction
> > is valid.
>
> Because any range of real axis (except of one-point ranges) contains
> infinitely many real numbers, then even the whole universe cannot
> represent it exactly (assuming finite universe). So there...

As long as we're splitting hairs here, [0,0] is a perfectly valid closed
range over
which the abstraction is valid...not that that diminishes the overall
argument in
any way :).

Drew

James Kanze

unread,
Sep 24, 2002, 3:05:19 PM9/24/02
to
Paavo Helde <firs...@ebi.ee> wrote in message
news:<3D8B6B97...@ebi.ee>...
> James Kanze wrote:
> > Of course, the real problems comes with floating point values. Far
> > too many programmers use them as an abstraction for real numbers.
> > Which is

> So what do you suggest as an abstraction for real numbers then? ;-)

There isn't one. Which is what makes numeric processing so difficult.

> > simply wrong; there isn't even a closed range for which the
> > abstraction is valid.

> Because any range of real axis (except of one-point ranges) contains
> infinitely many real numbers, then even the whole universe cannot
> represent it exactly (assuming finite universe). So there...

isn't one. That's my whole point: there is no possible abstraction for
real numbers, at least on a finite machine.

This means that whenever you use floating point arithmetic, you must
analyse carefully if the abstraction actually being used is "close
enough". Surprisingly, there are a very large number of cases (most?)
where it isn't -- you must consider that addition isn't associative,
etc. This doesn't mean that you can't do real calculations using
machine floating point. It does mean that you really have to know what
you are doing.

Obviously, if the goal is to convert Francs into Euros( a single
division) and I don't really care about the cents (it's not bookkeeping,
but just to roughly compare prices), then the abstraction is probably
close enough. If it is bookkeeping, the abstraction ISN'T close enough,
and I must do something else. If I'm calculating physical values (say
average velocity from distance and time), three digits precision is
sufficient, and the input values are far enough from the limits that
there is no risk of overflowing, then the abstraction is probably close
enough. If instead of average velocity, I want instant velocity, using
differentiation, it probably isn't, and a correct solution using machine
floating point will likely be different than the correct solution using
real numbers. And anytime more than a couple of operations (two or
three) are involved, or any of the values are anywhere near the upper or
lower limits, the abstraction starts to fail.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

James Kanze

unread,
Sep 24, 2002, 3:05:44 PM9/24/02
to
Robert Klemme <bob....@gmx.net> wrote in message
news:<3D8F3DB9...@gmx.net>...
> James Kanze schrieb:

> > > not in every case. think of some application that receives a user
> > > input and uses this as index.

> > This is a question of what constitutes a correct program. To me, a
> > program which can have an array bounds error in function of input is
> > incorrect.

> well, yes. but still i prefer a program that terminates gracefully
> with a runtimeexception (including a stack trace - most important!)
> than a program that simply does something in the range from crashing
> "proper" continuation.

Well, what I was asking for was a compiler error:-). Except that such
programs are legal (both in Java and in C++), so about all we can get is
a warning. In ideal world, I would get a message something like:

[calcul.cc:1234] WARNING: calcule may overflow if i (entered at
[input.cc:678]) > 153.

Except that it might have to walk back a list of variables until finding
the one actually input.

But as I said, current compiler technology is far (very far) from being
able to detect these cases, so...

> > Practically speaking, of course, current compiler technology isn't
> > capable of determining in every case, so the runtime check remains
> > necessary.

> i think so.

> > > or think of a class library that has public methods that receive
> > > an index. you have to include runtime checks for these.

> > You mean precondition checks, right. Something that you can do in
> > C++, but not (generally) in Java.

> si.

Full function instrumentation is not possible in a Java interface. And
you can't multiply inherit from a Java abstract class. So you any
precondition checks are incompatible with implementing multiple
logical interfaces with the same class.

And of course, to ensure that the instrumentation is active, the virtual
functions must be private. Something that you cannot do in Java either.

> > > i'm not completely sure but i think moder vm's can omit the check
> > > if it is safe. they're doing a lot of optimizaions on the fly.

> > From what I've understood, modern VM's typically eliminate about 80%
> > of the checks. Most importantly, they eliminate all of the checks
> > in tight loops -- the usual tactic is to generate the loop assuming
> > an adequate precondition such that the test is not necessary, and to
> > check the precondition before entering the loop. IF it ever turns
> > out to be false, the code is regenerated supposing a weaker
> > precondition.

> thanks for this elaboration! i think the runtime overhead then is
> neglectable with this considerations and one does not necessarily need
> to be able to switch the check off.

The runtime overhead certainly is (or can be) negligible in Java. I'm
less certain in C++, because of the way arrays end up being pointers.
At least one C++ implementation did implement full bounds checking, but
as far as I know, there was never any effort to optimize the results.
And with its "fat" pointers (the equivalent of a pointer and two
size_t's in normal C++), I suspect that the results would never have
been as fast as straight C++.

The proof that Java's runtime bounds checking has an acceptable cost, of
course, is the fact that mathematical programs making heavy use of Java
arrays run as fast, and often faster, in Java than in C++. The
optimizer can get all of the bounds checking out of the inner loops, and
doesn't have to worry about aliasing. On the other hand, switch the
arrays to Vector, which means wrapping the doubles in Double, and
constantly casting down, and C++ wins hands down.

--
James Kanze mailto:jka...@caicheuvreux.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

0 new messages