Encapsulation Technique

In Development by PaulLeave a Comment

I’m a really big fan of encapsulation. I use it all the time, and I’m always looking for improved techniques. One technique I’ve been using recently (in C#) involves using interfaces, nested classes, and a factory method. Here’s an example:

public interface IFoo
{
    IBar GetBar();
}

public interface IBar
{
    void SomeMethod();
}

public static class Foo
{
    public static IFoo Create()
    {
        return new FooInternal();
    }

    private class FooInternal: IFoo
    {
        public IBar GetBar()
        {
            return new BarInternal();
        } 
    }

    private class BarInternal: IBar
    {
        public void SomeMethod()
        {
        }
    }
}

A user of this code could do something like this:

var foo = Foo.Create();
var bar = foo.GetBar();
bar.SomeMethod();

But they wouldn’t have any direct access to FooInternal or BarInternal — which is a good thing! However, FooInternal and BarInternal could access each other if needed.

One downside: using nested classes in this way makes testing a bit harder since you can’t individually create and test FooInternal and BarInternal.

Share:

Leave a Comment