Code Smell 103 - Double Encapsulation

mcsee

Maxi Contieri

Posted on November 19, 2021

Code Smell 103 - Double Encapsulation

Calling our own accessor methods might seem a good encapsulation idea. But it is not.

TL;DR: Don't use setters and getters, even for private use

Problems

  • Setters

  • Getters

  • Exposing private attributes

Solutions

  1. Remove setters

  2. Remove getters

  3. Protect your attributes

Context

Using double encapsulation was a standard procedure in the 90s.

We wanted to hide implementation details even for private use.

This was hiding another smell when too many functions relies on data structure and accidental implementation.

For example, we can change an object internal representation and rely on its external protocol.

Cost/benefit is not worth it.

Sample Code

Wrong

contract MessageContract {
    string message = "Let's trade";

    function getMessage() public constant returns(string) {
        return message;
    }

    function setMessage(string newMessage) public {
        message = newMessage;
    }

    function sendMessage() public constant {
        this.send(this.getMessage());
        //We can access property but make a self call instead
    }
}
Enter fullscreen mode Exit fullscreen mode

Right

contract MessageContract {
    string message = "Let's trade";

    function sendMessage() public constant {
        this.send(message);
    }
}
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Semiautomatic

We can infer getters and setters and check if they are invoked from the same object.

Tags

  • Encapsulation

Conclusion

Double encapsulation was a trendy idea to protect accidental implementation, but it exposed more than protected.

Relations

More Info

Credits

Photo by Ray Hennessy on Unsplash


Encapsulate the concept that varies.

Erich Gamma


This article is part of the CodeSmell Series.

💖 💪 🙅 🚩
mcsee
Maxi Contieri

Posted on November 19, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related