Promoting Solid Code Architecture in AEM
Adobe Experience Manager is not the simplest Web development framework to learn. Especially if you a Java developer with several years of previous experience in Spring or Java EE. As most other popular Java Web frameworks are based on the MVC pattern, you probably get surprised when you don’t find a controller class in your AEM project codebase.
On my first AEM project I also tried to MVC to AEM components. Of course, it didn’t work out quite well. The reason is that AEM is not based on MVC at all. Instead, it’s code architecture is more aligned with the MVVM pattern. There are no controllers in AEM as Apache Sling is taking care of the request mapping. The View (HTL/Sightly) binds to the methods provided by the View-Model (Sling Model). The View-Model calls the business logic implemented in dedicated components (OSGi Services).
During the next few years working with AEM I made notes on the good practices that I saw on different projects. These include basic things like a proper logging strategy, using injector-specific annotations or preferring request over administrative session. With time, this set of notes became our company coding guidelines. The coding guidelines define our aligned best practices, which are enforced trough architectural unit tests and static code analysis.
We used our company coding guidelines written in Confluence to create a set of custom SonarQube rules. These automated checks, together with pull-request decoration feature, helps us ensure that guidelines really do get applied on all projects. Naturally, we don’t want to repeat the same mistakes and we want our new-joiners to learn from our previous experience.
Highlights:
- In an enterprise architecture, AEM is usually in the presentation layer
- AEM doesn’t follow the MVC pattern, instead it more aligned with the MVVM
- Define a clear separation of concerns for your codebase, just because you can write all the code in the Sling Model, doesn’t mean you should
- OSGi Services promote reusability and testability, make sure to use them, a lot
- Documenting best practices makes sense and it pays off in the long run
- We don’t want to repeat the same mistakes on different projects
- Coding guidelines help boost quality and alignment between project teams
- Architectural tests and SonarQube rules can help ensure that guidelines actually get applied on projects
- Creating internal guidelines and assets requires a significant team effort, but it pays off in the long term