DEV Community

Cover image for Code Smell 45 - Not Polymorphic
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

1

Code Smell 45 - Not Polymorphic

Methods should be interchangeable if they do the same.

Problems

  • Missed Polymorphism

  • Coupling

  • IFs / Type check Polluting

  • Names coupled to types.

Solutions

  1. Rename methods after what they do.

  2. Favor polymorphism.

Sample Code

Wrong

<?
class array {
public function arraySort() {
}
}
class list {
public function listSort() {
}
}
class Stack {
public function stackSort() {
}
}

Right

<?
interface Sortable {
public function sort();
}
class Array implements Sortable {
public function sort() {
// Implementation of the sort() method for Array
}
}
class List implements Sortable {
public function sort() {
// Implementation of the sort() method for List
}
}
class Stack implements Sortable {
public function sort() {
// Implementation of the sort() method for Stack
}
}
view raw polymorphic.php hosted with ❤ by GitHub

Detection

This is a semantic mistake. We could add a warning for similar method names on Polymorphic classes.

Tags

  • Polymorphic

Conclusion

Naming is very important. We need to name after concepts and not after accidental types,

Relations

More info

what is in a name


If you have three pet dogs, give them names. If you have 10,000 head of cattle, don't bother. Nowadays, the idea of giving a name to every file on your computer is ridiculous.

David Gelernter

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more