Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use aspects as a method for removing defensive checks from application logic?

Kind of a long title, but that is generally the question.

I want to know if you think its a good idea to do the following.

Instead of:

public void buyItem(int itemId, int buyerId) {
    if (itemId <= 0) {

        throw new IlleglArgumentException("itemId must be positive");
    }
    if (buyerId <= 0) {

        throw new IlleglArgumentException("buyerId must be positive");
    }
    // buy logic
}

I want to have something like:

@Defensive("isPositive(#itemId, #buyerId)")
public void buyItem(int itemId, int buyerId) {
    // buy logic
}

Do you think this is good/terrible/too fancy/too slow ? If you actually think its good I was thinking of using SpEL to implement it, does anyone have something better/lighter/faster in mind ?

Thanks,

like image 342
Simeon Avatar asked Feb 17 '12 13:02

Simeon


3 Answers

It's not necessarily a bad thing however your simple case can well be solved with exception statements (rather than assertions which I initially mentioned).

It seems you're introducing your own set of annotations which other developers in your project must accept and adapt to. However, once you've introduced annotations, it seems like a regular Proxy approach would be a better candidate to solve the issue.

To sum up: The problem you described can easily be solved using standard java alternatives, although in a more complex case it might be justified (consider e.g., @Secured in spring-security), especially if you're developing your own framework.

like image 153
Johan Sjöberg Avatar answered Nov 09 '22 19:11

Johan Sjöberg


I think it's

  • overengineering
  • breaking encapsulation, by relying on an external aspect (that could or couldn't be there) to maintain invariants of the object
  • confusing
  • not efficient
  • not adding any value

I like using Guava's Preconditions class for such checks. Moreover, such checks are part of the business logic, IMHO.

like image 27
JB Nizet Avatar answered Nov 09 '22 20:11

JB Nizet


I think you meant annotations, not aspects. Aspects are normally external to the code they advice. In any case, you can accomplish the sort of validations you highlighted in your post with JSR 303. Case in point:

public void buyItem(@Min(value = 1) int itemId, @Min(value = 1) int buyerId) {
    // buy logic
}

There are currently two well known implementations of JSR 303:

  • Hibernate Validator (reference implementation)
  • Apache Bean Validation
like image 26
Perception Avatar answered Nov 09 '22 18:11

Perception