Java language and library suggestions

C

chucky

Hello!
If I have a suggestion for extending the Java language and library,
what is the right place to discuss it?

I include a few things that I came across lately and would like to
have in Java. I will appreciate your comments.

1. introduce method
int String.byteLength(Charset charset);
that would return the length of the string in bytes in the given
charset. This would avoid calling String.getBytes(charset).length,
thus avoid allocating the byte array.

2. allow to specify character encoding for PrintStream. Java 6 SE's
PrintStream prints the characters in platform's default character
encoding.

3. Catch multiple exception types at once. The syntax could be
something like
try {
...
} catch(MalformedURLException, UnsupportedEncodingException as
IOException e){
// handle IOException e
}

4. Sometimes having to catch an exception that will never be thrown is
really annoying.
For example, I would like to write something like

@safe
URI uri = new URI("http://valid.uri.com/");

instead of

URI uri;
try {
uri = new URI("http://valid.uri.com/");
} catch(URISyntaxException e) {
throw new AssertionError(e);
}

I used the annotation notation, but I doubt something like this can be
achieved with annotations. It would be nice if the language had a
construct to mark some code exception safe and if it threw an
exception, it would result in AssertionError. It could also be more
flexible, like this

@safe(NumberFormatException, UnsupportedEncodingException)
{
// statement that should not throw any NumberFormatException or
UnsupportedEncodingException
// and if it does, it is an AssertionError
}
 
R

Roedy Green

2. allow to specify character encoding for PrintStream. Java 6 SE's
PrintStream prints the characters in platform's default character
encoding.

That is already done. See PrintWriter.
--
Roedy Green Canadian Mind Products
http://mindprod.com

"For reason that have a lot to do with US Government bureaucracy, we settled on the one issue everyone could agree on, which was weapons of mass destruction."
~ Paul Wolfowitz 2003-06, explaining how the Bush administration sold the Iraq war to a gullible public.
 
L

Lew

chucky said:
2. allow to specify character encoding for PrintStream. Java 6 SE's
PrintStream prints the characters in platform's default character
encoding.

Streams don't get character encodings.
4. Sometimes having to catch an exception that will never be thrown is
really annoying.
For example, I would like to write something like

@safe
URI uri = new URI("http://valid.uri.com/");

instead of

URI uri;
try {
uri = new URI("http://valid.uri.com/");
} catch(URISyntaxException e) {
throw new AssertionError(e);
}


That's not the language, that's the API. The API designer makes that
decision. They do it on purpose.

There is no way the library can know that the exception will never be thrown,
because there is no way the library can know that you will never make a
mistake with the argument to the method. Therefore your statement that the
"exception will never be thrown" is inaccurate. Remember, method arguments
deal with the general case of all possible inputs, not the specific input you
happened to give it on Saturday.
I used the annotation notation, but I doubt something like this can be
achieved with annotations. It would be nice if the language had a
construct to mark some code exception safe and if it threw an
exception, it would result in AssertionError. It could also be more
flexible, like this

@safe(NumberFormatException, UnsupportedEncodingException)
{
// statement that should not throw any NumberFormatException or
UnsupportedEncodingException
// and if it does, it is an AssertionError
}

This is no more simple than guaranteeing that the argument is correct. What
is your beef with catching exceptions anyway? How hard is it? It's not like
you're hauling rocks; you're just typing a few extra characters.
 
R

Roedy Green

3. Catch multiple exception types at once. The syntax could be
something like
try {
...
} catch(MalformedURLException, UnsupportedEncodingException as
IOException e){
// handle IOException e
}

I have often wished for to specify a list of types so you can avoid
duplicating code
--
Roedy Green Canadian Mind Products
http://mindprod.com

"For reason that have a lot to do with US Government bureaucracy, we settled on the one issue everyone could agree on, which was weapons of mass destruction."
~ Paul Wolfowitz 2003-06, explaining how the Bush administration sold the Iraq war to a gullible public.
 
A

Arne Vajhøj

chucky said:
If I have a suggestion for extending the Java language and library,
what is the right place to discuss it?

It should eventually go the relevant JCP JSR.

But you can start by hosting here to see how people like it.
1. introduce method
int String.byteLength(Charset charset);
that would return the length of the string in bytes in the given
charset. This would avoid calling String.getBytes(charset).length,
thus avoid allocating the byte array.

It would. But it would not save much time. It would still need
to iterate and generate all the bytes - just not saving them.

But I think it would be as useful as many existing methods, so
I would not complain if it was added.

I think it should go into CharsetEncoder not String though.
2. allow to specify character encoding for PrintStream. Java 6 SE's
PrintStream prints the characters in platform's default character
encoding.

I believe there already are constructors that supports that.
3. Catch multiple exception types at once. The syntax could be
something like
try {
...
} catch(MalformedURLException, UnsupportedEncodingException as
IOException e){
// handle IOException e
}

I like the comma separated list idea.
4. Sometimes having to catch an exception that will never be thrown is
really annoying.
For example, I would like to write something like

@safe
URI uri = new URI("http://valid.uri.com/");

instead of

URI uri;
try {
uri = new URI("http://valid.uri.com/");
} catch(URISyntaxException e) {
throw new AssertionError(e);
}

I used the annotation notation, but I doubt something like this can be
achieved with annotations. It would be nice if the language had a
construct to mark some code exception safe and if it threw an
exception, it would result in AssertionError. It could also be more
flexible, like this

@safe(NumberFormatException, UnsupportedEncodingException)
{
// statement that should not throw any NumberFormatException or
UnsupportedEncodingException
// and if it does, it is an AssertionError
}

I don't like that idea.

It is relative rare that you will need that (because even though the
code may not throw the exception now, then it may in the future), so
I think it is OK to ask people to explicit code for it.

Arne
 
M

markspace

chucky said:
Hello!
If I have a suggestion for extending the Java language and library,
what is the right place to discuss it?


If you just want chit chat, here's fine. If you wanted to reach Sun,
their window for suggestions closed up a couple of months ago. See
Project Coin for a list of what suggestions were proposed.

http://blogs.sun.com/darcy/date/20090331


I don't think I could personally support many of your proposals, however....
3. Catch multiple exception types at once. The syntax could be
something like

This got accepted and is under consideration. I think it's looking good.
 
T

Tomas Mikula

Streams don't get character encodings.

OK. I just wanted to print to System.out, which is a PrintStream, with
a given encoding. So I have to wrap it by a PrintWriter.
That's not the language, that's the API.  The API designer makes that
decision.  They do it on purpose.

There is no way the library can know that the exception will never be thrown,
because there is no way the library can know that you will never make a
mistake with the argument to the method.  Therefore your statement that the
"exception will never be thrown" is inaccurate.  Remember, method arguments
deal with the general case of all possible inputs, not the specific input you
happened to give it on Saturday.

But if I know that I provide the correct input (and if not, I want my
program to crash, because I consider it a programming error), I still
have to write these extra lines of code. Do it 4 times in one method
and the readability of the code suffers a lot. Example, when I want my
program to crash on wrong input, is when the input comes from the
configuration file, or is hardcoded in the program code. Such input is
parsed only at the application startup and it's OK to crash. So I
don't want to catch the exception, but I don't want to declare it all
the way up the call hierarchy either.
This is no more simple than guaranteeing that the argument is correct.  What
is your beef with catching exceptions anyway?  How hard is it?  It's not like
you're hauling rocks; you're just typing a few extra characters.

Generally, I like Java's checked exception. I just don't want to
handle them when I am *sure* they won't be thrown. As I explained
above, in some cases I can guarantee the correctness of the argument.
These `few' extra character can make the code a lot less elegant.

Regards,
Tomas
 
T

Tomas Mikula

I don't like that idea.

It is relative rare that you will need that (because even though the
code may not throw the exception now, then it may in the future), so
I think it is OK to ask people to explicit code for it.

Did you mean that the number format, url format, ... may change and
previously valid values will become invalid?
If so, I want to do the same thing, let my program crash, but without
the extra code needed.
Maybe I didn't explain it clearly the first time. I didn't mean that
no exceptions would be checked within the code marked with @safe.
Rather if an exception in such code occured, AssertionError would be
thrown.

Regards,
Tomas
 
L

Lew

markspace said:

There are some amazingly bad suggestions there. For example, the proposal to
allow "#switch (...) instanceof" is ludicrous. Others look all right on the
face of them, such as "open and close brace optional for single statement try,
catch, finally, method declaration", but then we would just mandate to put the
braces back in by convention just like we do now for 'if' and 'for' and such.
Others make sense to me, like "Allow the class literal of the surrounding
class to be referenced with the 'class' keyword".

"Underscores in numbers" is another stupid one.

I'm sure others have similar reactions, with different suggestions plugged
into "ludicrous", "plausible but not really" and "good idea" from mine.
 
M

markspace

Tomas said:
But if I know that I provide the correct input (and if not, I want my
program to crash, because I consider it a programming error),


Err...
public void someMethod() throws Exception
{
URL uri = new URI("http://cnn.com.");
}

Generally, I like Java's checked exception. I just don't want to
handle them when I am *sure* they won't be thrown. As I explained
above, in some cases I can guarantee the correctness of the argument.
These `few' extra character can make the code a lot less elegant.

Or if you have several statements that might throw, then lump them all
together. Using the "cause" parameter in a new exception provides an
adequate stack trace, I think.

try {
someMethod(); // several config methods, as above, each
otherMethod(); // with "throws Exception".
....
} catch( Exception x ) {
throw new Error( x );
}
 
T

Tomas Mikula

Err...
   public void someMethod() throws Exception
   {
      URL uri = new URI("http://cnn.com.");
   }


Or if you have several statements that might throw, then lump them all
together.  Using the "cause" parameter in a new exception provides an
adequate stack trace, I think.

   try {
     someMethod();  // several config methods, as above, each
     otherMethod(); // with "throws Exception".
     ....
   } catch( Exception x ) {
     throw new Error( x );
   }

I don't find this as a clean solution.
1. I don't want to write a separate method instead of one line of
code. And if I would, I would write someMethod() like this:
void someMethod() {
try {
URL uri = new URI("http://cnn.com.");
} catch(URISyntaxException e){
throw new AssertionError(e);
}
}

2. if someMethod() throws Exception, I have to catch it in all methods
calling someMethod().

3. Anyone who will ever call someMethod() should read its
documentation to find out that either
a) the method declares Exception, but it will never be thrown, and
if yes, it should be propagated as error; or
b) the method declares Exception, which can be SocketException or
FileNotFoundException, and if it is something else, it should be
propagated as error.


Tomas
 
J

Joshua Cranmer

Lew said:
There are some amazingly bad suggestions there. For example, the
proposal to allow "#switch (...) instanceof" is ludicrous. Others look
all right on the face of them, such as "open and close brace optional
for single statement try, catch, finally, method declaration", but then
we would just mandate to put the braces back in by convention just like
we do now for 'if' and 'for' and such. Others make sense to me, like
"Allow the class literal of the surrounding class to be referenced with
the 'class' keyword".

"Underscores in numbers" is another stupid one.

I'm sure others have similar reactions, with different suggestions
plugged into "ludicrous", "plausible but not really" and "good idea"
from mine.

That was just a proposal list, some of which are woefully
underspecified. It seems the strongest contenders were the first ones
which were passed, namely Strings in switch (there are some cases where
that's useful), the catch-multiple exceptions, ARM (that is probably
going to be the real Java 7 killer feature), shortening generic
construction (slightly hellish for compilers, I suppose), null-safe
operators (which generated strong opposing positions), and apparently
generics+varargs savory goodness.

Note that all of these are for further consideration, which seems to me
to be mostly "projects that would likely be more beneficial than not and
which have clear specifications" as opposed to "projects that will be
making it into Java 7".

I'd say the projects most likely to make it in are the catch-multiple,
ARM, and generics goodnesses: all of these are very clear-cut,
compiler-level changes that have very demonstrable use cases and little
opposition.

The safe-null-check operators can be confusing and misleading at times
for the unwary users, and Strings in switch is in the apathetic center.
A lot of the second round picks have some extreme polarizations in view;
probably the easiest one there is the binary literal type, which
requires minimal changes to the lexer.
 
L

Lew

Joshua said:
That was just a proposal list, some of which are woefully
underspecified. It seems the strongest contenders were the first ones
which were passed, namely Strings in switch (there are some cases where
that's useful), the catch-multiple exceptions, ARM (that is probably
going to be the real Java 7 killer feature), shortening generic
construction (slightly hellish for compilers, I suppose), null-safe
operators (which generated strong opposing positions), and apparently
generics+varargs savory goodness.

Note that all of these are for further consideration, which seems to me
to be mostly "projects that would likely be more beneficial than not and
which have clear specifications" as opposed to "projects that will be
making it into Java 7".

I'd say the projects most likely to make it in are the catch-multiple,
ARM, and generics goodnesses: all of these are very clear-cut,
compiler-level changes that have very demonstrable use cases and little
opposition.

The safe-null-check operators can be confusing and misleading at times
for the unwary users, and Strings in switch is in the apathetic center.
A lot of the second round picks have some extreme polarizations in view;
probably the easiest one there is the binary literal type, which
requires minimal changes to the lexer.

I forget, did someone suggest unsigned bytes? That's probably the single most
glaring defect in Java.
 
J

Joshua Cranmer

Lew said:
I forget, did someone suggest unsigned bytes? That's probably the
single most glaring defect in Java.

Close:
<http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000906.html>

Basically, it adds an unary operator "(+)" (the ( and ) are part of it)
that would be equivalent to an & 0xff or 0xffff for byte and short or
char operands, respectively.

I think adding unsigned type(s) would be a sufficiently involved change,
in both language and library (face it: IO stream utilities would need to
be switched over to use it to be useful), that it falls out of scope for
Project Coin. Note that none of the selected proposals for further
consideration, with the exception of large arrays, involve significant
VM change.
 
T

Tomas Mikula

Tomas Mikula wrote:

...


The best solution I've found so far for this problem is to create my own
RuntimeException subclass:

try{
   // whatever}(catch IOException e){

   throw new MyApplicationInternalException(e);

}

MyApplicationInternalException is strictly reserved for conditions that
indicate the application itself went wrong, such as an Exception that
should not be possible. Because it subclasses RuntimeException it does
not need to be declared in each method.

It has a constructor that is something like:

MyApplicationInternalException(Exception e){
   super("Internal error in my application: "+e.toString(),e);

}

It can either be caught at the top level and suitably reported, or let
cause the application to crash.

This is basically the same code that I wanted to get rid of in the
original post by replacing it with

@safe
whatever_statement;

except that I would throw AssertionError instead of
MyApplicationInternalException.

I will repeat the intended semantics of the above proposal once again:
"I have assured that whatever_statement will not throw any exception,
so I ask the compiler not to force me to catch or declare the
exception. If it despite all my effort throws an exception, it is an
error in application logic (such as failed assertion) and the
exception should be rethrown as AssertionError."
Note that you *have* to do something to distinguish the "cannot possibly
happen" exceptions. It is not usually possible for the compiler to tell
whether you intended to have code enforcing the relevant conditions or not.

This is what I meant the @safe directive for. To tell the compiler
that I took care of valid input. And if I did it wrong, let my program
crash, but don't force me to handle the exceptions.

Tomas
 
A

Arne Vajhøj

Tomas said:
Did you mean that the number format, url format, ... may change and
previously valid values will become invalid?
If so, I want to do the same thing, let my program crash, but without
the extra code needed.
Maybe I didn't explain it clearly the first time. I didn't mean that
no exceptions would be checked within the code marked with @safe.
Rather if an exception in such code occured, AssertionError would be
thrown.

The problem is that your code is demo code.

In real code you typical have an interface that declares
a throw exception.

And even though you may know tat the current implementation
code will never throw the exception, then another implementation
in the future may.

Arne
 
T

Tomas Mikula

The problem is that your code is demo code.

In real code you typical have an interface that declares
a throw exception.

And even though you may know tat the current implementation
code will never throw the exception, then another implementation
in the future may.

Arne

That doesn't change anything. Maybe I chose a misleading name. Maybe I
should have chosen @assert instead of @safe.
Then
@assert any_statement;
means that I make an assertion that any_statement will not throw any
exception. And if it does, it is an AssertionError.
And if the semantics of any_statement changes in the future, it's
still an AssertionError.
Consider the example:

int i;
try {
i = Integer.parseInt(valid_int_string);
} catch(NumberFormatException e) {
throw new AssertionError(e);
}

What you say means that I should not throw AssertionError, because in
the future the code could really throw the NumberFormatException. But
if it does, I still want to get the AssertionError, because
continueing without the correct value in i does not have any sense.

As with everything, the use of @safe (@assert) would be a deliberate
decision of the programmer.

Tomas
 
A

Arne Vajhøj

Tomas said:
That doesn't change anything. Maybe I chose a misleading name. Maybe I
should have chosen @assert instead of @safe.
Then
@assert any_statement;
means that I make an assertion that any_statement will not throw any
exception. And if it does, it is an AssertionError.
And if the semantics of any_statement changes in the future, it's
still an AssertionError.
Consider the example:

int i;
try {
i = Integer.parseInt(valid_int_string);
} catch(NumberFormatException e) {
throw new AssertionError(e);
}

What you say means that I should not throw AssertionError, because in
the future the code could really throw the NumberFormatException. But
if it does, I still want to get the AssertionError, because
continueing without the correct value in i does not have any sense.

As with everything, the use of @safe (@assert) would be a deliberate
decision of the programmer.

The new code snippet is still demo code and does at all cover
what I was talking about: interfaces.

If a method in an interface is declared to throw an exception
then it is a clear statement that it may happen either now or
in the future.

Assertions is something that is expected never to happen.

Converting exceptions to assertions in such a case is a severe
violation of OO principles.

And that type of situations happens a lot more frequently than
the simple examples you have given.

Arne
 
T

Tomas Mikula

The new code snippet is still demo code and does at all cover
what I was talking about: interfaces.

If a method in an interface is declared to throw an exception
then it is a clear statement that it may happen either now or
in the future.

Assertions is something that is expected never to happen.

Converting exceptions to assertions in such a case is a severe
violation of OO principles.

Then one would not use the proposed @safe directive in that case. I
didn't suggest to use it any time it seems that the code does not
throw exceptions.
Anyway there are still many cases when one could use safely it to get
more readable code.

Tomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top