开发者

Question safe withdraw/deposit using AspectJ

I have question regarding making a bankAccount class implement safe withdraw/deposit function. So far it will print log when you make a withdraw or deposit to the bankAccount class. Anyway my question is how to implement the safety e.g. you cannot withdraw mor开发者_运维知识库e money than what you have currently in your bankAccount. If I'm not allowed to implement that safety in the bankAccount class, and want to implement it to an AspectJ.

I have the following now. As can be seen the withdraw is done regardless if the if-statement is true or false. Therefore I had to in the else statement deposit back the amount of money, so it would not turn negative. Can this be done in some nicer way possibly?

pointcut checking(BankAccount ba, float x): 
    call(* BankAccount.withdraw(..)) && target(ba) && args(x);                                                                                                   



before(BankAccount b, float x) : checking(b, x) {
    if(b.getBalance() >= x) {
        System.out.println("Account changing. $" + x + " withdrawn..."); 

    } else {               
        System.out.println("Account does not have. $" + x + " to withdrawn...");
        b.deposit(x);
    }

}


I'd say this would be better handled by an around advice, which can prevent proceeding to the normal invocation and substitute some other action instead if the transaction shouldn't be allowed.

The code for the around advice should be basically similar to what you wrote for before, except in the if block you'd have to call proceed to continue into the normal execution, and in the else block you'd no longer need the call to deposit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜