Code That Says Exactly What It Means

Peter C peterc at gmail.com
Thu Oct 30 05:23:29 UTC 2025


On Thursday, 30 October 2025 at 03:48:01 UTC, Steven 
Schveighoffer wrote:
>

An putting aside any idea of adding scopeprivate to D, let's 
remind ourselves that abstraction is one of the central 
principles of software engineering, what an abstract data type 
actually is, and why it's important for it to have the capacity 
to establish and maintain its own invariants:

https://learn.adacore.com/courses/ada-in-practice/chapters/abstract_data_types.html

If I put these two types in the same module, where you can 
reasonably argue they belong, then the concerns in the article 
above become an immediate reality in D:

class Collection
{
     int[] data;

     scopeprivate int _version; // it's vital here that Collection 
maintain control over this. scopeprivate makes that explicit and 
enforcable. This is a good thing, not a bad thing.

     this(int[] values)
     {
         data = values.dup;
         _version = 0;
     }

     void add(int value)
     {
         data ~= value;
         _version++;
     }

     int getVersion()
     {
         return _version;
     }
}

class CollectionIterator
{
     private Collection coll;
     private size_t index;
     private int expectedVersion;

     this(Collection c)
     {
         coll = c;
         index = 0;
         expectedVersion = c.getVersion();
     }

     bool hasNext()
     {
         checkForModification();
         return index < coll.data.length;
     }

     int next()
     {
         checkForModification();
         return coll.data[index++];
     }

     private void checkForModification()
     {
         if (coll.getVersion() != expectedVersion)
         {
             throw new Exception("Collection modified during 
iteration!");
         }
     }
}




More information about the Digitalmars-d mailing list