Access modifiers have long been seen as essential to safe and clean code. But they’re ultimately a low-level mechanism for expressing high-level ideas.Access modifiers have long been seen as essential to safe and clean code. But they’re ultimately a low-level mechanism for expressing high-level ideas.

Rethinking Encapsulation: From Private to Public by Design

2025/10/16 13:15
6분 읽기
이 콘텐츠에 대한 의견이나 우려 사항이 있으시면 crypto.news@mexc.com으로 연락주시기 바랍니다

This article is part of a broader discussion in my book Safe by Design: Explorations in Software Architecture and Expressiveness. If you like it, you might enjoy the full read for free on GitHub.

Introduction: Rethinking Access Control

Encapsulation is one of the core pillars of object-oriented programming. It is commonly introduced through the use of access modifiers — private, protected, public, and so on — which restrict visibility of internal implementation details. Most popular object-oriented languages provide access modifiers as the default tool for enforcing encapsulation.

While this approach is effective, it tends to obscure a deeper and arguably more powerful mechanism: the use of explicit interfaces or protocols. Instead of relying on visibility constraints embedded in the language syntax, we can define behavioral contracts directly and intentionally — and often with greater precision and flexibility.

This article offers an alternative perspective on access control, suggesting that access modifiers are, in many cases, just a shorthand for declaring implicit interfaces. We’ll explore how switching from implicit to explicit contracts can improve modularity, enhance design clarity, and even allow us to imagine programming languages that work without private or protected at all.

Access Modifiers as Implicit Interfaces

Access modifiers give us fine-grained control over which parts of a class are visible to the outside world. A private method is hidden from everyone except the class itself. A protected method is visible to subclasses. Package-private (in languages like Java) further narrows or expands visibility based on the module boundary. These modifiers form a visibility matrix, controlling how internal details are exposed.

But here’s the key observation: each combination of access levels effectively defines a contract — a set of methods that a particular group of clients is allowed to use. This is conceptually identical to an interface.

For example, when a class exposes one method as public and keeps the rest private, it’s silently declaring, “This is the only thing you’re allowed to call.” The contract is there — it’s just invisible.

Access modifiers are, in this sense, a mechanism for declaring implicit interfaces. The problem is that they are invisible to tooling and to readers. They offer no way to reason about multiple views of the same object — something explicit interfaces handle much better.

The Power of Explicit Interfaces

Interfaces (or protocols, depending on the language) let us define clearly what capabilities an object exposes — and to whom. Instead of burying access control inside the implementation using private or protected, we can expose different behaviors through multiple public interfaces. This makes the contract visible, composable, and testable.

Interfaces offer several advantages:

  • Clarity: Clients only see the functionality they are supposed to use. No hidden methods leaking through reflection or subclassing.
  • Flexibility: Different clients can interact with the same object through different interfaces, depending on context.
  • Polymorphism: Explicit interfaces enable runtime substitution, mocking, and dependency inversion — all core ideas in modern software design.
  • Encapsulation without obscurity: By expressing visibility through interfaces rather than modifiers, we separate what is exposed from how it’s implemented.

In effect, interfaces give us a more declarative, higher-level alternative to access modifiers. And unlike modifiers, interfaces scale well in large codebases, across modules, teams, and versions.

📘 If you’re enjoying this so far, there’s a lot more in the book — same tone, just deeper. It’s right here if you want to peek.

A Concrete Example

Let’s take a simple class that uses traditional access modifiers to hide internal details:

public class ConsistentObject {     public void methodA() { /* ... */ }     protected void methodB() { /* ... */ }     void methodC() { /* ... */ } // package-private     private void methodD() { /* ... */ } } 

This class defines different visibility levels using Java’s modifiers. But what if we rewrote the same intent using interfaces?

public interface IPublicConsistentObject {     void methodA(); } public interface IProtectedConsistentObject extends IPublicConsistentObject {     void methodB(); } public interface IDefaultConsistentObject extends IProtectedConsistentObject {     void methodC(); } class ConsistentObject implements IDefaultConsistentObject {     public void methodA() { /* ... */ }     public void methodB() { /* ... */ }     public void methodC() { /* ... */ }     public void methodD() { /* ... */ } } 

Here, each interface builds on the previous one, modeling increasingly privileged access. The important difference is that now the contracts are explicit and reusable. Instead of relying on compiler-enforced visibility, we guide client interaction by choosing which interface to provide.

A consumer of this class might only receive a reference of type IPublicConsistentObject, and therefore would only see methodA() — even though the underlying object knows how to do more.

This model makes dependencies more honest and design more modular.

The Limitation: Constructors and Instantiation

There’s one area where access modifiers still feel necessary: controlling object creation.

Constructors can’t be abstracted as easily as methods. You can’t define a constructor in an interface, and you can’t delegate instantiation to a consumer the same way you do method calls. That’s why private constructors (and protected ones, in some cases) remain common — especially when enforcing factory patterns, singletons, or internal lifecycle rules.

But even this limitation is manageable.

If we embrace factory functions or dependency injection, we decouple creation from usage:

interface PublicAPI {     fun doStuff() } private class InternalImplementation : PublicAPI {     override fun doStuff() { /* ... */ } } fun createInstance(): PublicAPI {     return InternalImplementation() } 

In this model, the internal class remains private, and the only way to obtain it is through the createInstance() factory. Clients never need to know — or care — how it was constructed.

This approach makes the object lifecycle part of the module’s explicit API. It also aligns naturally with principles like Inversion of Control, and is widely used in dependency-injection frameworks.

In short, we don’t need private constructors. We just need to move the responsibility of creation one level higher.

Conclusion: In Defense of Public Everything

Access modifiers have long been seen as essential to safe and clean code. But they’re ultimately a low-level mechanism for expressing high-level ideas — contracts, roles, and boundaries.

By shifting from implicit contracts enforced through visibility, to explicit contracts expressed via interfaces and factory functions, we unlock several benefits:

  • Clearer APIs
  • Greater flexibility across modules
  • Better separation of concerns
  • Easier testing, mocking, and substitution

This doesn’t mean private and protected are inherently bad. But they’re a shortcut — a legacy of language design choices made before interface-based composition became mainstream.

We can imagine a language that omits access modifiers entirely and instead relies on structured APIs to express visibility. In that world, encapsulation would still be possible — arguably even more robust — because everything would be explicit, composable, and visible by design.

And maybe that’s a world worth building toward.

If you enjoyed this article, you might like my book Safe by Design: Explorations in Software Architecture and Expressiveness. It dives deeper into topics like this one — contracts, type safety, architectural clarity, and the philosophy behind better code.

👉 Check it out on GitHub

시장 기회
PUBLIC 로고
PUBLIC 가격(PUBLIC)
$0.01553
$0.01553$0.01553
+0.12%
USD
PUBLIC (PUBLIC) 실시간 가격 차트
면책 조항: 본 사이트에 재게시된 글들은 공개 플랫폼에서 가져온 것으로 정보 제공 목적으로만 제공됩니다. 이는 반드시 MEXC의 견해를 반영하는 것은 아닙니다. 모든 권리는 원저자에게 있습니다. 제3자의 권리를 침해하는 콘텐츠가 있다고 판단될 경우, crypto.news@mexc.com으로 연락하여 삭제 요청을 해주시기 바랍니다. MEXC는 콘텐츠의 정확성, 완전성 또는 시의적절성에 대해 어떠한 보증도 하지 않으며, 제공된 정보에 기반하여 취해진 어떠한 조치에 대해서도 책임을 지지 않습니다. 본 콘텐츠는 금융, 법률 또는 기타 전문적인 조언을 구성하지 않으며, MEXC의 추천이나 보증으로 간주되어서는 안 됩니다.

USD1 Genesis: 0 Fees + 12% APR

USD1 Genesis: 0 Fees + 12% APRUSD1 Genesis: 0 Fees + 12% APR

New users: stake for up to 600% APR. Limited time!