jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 05:49pm on 15/03/2021
You've been able to can auto-close a closable thing for ages now.
try(Reader r = new FileReader(/*blah*/)){
   r.whatever();
}
// r is automatically closed
But today I found that it works for something you already opened!
Reader r = new FileReader(/*blah*/);
try(r){
   r.whatever();
}
// r is automatically closed
This came up because I had a list of files and I wanted to close each one after handling it. So I couldn't create it in the header of the try block.
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 12:33pm on 19/01/2021
In some languages you can write a method that returns two things, and then say something like
a, b = getCatAndDog()
That's not allowed in Java. Why not? You could do something like...
class Pair<T,U>{/*boilerplate to handle two things*/}

Pair<Cat,Dog> x = getCatAndDog();
Cat a = x.getLeft();
Dog b = x.getRight();
Ouch, and what if you want more than two?

I have done it with Object[] but that's pretty hacky, and I've seen people return a map of names to values, but both of those are type unsafe (you'd have to cast the return values).

There's a syntax for multiple declarations...
int a, b;
... so that could be extended to allow multiple types:
Cat, Dog a, b = getCatDog();
or with the new type inference:
var a, b = getCatAndDog();
Now I'm wondering how to make that proposal...

Edit: The process seems to be to sign up at jcp.org and submit a JSR. Bit daunting.
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 09:14pm on 01/10/2020
(Cross-posted from my own account - I put it there because I forgot this community existed!)

There are so many ways to iterate in Java. 8~(

Suppose that we have
class Thing{...}
interface Processor{void process(Thing thing);}
We want to process each thing. How do we complete this method?
void processAllThings(List<Thing> things, Processor p){
    // ???
}
  1. old skool C-style:
    for ( int i = 0; i < things.size(); i++ )
        p.process( things.get( i ) );
    Bonus variant 1:
    for ( int i = 0; ; ) {
        if ( i >= things.size() )
            break;
        p.process( things.get( i++ ) ); // careful where you put the ++
    }
    Bonus(?!) variant 2:
    for ( int i = 0; ; ) {
        try {
            p.process( things.get( i++ ) );
        } catch ( IndexOutOfBoundsException x ) { // spot the bug
            break;
        }
    }
    Bonus(?!) variant 3:
    for ( int i = 0; ; ) {
        Thing thing = null;
        try {
            thing = things.get( i++ );
        } catch ( IndexOutOfBoundsException x ) {
            break;
        }
        p.process( thing );
    }
  2. You can use while (but who does that?)
    int i = 0
    while ( i < things.size() )
        p.process( things.get( i++ ) );
  3. You can use do... while (but who does that?)
    int i = 0
    do
        p.process( things.get( i ) );
    while ( ++i < things.size() ); // careful where you put the ++
  4. Still left over from before 1.2:
    Vector v = new Vector(things);
    for ( Enumeration e = v.elements(); e.hasNextElement();  )
        p.process( (Thing)e.nextElement() );
  5. Still left over from before 1.5:
    for ( Iterator i = things.iterator(); i.hasNext();  )
        p.process( i.next() );
  6. Still left over from before 1.8:
    for ( Thing thing : things )
        p.process ( thing );
    Bonus variant for newer Java versions:
    for ( var thing : things )
        p.process ( thing );
  7. Arrived in 1.8:
    things.forEach(
        p::process
    );
    Bonus variant 1:
    things.forEach(
        thing -> p.process(thing);
    );
    Bonus variant 2:
    things.forEach(
        new Consumer(){
            @Override public void accept(Thing thing){
                p.process(thing);
            }
        }
    );
  8. Can't be bothered with the lambda variants this time.
    things.stream()
        .forEach(
            p::process
        );
Phew! Hmm - I probably missed some...
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 04:56pm on 09/06/2013
I have a development framework for Swing apps called Compositor. Although I wrote it for my own benefit, I'd be interested in feedback from other developers. Would anyone like to have a go with it and tell me how they get on?
lea_hazel: Neuron cell (Science: Brains)
posted by [personal profile] lea_hazel at 12:50pm on 25/01/2012
I realize this community hasn't been updated in almost a year, and that it only has a few members. However, I'm going to risk it and attempt a shot in the dark.

I was a Java developer a few years ago and I haven't touched it in a while. I never had an IDE installed on my home computer, since I've never needed one. Now I'm suddenly feeling a strange craving to mess around and code something, for my own amusement. Can anyone recommend a lightweight, freeware IDE that I can use? I've been thinking of maybe installing IntelliJ.
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 09:36am on 07/03/2011
     [java] 2011-03-07 08:57:04.693 java[399] CFLog (0): CFMessagePort: bootstrap_register(): failed 1103 (0x44f), port = 0xf803, name = 'java.ServiceProvider'
     [java] See /usr/include/servers/bootstrap_defs.h for the error codes.
     [java] 2011-03-07 08:57:04.694 java[399] CFLog (99): CFMessagePortCreateLocal(): failed to name Mach port (java.ServiceProvider)
Sometimes I get that in build output on my Mac. The file it says I should see doesn't help. It turns out that it means "You are compiling while another Java process is running".
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 04:14pm on 28/02/2011
I've been using Groovy. It's a pleasant scripting language that runs in a JVM, and has a Java-ish syntax. There are a number of differences to Java. One is it's relaxed attitude to typing, which I noticed when returning to something I wrote a while ago.
if ( someCondition ) {
    // do stuff...
} else if ( anotherCondition ) {
    // do other stuff...
} else {
    barf
}
WTF is barf? It looks like I was roughing out the code, and intending to come back to throw some exception if neither condition is true. In Java, the compiler would have complained about barf. But in the relaxed world of Groovy, the code works. After a little testing, I find that executing barf produces groovy.lang.MissingPropertyException: No such property: barf which is pretty much what I wanted!
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 03:10pm on 04/01/2011
I love logging. In many ways it's more useful than a debugger. Long ago I wrote a simple logger, and I still use it, or nowadays Java has a built-in logger, and in my experience it's fine.

But I hate Log4J. There's one straightforward reason: by default, Log4j does nothing useful. I couldn't count the times I've seen "Please initialize the Log4J system correctly" as if it were my fault. It's a logger doesn't log!

Another reason is that to specify a daily rolling log file (which is almost always what you want) requires 5 (or more) lines of configuration.

So here's a rule for writing any software. Do the simplest useful thing by default, and make the most likely use cases as simple as possible. Log4J fails on both counts.
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 05:52pm on 21/05/2009
I'm working on a project which involves a lot of JSP in an "interesting" CMS. We have a consultant helping us with the "interesting" bits. Today he gave us a JSP containing the following (some details elided to protect the guilty):
String sql = "SELECT * FROM tree WHERE id in (
	SELECT parent FROM tree WHERE id=" + parent + ")";
parents = cms.SQL ( sql );
I'd like to propose this for the canonical example of what *not* to do.

Edit: Many people dislike JSPs. They don't bother me, but they do allow you to do anything at all, not just rendering. In this particular case, the JSP has to know about the database table structure [sigh], and it should (but probably doesn't) sanitise the parent parameter [sigh], and it has to have a database connection wrapper object [sigh].

I'm even a little miffed about pointless local variable sql, but I'll let that one go. Oh, and KEYWORDS in UPPER case annoys me too, but some people think it's more readable.
jbanana: Badly drawn banana (Default)
posted by [personal profile] jbanana at 11:29pm on 06/05/2009
This is a community for anyone writing Java code.

After enjoying the java_dev community on LJ so much, I thought there should be a DW place for people who write Java. This is it.

Links

March

SunMonTueWedThuFriSat
  1
 
2
 
3
 
4
 
5
 
6
 
7
 
8
 
9
 
10
 
11
 
12
 
13
 
14
 
15 16
 
17
 
18
 
19
 
20
 
21
 
22
 
23
 
24
 
25
 
26
 
27
 
28
 
29
 
30
 
31