Cross cutting concern example
Asked Answered
M

6

179

What is a good example of a cross-cutting concern? The medical record example on the wikipedia page seems incomplete to me.

Specifically from this example, why would logging lead to code duplication (scattering)? (Besides simple calls such as log("....") everywhere, which doesn't seem like a big deal).

What is the difference between a core concern and a cross-cutting concern?

My end goal is to get a better understanding of AOP.

Mabel answered 16/5, 2014 at 16:45 Comment(0)
C
332

Before understanding the Crosscutting Concern, we have to understand the Concern.

A Concern is a term that refers to a part of the system divided on the basis of the functionality.

There are two types of concerns:

  1. The concerns representing single and specific functionality for primary requirements are known as core concerns.
    OR
    Primary functionality of the system is known as core concerns.
    For example: Business logic
  2. The concerns representing functionalities for secondary requirements are referred to as crosscutting concerns or system-wide concerns.
    OR
    The crosscutting concern is a concern which is applicable throughout the application and it affects the entire application.
    For example: logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.

Courtesy

enter image description here

This figure represents a typical application that is broken down into modules. Each module’s main concern is to provide services for its particular domain. However, each of these modules also requires similar ancillary functionalities, such as security logging and transaction management. An example of crosscutting concerns is "logging," which is frequently used in distributed applications to aid debugging by tracing method calls. Suppose we do logging at both the beginning and the end of each function body. This will result in crosscutting all classes that have at least one function.

(Courtesy)

Cowart answered 11/9, 2014 at 5:26 Comment(3)
"The crosscutting concern is a concern which is applicable throughout the application" ➤ Not sure about this since transaction management is not applicable 'throughout' the application but is still a cross-cutting concern. And the picture tells me nothing to be honest, it is only confusing..Latria
Good explanation, but I have a bit issue with the picture where we call these concerns, cross-cutting not cross-cut-ed concerns and it would be better I think to cut other concerns with cross-cutting concerns, not another way around. Like Aspect-oriented developmentPhilina
still the answer doesn't explains the problem with simply using something like Log4j and logging like LogManager.getLogger().info(ModuleName, msg)Gastronomy
F
63

I think the single best example of a cross-cutting concern is transactional behavior. Having to put try-catch blocks with commit and rollback calls in all your service methods would be repellent, for instance. Annotating the methods with a marker that AOP can use to encapsulate them with the desired transactional behavior is a big win.

Another good candidate as an example of a cross-cutting concern is authorization. Annotating a service method with a marker that tells who can call it, and letting some AOP advice decide whether to allow the method call or not, can be preferable to handling that in service method code.

Implementing logging with AOP advice could be a way to get more flexibility, so that you can change what gets logged by changing a joinpoint. In practice I don't see projects doing that very often. Typically using a library like log4j that lets you filter by logging-level and category, at runtime if you need to, works out well enough.

A core concern is a reason that the application exists, the business logic that the application automates. If you have a logistics application that handles shipping freight, figuring out how much cargo you can pack on a truck or what's the best route for the truck to take to drop off its deliveries might be core concerns. Cross-cutting concerns are typically implementation details that need to be kept separate from business logic.

Fillander answered 16/5, 2014 at 17:3 Comment(7)
So even though transactional behavior really only exists in the data access layer, because the try-catch blocks are duplicated over lots of the methods, it is considered cross-cutting. My original perceptions was that cross-cutting meant the code spanned multiple layers of the application.Mabel
@jlars62: cross-cutting means it goes at right-angles to the features.Fillander
@jlars62: by at right-angles i mean: think of a feature as a stack of layers. a cross-cutting concern may apply to only one layer, but it is common to all the features.Fillander
@NathanHughes Authorization is a good example. I just refactored my app to put all authorization code in a cross-cutting architecture and it worked wonders to clean up a lot of code. I consider the domain like a house. If you have the key to get in, you can do whatever you want in there (you are presumed an owner). But you wouldn't lock every door in the house and demand a key entry. You're either in or you aren't.Eurus
"Transactional behavior" may be common to many features but this will not be "cross cutting" because it is not "crossing" the layers. The reason, for example, logging is a cross cutting concern is because I may want to log in the presentation layer, business layer, data layer etc.Josefina
So, multi-tenancy / role-based permission filtering / scoping would also be a cross-cutting concern, as a sub-set of security, right?Pusey
@ortonomy: maybe. hard to make a list everybody agrees on, as you can see from the other comments :-)Fillander
C
15

In addition to the accepted answer I want to mention another example for a cross-cutting concern: remoting. Say I just want to call other components in my ecosystem locally as if they were running in process. Maybe in some cases they even do. But now I want to run my services distributed in a cloud or cluster. Why should I care about this aspect as an application developer? An aspect could take care of finding out who to call and and how, serialising transmitted data if necessary and making a remote call. If everything was running in process the aspect would just forward the local call. On the callee side the aspect would deserialise the data, make the local call and return the result.

Now let me tell you a little story about "trivial" things like log output: Just a few weeks ago I refactored a complex, but not too big code base (around 250K lines of code) for a client. In a few hundred classes one kind of logging framework was used, in another few hundred another. Then there were several thousand lines of System.out.println(*) where there really should have been log output. So I ended up with fixing thousands of lines of code scattered throughout the code base. Fortunately I could use some clever tricks in IntelliJ IDEA (structural search & replace) in order to speed up the whole action, but boy don't you think it was trivial! Sure, strongly context-dependent debug logging will always occur within a method body, but many important types of logging such as tracing method calls (even hierarchically with a nicely indented output), logging both handled or unhandled exceptions, user auditing (logging calls to restricted methods based on user roles) and so forth can easily be implemented in aspects without them polluting the source code. The everyday application developer does not need to think about it or even see the logger calls scattered across the code base. Someone is responsible for keeping the aspect up to date and can even switch the logging strategy or the whole logging framework centrally in one place.

I can come up with similar explanations for other cross-cutting concerns. Keeping code clean and free from scattering and tangling IMO is a matter of professionalism, not anything optional. Last but not least it keeps the code readable, maintainable, refactorable. Amen.

Cluny answered 17/5, 2014 at 9:2 Comment(2)
Could I ask How U isolated the scattered logging in the codebase?Rudderhead
That is a very general question. So my general answer is: by identifying logging patterns, then factoring out each of them into an aspect (or an advice of an existing aspect) one by one, leaving only the ones behind which defy matching a usage pattern. Those are fewer than you might think at first glance, because this kind of refactoring also makes you reconsider your logging strategy as a whole, e.g. clean-coding class and method names in order to make generic logging more readable, resulting in fewer custom log messages.Cluny
F
3

i found this very clear from Wikipedia:

if writing an application for handling medical records, the indexing of such records is a core concern, while logging a history of changes to the record database or user database, or an authentication system, would be cross-cutting concerns since they interact with more parts of the program.

Examples of concerns that tend to be cross-cutting include:

Business rules

Caching

Code mobility

Data validation

Domain-specific optimizations

Error detection and correction

Internationalization and localization which includes Language localisation

Information security

Logging

Memory management

Monitoring

Persistence

Product features

Real-time constraints

Synchronization

Transaction processing

Context-sensitive help

Farl answered 20/12, 2020 at 10:39 Comment(0)
W
1

Cross Cutting Concerns are the scenarios which should always be present irrespective of the type of application.

For example Logging, Security, Performance Profiling, Localization, Accessibility, Transaction etc. Irrespective of the Software we are building logging is needed(otherwise how some one will debug or get some relevant information from prod data). Security(authentication/authorization etc.) is needed where only authentic user can enter into the application with right set of privileges. We need to know how your application performs then we need to do profiling. In case application is used by international users(with their own localized language), then we need to support the same in application. Accessibility is usability cases for disabled people to use our application.

Now Irrespective of whether our application is desktop based, web based etc. if it needs to be used by End users across geography in production environment then cross cuts are needed. Till now I haven't said anything about what application is all about etc, but given the list of concerns which should be addressed before releasing it to end users in production environment. and that's all about cross cut concerns(which needs to be handled by all applications/methods/classes i.e at various levels).

Womera answered 2/2, 2020 at 13:42 Comment(0)
S
0

Adding my grain of salt and coming from the Android mobile perspective, I will say that cross-cutting concern can be defined for example with Analytics. You dont need the Analytics to complete some module behavior, and such, making that module to create or instantiate such Analytics will lead to a code duplication.

So having an injector that deals with that dependency that can be shared all over your modules, will resolve the problem.

A core concern will be the Single responsibility of such module and the cross-concern will be the Analytics library that will be used in all over the place.

Scraperboard answered 26/1 at 15:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.