Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[aspectj-users] Need help refactoring an input validation aspect

Hello everyone,

I'm just getting started with AspectJ, and have gotten stuck on extracting
some exception handling concerns. Can anyone point me in the right
direction?

Here's the original code:

  private static int promptForNumber(final BufferedReader stdin) {
    int inputSize = 0;

    boolean inputIsValid = false;
    while (!inputIsValid) {
      try {
        inputSize = Integer.parseInt(stdin.readLine());

        inputIsValid = true;
      } catch (IOException e) {
        System.err.println(
          "Encountered an I/O exception. Exiting.");
        System.exit(1);
      } catch (NumberFormatException e) {
        System.err.println(
          "Invalid number entered. (" + e.getMessage() + ")" );
      }
    }

    return inputSize;
  }

I extracted an IOException handling aspect, as follows:

  aspect IOExceptionHandling {
    declare soft : IOException
        : call(* *.*(..) throws IOException) &&
          within(Average);

    after() throwing(org.aspectj.lang.SoftException e)
        : execution(* Average.*(..)) && within(Average) {
      if (e.getWrappedThrowable() instanceof IOException) {
        System.err.println(
          "Encountered an I/O exception. Exiting.");
        System.exit(1);
      }
    }
  }

Now I'd like to extract the NumberFormatException handler, and (ideally)
the inputIsValid and while loop.

At the end, I was hoping to have something like:

  aspect IOExceptionHandling {
    ...
  }

  aspect InputValidation {
    ...
  }

  private static int promptForNumber(final BufferedReader stdin) {
    return Integer.parseInt(stdin.readLine());
  }

I might be asking for a lot, especially with the looping, but any help
would be appreciated. :)

Thanks,
David

_____________________________________________________________________
Dr. David Coppit                    Assistant Professor
coppit@xxxxxxxxx                    Department of Computer Science
http://www.cs.wm.edu/~coppit/       The College of William and Mary


Back to the top