Introduce `private(this)` Access Modifier

Peter peterP at gmail.com
Fri Jul 4 09:26:30 UTC 2025


DIP: xxxx
Title: Introduce `private(this)` Access Modifier
Author: [Your Name]
Status: Draft
Created: 2025-07-04

## Abstract

This DIP proposes adding a new access modifier, `private(this)`, 
that applies only to class and struct members.
Outside the defining module it behaves identically to `private`.
Within the module, however, it restricts access to the scope of 
the declaring type, preventing any other code in the same module 
from touching it.

## Rationale

Currently, D’s `private` grants access to all code in the same 
module.
While that can simplify internal communication, it undermines 
encapsulation by allowing unrelated types
and functions in the same module to directly manipulate class or 
struct internals.
Enforcing true type-level privacy strengthens abstraction 
boundaries and helps maintain invariants.

## Specification

- Applicable only to class and struct members.

- Outside the defining module, `private(this)` == `private`.

- Inside the defining module:
   - Only code lexically inside the body of the same class or 
struct may access the member.
   - No free functions, mixins, nested types, or other types in 
the module may access it.

- All existing access rules (transitive private, inheritance, 
package scopes) remain unchanged.

## Example

module example;

struct S
{
     private(this) int x;    // Only S’s code can touch x
     int getX() { return x; }
}

void helper()
{
     S s;
     // s.x = 5;             // Error: x not accessible here
}

Pros and Cons
-------------

Pros of not having private(this)

     Simpler access model with just private at module level.

     No new keyword to learn or confuse beginners.

     Existing codebases remain fully functional without change.

Cons of not having private(this)

     Invariants can be broken by unrelated code in the same module.

     Difficult to enforce strict encapsulation; relies on 
documentation and discipline.

     Module-sized privacy may encourage large modules with weak 
boundaries.


Pros of having private(this)

     Strong, compiler-enforced type-level encapsulation.

     Clearer abstraction boundaries and safer internal invariants.

     Encourages smaller, focused modules and cleaner 
object-oriented design.

Cons of having private(this)

     Introduces another access modifier and slightly raises 
language complexity.

     Potential confusion between private and private(this) for new 
users.

     May require refactoring of existing module-heavy code to 
satisfy the stricter rules.




More information about the dip.ideas mailing list