Talk:Aspect oriented programming: Difference between revisions

small tweaks to task
(small tweaks to task)
Line 26:
=== A Possible Task ===
 
Task: Write an example of a factorial function with a logging feature which may be toggled on or off, preferably at compile time, and if possible without altering the original code.
Task: Write some code which provides an optional feature which may be enabled or disabled as the developer desires, at as high a level as possible in the language. If possible, keep the feature code separate, and avoid polluting the original code. The task could be to write a factorial function which logs each iteration it takes only when the LOGGING feature is enabled.
 
Output of factorial(4) when LOGGING is enabled:
Line 34:
2 x 1!</lang>
 
A runtime solution for Javascript which avoidsallows us to enable logging at runtime, without polluting the original code:
 
<lang javascript>
###factorial.js###
function factorial(n) {
return ( n==1 ? 1 : n*factorial(n-1) );
}
 
###LOGGING.js###
// Overwrite existing global factorial function with a logging version
Line 45 ⟶ 50:
};
 
###LOGGING_generalised.js###
// This couldcan be generalised into a decorator that can add logging to any given function.
function addLoggingTo(parent,name) {
var oldFn = parent[name];
Line 56 ⟶ 62:
</lang>
 
This might be considered preferable to #ifdefsa whichbunch getsof if-statements mixed into the code. The aspect is separate from the original source.
 
Some general fallbacks exist for a wide range of languages which have no higher-level support. A simple if (LOGGING) check should always work. Some applications mutate existing code at runtime using a plugin or module framework, in which case the LOGGING feature could be a plugin that may or may not be present to consume log events.
Anonymous user