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

StackOverflow https://stackoverflow.com/questions/19473806

Question

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?

Was it helpful?

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

OTHER TIPS

I dont think Interface is a suitable option for this particular task.

I would rather create an abstract base class and inherit it in my public class. This way the information of your base class is only changed through your public class which will connect to other classes.

Since interface does not allow you to implement the code , you will essentially have all your code within the class implementing the interface and you can choose to hide that implementation but I would rather prefer an abstract base class to achieve this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top