60 msdn magazine
A well-architected application has separate layers so
diff erent concerns don’t interact more than needed. Imagine you’re
designing a loosely coupled and maintainable application, but in
the middle of the development, you see some requirements that
might not fi t well in the architecture, such as:
- Th e application must have an authentication system, used
before any query or update.
- Th e data must be validated before it’s written to the database.
- Th e application must have auditing and logging for
sensible operations.
- Th e application must maintain a debugging log to check
if operations are OK.
- Some operations must have their performance measured
to see if they’re in the desired range.
Any of these requirements need a lot of work and, more than that,
code duplication. You have to add the same code in many parts of
the system, which goes against the “don’t repeat yourself ” (DRY)
principle and makes maintenance more diffi cult. Any requirement
change causes a massive change in the program. When I have to
add something like that in my applications, I think, “Why can’t the
compiler add this repeated code in multiple places for me?” or, “I
wish I had some option to ‘Add logging to this method.’”
Th e good news is that something like that does exist: aspect-oriented
programming (AOP). It separates general code from aspects that cross
the boundaries of an object or a layer. For example, the application log
isn’t tied to any application layer. It applies to the whole program and
should be present everywhere. Th at’s called a crosscutting concern.
AOP is, according to Wikipedia, “a programming paradigm
that aims to increase modularity by allowing the separation of
crosscutting concerns.” It deals with functionality that occurs in
multiple parts of the system and separates it from the core of the
application, thus improving separation of concerns while avoiding
duplication of code and coupling.
ASPECT-ORIENTED PROGRAMMING
Aspect-Oriented
Programming with the
RealProxy Class
Bruno Sonnino
This article discusses:
- The basics of aspect-oriented programming (AOP)
- The Decorator design pattern
- Using the RealProxy class to create a dynamic proxy
- How to fi lter aspects
- The differences between RealProxy and PostSharp
Technologies discussed:
Microsoft .NET Framework, Aspect-Oriented Programming
public class Repository<T> : IRepository<T>
{
public void Add(T entity)
{
Console.WriteLine("Adding {0}", entity);
}
public void Delete(T entity)
{
Console.WriteLine("Deleting {0}", entity);
}
public void Update(T entity)
{
Console.WriteLine("Updating {0}", entity);
}
public IEnumerable<T> GetAll()
{
Console.WriteLine("Getting entities");
return null;
}
public T GetById(int id)
{
Console.WriteLine("Getting entity {0}", id);
return default(T);
}
}
Figure 1 The Repository