Search code examples
c#interfaceimmutabilityencapsulation

Would an Interface be appropriate for providing access to data outside a library, while only being able to change class data inside the library?


Take the following code (closely resembles what I'm trying to do).

IDirectory.cs

public interface IDirectory
{
    string FullPath{ get; }
}

DirectoryTree.cs

public class DirectoryTree
{
    private Directory _root;
    ...
    public IDirectory GetRoot(){...};

    private class Directory: IDirectory
    {
       ...
    }
}

I want to provide a way for other classes that use this library to access the Directory's information, but in an "Immutable" fashion, so only using "get" functions in the interface. Internally, in the case of, say, a directory getting renamed (FileSystemWatcher), I can update the Directory name field with a setter, but ONLY from inside the DirectoryTree or Directory class. Events can be registered with the DirectoryTree to be notified of changes.

Interfaces seem to make the most sense for this, but I am inexperienced. I have always been under the impression Interfaces just make it easy to interact with similar parts of different classes, but I haven't seen any examples of people using them to "protect" parts of a class from the outside world. This also makes me wonder if I'm breaking encapsulation? Is an Interface an advisable way of solving this problem?


Solution

  • I think this way is good for you.But before i recommend read these article:

    When to Use Interfaces:

    • Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.

    • Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.

    • Interfaces are better in situations in which you do not have to inherit implementation from a base class.

    • Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.

    Abstract classes and methods

    Interface vs Base class