What is the difference between public and private methods?

. 1 min read

Beginners ask the hardest questions. Can you answer this week's question without using any technical jargon?

What is the difference between public and private methods?

My favourite answer is from Sandi Metz's beautiful book, Practical Object-Orientated Design in Ruby.

Imagine a restaurant kitchen. Customers order off a menu. These orders come into the kitchen through a little window (the one with the bell beside it, “order up!”) and the food eventually comes out. To a naïve imagination it may seem as if the kitchen is filled with magical plates of food that are waiting, pining to be ordered, but in reality the kitchen is full of people, food, and frenzied activity, and each order triggers a new construction and assembly process.

The kitchen does many things, but does not, thankfully, expose them all to its customers. It has a public interface that customers are expected to use; the menu. Within the kitchen many things happen, many other messages get passed, but these messages are private and thus invisible to customers. Even though they may have ordered it, customers are not welcome to come in and stir the soup.

This distinction between public and private exists because it is the most effective way to do business. If customers directed the cooking, they would have to be re-educated whenever the kitchen ran low on an ingredient and needed to make a substitution. Using a menu avoids this problem by letting each customer ask for what they want without knowing anything about how the kitchen makes it.

Photo by Josh Wilburne on Unsplash.