Rules Hub
Coding Rules Library
Create dedicated transformation methods for distinct contexts
Do not reuse specific data transformation methods for unrelated use cases; create dedicated methods to ensure decoupling.
Bad example
| 1 | class Article { |
| 2 | // Existing method specific to the Web Page |
| 3 | public asWebTeaser() { |
| 4 | return { |
| 5 | title: this.title, |
| 6 | image: this.image.getUrl('large') // Web needs large images |
| 7 | }; |
| 8 | } |
| 9 |
|
| 10 | // BAD: Piggybacking on the Web logic for a Widget |
| 11 | public asWidgetData() { |
| 12 | const webData = this.asWebTeaser(); |
| 13 | return { |
| 14 | headline: webData.title, |
| 15 | // Dependent on Web logic: if 'asWebTeaser' changes image size, Widget breaks |
| 16 | thumbnail: webData.image |
| 17 | }; |
| 18 | } |
| 19 | } |
Explanation (EN)
The `asWidgetData` method reuses `asWebTeaser`, creating a hidden dependency. If the web teaser logic changes (e.g., to return a different image size), the widget logic breaks or behaves incorrectly.
Objašnjenje (HR)
Metoda `asWidgetData` ponovno koristi `asWebTeaser`, stvarajući skrivenu ovisnost. Ako se logika za web teaser promijeni (npr. vrati drugačiju veličinu slike), widget će prestati ispravno raditi.
Good example
| 1 | class Article { |
| 2 | public asWebTeaser() { |
| 3 | return { |
| 4 | title: this.title, |
| 5 | image: this.image.getUrl('large') |
| 6 | }; |
| 7 | } |
| 8 |
|
| 9 | // GOOD: Dedicated transformation independent of Web logic |
| 10 | public asWidgetData() { |
| 11 | return { |
| 12 | headline: this.title, |
| 13 | // Widget explicitly requests what it needs |
| 14 | thumbnail: this.image.getUrl('thumbnail') |
| 15 | }; |
| 16 | } |
| 17 | } |
Explanation (EN)
The widget transformation is now self-contained. Changes to the web teaser logic will not affect the widget, preventing regression bugs and making the code easier to maintain.
Objašnjenje (HR)
Transformacija za widget je sada samostalna. Promjene u logici web teasera neće utjecati na widget, čime se sprječavaju regresijski bugovi i olakšava održavanje koda.
Notes (EN)
Avoid mapping one DTO to another (e.g., `WebDTO` -> `WidgetDTO`). Always derive specific DTOs directly from the source entity to maintain clear separation of concerns.
Bilješke (HR)
Izbjegavajte mapiranje jednog DTO-a u drugi (npr. `WebDTO` -> `WidgetDTO`). Uvijek izvodite specifične DTO-ove izravno iz izvornog entiteta kako biste zadržali jasno razdvajanje odgovornosti.