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
Remove getters
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
}
}
Right
contract MessageContract {
string message = "Let's trade";
function sendMessage() public constant {
this.send(message);
}
}
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
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.