DEV Community

Cover image for Code Smell 58 - Yo-yo Problem
Maxi Contieri
Maxi Contieri

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

2

Code Smell 58 - Yo-yo Problem

Searching for a concrete method implementation? Go back and forth, up and down.

TL;DR: Don't ab(use) hierarchies.

Problems

  • Deep Hierarchies

  • Subclassification for Code Reuse

  • Readability

  • Low Cohesion

  • High Coupling

Solutions

  1. Favor composition over inheritance.

  2. Refactor deep hierarchies.

Sample Code

Wrong

<?

abstract class Controller {

}

class BaseController extends Controller {

}

class SimpleController extends BaseController {

}

class ControllerBase extends SimpleController {

}

class LoggedController extends ControllerBase {

}

class RealController extends LoggedController {

}

Enter fullscreen mode Exit fullscreen mode

Right

<?

interface ControllerInterface {

}

abstract class Controller implements ControllerInterface {

}

final class LoggedControllerDecorator implements ControllerInterface {

}

final class RealController implements ControllerInterface {

}
Enter fullscreen mode Exit fullscreen mode

Detection

Any linter can check for suspects against a max depth threshold.

Tags

  • Hierarchy

Conclusion

Many novice programmers reuse code through hierarchies. This brings high coupled and low cohesive hierarchies.

Johnson and Foote established in their paper this was actually a good design recipe back in 1988. We have learned a lot from there.

We must refactor and flatten those classes.

Relations

More info

%[https://en.wikipedia.org/wiki/Yo-yo_problem]

c2

Hierarchies should be deep by Johnson and Foote


An error arises from treating object variables (instance variables) as if they were data attributes and then creating your hierarchy based on shared attributes. Always create hierarchies based on shared behaviors, side.

David West



This article is part of the CodeSmell Series.

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

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs