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,
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.
I think it's
I like using Guava's Preconditions class for such checks. Moreover, such checks are part of the business logic, IMHO.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With