Skip to content

Latest commit

 

History

History
134 lines (85 loc) · 3.81 KB

File metadata and controls

134 lines (85 loc) · 3.81 KB

Code Smell 191 - Misplaced Responsibility

Code Smell 191 - Misplaced Responsibility

You have a clear responsibility for the wrong object

TL;DR: Don't be afraid to create or overload the proper objects.

Problems

Solutions

  1. Find actual behavior on the real objects using the MAPPER.

  2. Answer the question: 'Whose responsibility is..?'

Context

Finding responsible objects is a tough task.

If we talk to anybody outside the software world, they will tell us where we should place every responsibility.

Software engineers, on the contrary, tend to put behavior in strange places like helpers.

Sample Code

Wrong

function add(a, b) {
  return a + b;
}
// this is natural in many programming languages,
// but unnatural in real life

class GraphicEditor {
  constructor() {
    this.PI = 3.14;
    // You shouldn't define the constant here
  }

  pi() {
    return this.PI;
    // Not this object's responsibility
  }

  drawCircle(radius) {
    console.log("Drawing a circle with radius ${radius} " +
    "and circumference " + (2 * this.pi()) * radius");
  }
}

Right

class Integer {
  function add(adder) {
    return this + adder;
  }
}
// This won't compile in many programming languages
// But it is the right place for adding responsibility

class GraphicEditor {
  drawCircle(radius) {
    console.log("Drawing a circle with radius " + radius +
      " and circumference " + (2 * RealConstants.pi() * radius));    
  }
}
// PI's definition is RealConstants (or Number)'s responsibility

class RealConstants {
  pi() {
    return 3.14;
  }
}

Detection

[X] Manual

This is a semantic smell.

Exceptions

  • Some languages force you to add protocol in some objects and not on everyone (like primitive integers, Strings, Arrays, etc.)

Tags

  • Behavior

Conclusion

If you put the responsibilities in the proper object, you will surely find them in the same place.

Relations

Code Smell 22 - Helpers

Code Smell 63 - Feature Envy

More Info

Disclaimer

Code Smells are just my opinion.

Credits

Photo by Austin Neill on Unsplash


We know an object by what it does, by what services it can provide. That is to say, we know objects by their behaviors.

David West

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code