Kao
Kao

Reputation: 7364

Is it ok to make inter-type declaration of static method?

Consider following class with a static method:

public class Vector2D {      
    /* ... */
    public static Vector2D sum(Vector2D first, Vector2D second) {
        return new Vector2D(first.x + second.x, first.y + second.y);
    }
}

This method can be also added as an inter-type declaration in AspectJ:

public aspect Vector2DMath {
    public static Vector2D Vector2D.sum(Vector2D first, Vector2D second) {
        return new Vector2D(first.x + second.x, first.y + second.y);
    }
}

Which approach is more correct in terms of aspect-oriented programming?

Personally, I think that first approach is better (less code), but if so, then when inter-type declarations of static method can be useful?

Upvotes: 0

Views: 100

Answers (2)

kriegaex
kriegaex

Reputation: 67297

It does not make sense to compare apples and pears. There is no "better" or "worse" here, only situative decisions:

  • Whenever you have access to the source code of the class and the method you want to add implements a core concern, use OOP (edit: fix typo, earlier I had written "AOP").
  • If you do not have access to the source code and inheritance is not a good or even viable solution for implementing a core concern, use AOP as a workaround.
  • If you want to implement a cross-cutting concern across many classes or even throughout the whole system, always use AOP not matter whether you have source code access or not because that is where AOP helps you to write better and cleaner, more modular and more maintainable code.

Having said that and looking at your example, it seems that Vector2D.sum is pretty much addressing a core concern, so if you do not necessarily need AOP to work around the "no source code" problem, use OOP and just edit the class. In other cases the decision might be different. ITD for (non-)static methods is a useful AOP tool.

Edit: I forgot to mention that static methods are usually "bad" because it is hard to mock-test them. Not always, but often they are a bit old-school C-style. In this concrete example, why create a static method to add up two instances of the same class? Why not a regular sum method taking one argument?

Upvotes: 1

Adam Gent
Adam Gent

Reputation: 49085

IMO Static method ITDs are really only useful for code generation (spring roo is an example) akin to C# partial classes keeping the code generator code in a separate file from the developers code.

And yes the first approach is a myriad of ways better than the second approach.

Upvotes: 1

Related Questions