Controlling Visibility

Objects that are visible can be read or even changed through external code, which is a common cause of bugs and surprises. Restricting this visibility, encapsulating your code, is very common in object-oriented languages.

It all centers around the concept of a namespace in code—an area in the code that’s defined by a name. A class is a simple example: everything inside the class definition forms part of its namespace. By default, an object is visible in the whole namespace in which it’s defined: it’s public within that namespace, but not visible outside that namespace. We’ll talk about this in more detail in the next chapter about modules.

In Crystal, methods are public by default. That is, they’re usable inside and ...

Get Programming Crystal now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.