Aspect oriented programming: Difference between revisions

From Rosetta Code
Content added Content deleted
(Encapsulating features and tracking features spread throughout code)
 
(added cross-cutting concerns)
Line 7: Line 7:
=={{header|Java}}==
=={{header|Java}}==


Java has an aspect oriented programming library called AspectJ. Aspects can create entry and exit intercepts on normal methods.
Java has an aspect oriented programming library called AspectJ. Aspects can create entry and exit intercepts on normal methods. In aspect language, features are called cross-cutting concerns.


=={{header|C}}==
=={{header|C}}==

Revision as of 12:38, 13 June 2011

One goal of aspect oriented programming is to keep all the code relating to a single feature in one module of code.

There are a variety of ways to achieve this with object-oriented programming and functional programming, including inheritance, decorators and configuration trees.

When it is not possible to group a feature's code in one place, there can be ways to at least mark and track the lines of code.

Java

Java has an aspect oriented programming library called AspectJ. Aspects can create entry and exit intercepts on normal methods. In aspect language, features are called cross-cutting concerns.

C

It can be difficult to modularise features in C, if the feature affects different parts of the program.

Using a define var

When a new feature introduces code scattered throughout the program, we can relate all the code together using a define and ifdefs.

<lang c>

  1. define MY_NEW_FEATURE_ENABLED

...

  1. ifdef MY_NEW_FEATURE_ENABLED
 my_new_feature();
  1. endif

...

  1. ifdef MY_NEW_FEATURE_ENABLED
 close_my_new_feature();
  1. endif

</lang>

As well as allowing us to enable or disable the feature at compile time, this also provides a way to find all the relevant code easily, by searching for the variable name.

The same approach using a boolean instead of a define variable can be found in many languages, to allow a feature to be toggled on or off at runtime.

Using a macro

An alternative macro method can be used in C, which is shorter for one-liners.

<lang c> /* Enable logging: */ /* #define LOG(x); printf("%s\n",x); */ /* Disable logging: */

  1. define LOG(x);

...

LOG(blah);

... </lang>

Using function pointers

Although C is not strictly a functional programming language, it is possible to call a procedure from a pointer, and by re-assigning the pointer force a different procedure to be called. I forget the code for this but it may involve (void *) and &.

JavaScript

Bemson's Flow library introduces an aspect-like framework for Javascript.

New Page Notes

I may have described a feature-oriented programming paradigm, or something related to modular programming. If so please feel free to rename or refactor the page!