Public Interfaces in Ruby
Just like in business, when you have multiple entities working together; a contract is used to define their working relationship. In Object Oriented Programming, the contract is the interface. Let’s see how we can design good interfaces in Ruby and identify the bad ones.
Why good interfacing matters?
An application consists of many objects and those objects need to communicate to offer functionality. Over time new features are introduced, new objects added, and existing objects are modified.
It is not easy to introduce or modify objects with poor interfacing. Changes become difficult when others are dependent on the thing you are changing. It is inevitable that things will change and dependencies will exist. How can we reduce the pain when changes are required to the already used bits? Better interfacing.
What makes a good interface?
The interface for a Ruby class are the public methods. These are the parts that other classes may use. So the first step to a good interface is only make a method public if it is unlikely to change. The code more likely to change should reside in the private section. A public method can reference a private serving as a layer of protection for the interface. The interface methods define what the class does and the private methods will help serve the cause.
- Public methods should be less likely to change
- The collection of public methods satisfy single responsibility
- Use a private method for internal logic
- Code that is more likely to change lives in a private method
A poor interface will lead to an unmaintainable codebase because change will happen and every change impacts each dependency. A good interface is not hard to achieve yet very easy to overlook. Put care in how you design an interface because developers that come after you will assume you did.
Did you like this article? Check out these too.
Found this useful? Know how it can be improved? Get in touch and share your thoughts at