RULE-604 Avoid repeated ObjectMapper creation#453
Conversation
rducasse
left a comment
There was a problem hiding this comment.
I agree with the rule in principle — ObjectMapper is indeed costly to instantiate repeatedly.
But before we can approve, one blocking request:
The asciidoc needs to document and source the environmental relevance. The current version explains what to do but not why it matters. Please add a == Why this matters or == References section that includes at least one external reference (e.g. the Jackson documentation explicitly recommending reuse, or a benchmark comparing shared vs. per-call instantiation).
A few smaller points:
- Exceptions: document the cases that should not be flagged (constructor assigning to a field, Spring
@Beanmethod, static initializer) - Detection scope: clarify whether the rule covers only ObjectMapper or also sub-classes (XmlMapper, CsvMapper, JsonMapper)
- Thread-safety: worth a sentence — ObjectMapper is thread-safe after configuration, which is the key reason sharing is safe
There was a problem hiding this comment.
Pull request overview
Adds the GCI604 rule specification to discourage creating a new Jackson ObjectMapper for every serialization/deserialization, promoting reuse for better performance and reduced allocation.
Changes:
- Added rule documentation with non-compliant/compliant Java examples (including a Spring injection example).
- Added rule metadata (
GCI604.json) defining title, severity, remediation cost, and tags.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| src/main/rules/GCI604/java/GCI604.asciidoc | Documents the rationale and provides non-compliant/compliant Java examples for reusing ObjectMapper. |
| src/main/rules/GCI604/GCI604.json | Defines the rule’s metadata (title, type, severity, remediation, tags). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| String toJson(Object user) throws Exception { | ||
| ObjectMapper mapper = new ObjectMapper(); // Noncompliant | ||
| return mapper.writeValueAsString(user); |
| String toJson(Object user) throws Exception { | ||
| return OBJECT_MAPPER.writeValueAsString(user); | ||
| } |
| String toJson(Object user) throws Exception { | ||
| return objectMapper.writeValueAsString(user); | ||
| } |
Avoid repeated ObjectMapper creation
Groupe Les Shreks des dépendances moisies( CGI)