Public Interfaces in Ruby
In business, when multiple entities collaborate, a contract will define their working relationship. In Object-Oriented Programming, the contract is the interface. Let’s see how we can design a good interface in Ruby and identify the bad ones.
Why does good interfacing matter?
An application consists of many objects. Those objects need to communicate to offer functionality. Over time we introduce new features, add things, and make modifications.
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. Things will inevitably change, and dependencies will exist. How can we reduce the pain when changes happen? Better interfacing.
What makes a good interface?
The interface is the collection of public methods. These are the parts that other classes may use. The first step to a good interface is to limit it to things that are 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? Have a suggestion? Get in touch at