views:

35

answers:

2

Hi all,

We use the http://jedi.codehaus.org libraries for working with collections and manipulating them in a functional way. We recently came across a problem when doing something similar to the following:

public class Address {
    //constructors and stuff

    public KiloWatts electricityConsumed(Duration timePeriod) throw NoElectricitySupply {
        .... does stuff but can throw checked exception
    } 
}

given we have a collection of addresses and we wanted to perform something on the UnitsOfElectricity associated with each address, how would you handle the thrown exception e.g.:

public KiloWatts totalEnergyConsumed(Address... addresses, final Duration timePeriod) {
     List<KiloWatts> energyConsumedPerAddress = FunctionalPrimitives.collect(addresses, new Functor<Address, KiloWatts>{
         public KiloWatts execute(Address address){
              try {
                  return address.energyConsumed(timePeriod);
              } catch (NoElectricitySupply e) {

                  //What do you do here?

              }
         }
     });
}

How would you handle the exception?

+1  A: 

If NoElectricitySupply is logically equivalent to zero KiloWatts, shouldn't you just return such object?

If they're not quite equivalent, you could create some sort of special NoKiloWatts subclass and return an instance of such in the catch block.

Joonas Pulakka
I agree. I would liken this to the concept of "not a number" (NaN) that you can encounter when you perform certain math operations.
John Munsch
Nope - No electricity supply could mean they're not connected, perhaps they use gas or something instead. So zero kilowatts wouldn't necessarily model the situation correctly.
Stuart Ervine
+1  A: 

As far as I can tell, you have 2 options:

  1. throw a runtime exception (and ignore it); or
  2. throw a runtime exception, using it to 'marshall' the checked exception past the interface boundary.

for (2), something like:

public KiloWatts totalEnergyConsumed(Address... addresses, final Duration timePeriod) {
    try {
        List<KiloWatts> energyConsumedPerAddress = FunctionalPrimitives.collect(addresses, new Functor<Address, KiloWatts>{
            public KiloWatts execute(Address address){
                try {
                    return address.energyConsumed(timePeriod);
                } catch (NoElectricitySupply e) {
                    throw new RuntimeException("internal marshalling exception", e);
                }
           }
       });
    } catch(RuntimeException re) {
        throw e.getCause();
    }
}
Raymond Barlow
This would work - it's a shame java forces you to do this. I wonder if anyone has come up with a neat clean way of doing this?
Stuart Ervine
Yeah, Java can be noisy. Try Scala :)
Raymond Barlow