cover-img

Code Smell 68 - Getters

How to avoid getters

6 May, 2023

5

5

0

TL;DR: How to avoid getters

Getting things is widespread and safe. But it is a very bad practice.

Problems

  • Naming
  • Information Hiding
  • Coupling
  • Encapsulation Violation
  • Mutability
  • Anemic Models

Solutions

  1. Avoid Getters
  2. Use domain names instead
  3. Protect your implementation decisions.

Sample Code

Wrong

<?php

final class Window {
public $width;
public $height;
public $children;

public function getWidth() {
return $this->width;
}

public function getArea() {
return $this->width * $this->height;
}

public function getChildren() {
return $this->children;
}
}

Right

<?php

final class Window {
private $width;
private $height;
private $children;

public function width() {
return $this->width;
}

public function area() {
return $this->height * $this->width;
}

public function addChildren($aChild) {
// Do not expose internal attributes
return $this->children[] = $aChild;
}
}

Detection

Getters coincide in certain scenarios with a true responsibility. It will be reasonable for a window to return its color and it may accidentally store it as color. so a color() method returning the attribute color might be a good solution.

getColor() breaks bijection since it is implementative and has no real counterpart on our mappers.

Most linters can warn us if they detect anemic models with getters and setters.

Tags

  • Information Hiding

Conclusion

Getters and Setters are a bad established practice. Instead of focusing on object behavior (essential), we are desperate to know object guts (accidental) and violate their implementation.

Relations

Code Smell 28 - Setters

Code Smell 01 - Anemic Models

Code Smell 64 - Inappropriate Intimacy

More Info

Nude Models - Part II: Getters

Credits

Photo by Vidar Nordli-Mathisen on Unsplash


The value of a prototype is in the education it gives you, not in the code itself.

Alan Cooper


Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

5

5

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.