Motivations
Motivations
Aspect-Oriented Programming (AOP) is a programming paradigm that enhances the modularization and separation of concerns of the code.
Aspect Oriented Programming
With programming paradigms like Object Oriented Programming, concerns such as logging, security, and transaction management are scattered throughout the codebase, leading to code duplication, tangled dependencies, and decreased maintainability. AOP addresses this problem by introducing a separate module called an "aspect" that encapsulates the cross-cutting concerns.
class Foo {
method1() {
try { /* Code for method1 */ }
catch (error) { this.logError(error); /* Logging error here */ }
}
}
class Bar {
method2() {
try { /* Code for method2 */ }
catch (error) { this.logError(error); /* Logging error here */ }
}
}
class Baz {
method3() {
try { /* Code for method3 */ }
catch (error) { this.logError(error); /* Logging error here */ }
}
}
class Foo {
@LogErrors
method1() {
// Code for method1
}
}
class Bar {
@LogErrors
method2() {
// Code for method2
}
}
class Baz {
@LogErrors
method3() {
// Code for method3
}
}
A lesson learned from Java
AOP has gained significant popularity in the Java ecosystem, primarily due to frameworks like AspectJ, which have revolutionized the way we develop applications in Java.
AOP has played a pivotal role in shaping some of the most widely-used Java frameworks, such as Spring and Hibernate. By providing a consistent syntax and independent tooling, it has enabled the creation of reusable behaviors that can seamlessly integrate with different frameworks.
In contrast, JavaScript lacks this kind of interoperability, which often poses challenges when writing code that needs to be portable across various JavaScript environments, such as React, Angular, Node.js, and the browser.
In an attempt to fill this gap, I developed AspectJS with the aim of bringing the power and flexibility of AOP to the JavaScript ecosystem.
More than ES decorators
Some JavaScript frameworks, such as Angular, Nest.js or TypeORM already utilize ECMAScript Decorators to enhance classes and methods with additional behavior, similar to the capabilities of Aspect-Oriented Programming (AOP). However, it is important to acknowledge that ES decorators have certain limitations:
- They are hard to write due to their complex syntax
- They encapsulate behavior within themselves, which limits their extensibility and portability across different platforms
ECMAScript decorators look like Java annotations. However, Java annotations are just interfaces while ECMAScript decorators come with their own implementation.
AspectJS introduces the concept of annotations for Javascript. Simply put, an AspectJS annotation is an ECMAScript decorator with no implementation. The actual behavior is added later through the introduction of Aspects.