Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide implementation

Tags:

c#

oop

Lets say I have a class library, where any classes that are internal have access to the following interface:

interface myInterface
{
    string myProperty { get; set; } // notice setter.
}

But if somebody adds this class library to their project they get the following interface:

public interface myInterface
{
    string myProperty { get; }
}

What is the most efficient and accepted way of doing this? Have one interface implement the other?

like image 376
Cheetah Avatar asked Jan 11 '13 14:01

Cheetah


People also ask

How do you hide implementation details?

Abstraction is hiding the implementation details by providing a layer over the basic functionality.

How do you hide implementation in C++?

In the main cpp, use an anonymous namespace and put there the functions that you do not want to be visible outside. Anonymous namespaces are only visible within the compilation unit in which they are declared. They have the advantage to hide much more than only local functions.

Does encapsulation hide implementation?

Another important concept to do with encapsulation is implementation-hiding. The idea behind implementation-hiding is to hide the inner workings of the function from the outside world.

Why to hide implementation in java?

Implementation hiding is a key concept in object-oriented programming. The idea is to hide the implementation of a class so that changes in the implementation do not affect the public interface of the class.


2 Answers

Make your public interface have just the getter:

public interface myInterface
{
    string myProperty { get; } 
}

And then derive another internal-only interface from it that has a setter:

internal interface myInternalInterface : myInterface
{
    new string myProperty { get; set; }
}

You can them implement the internal interface:

class myImplementation : myInternalInterface
{
    public string myProperty{get; set;}
}

If you need to call the setter, you can cast your instance to the internal inteface and call it on that. This approach is a bit of a design smell though, so use it sparingly.

like image 164
adrianbanks Avatar answered Oct 14 '22 01:10

adrianbanks


You can have the internal interface extend the public interface, like so:

public interface MyInternalInterface: MyPublicInterface
{
    string MyProperty { set; }
}

public interface MyPublicInterface
{
    string MyProperty { get; }
}

internal class A: MyInternalInterface
{
    public string MyProperty { get; set; }
}

public class Foo
{
    private A _a = new A();
    internal MyInternalInterface GetInternalA() { return _a; }
    public MyPublicInterface GetA() { return _a; }

}

This way you don't need any casts or anything.

like image 22
vidstige Avatar answered Oct 14 '22 00:10

vidstige