Search code examples
c#oopencapsulation

Exposing object data without breaking encapsulation


Good object-oriented design says that objects should not expose their internals. Given this is the case, what is the best way to display data?

For example, how would you go about displaying the data field after calling DoSomethingToData in a Console application?

public class Foo {
    string data;

    public void DoSomethingToData(string someParam) {
        .....
    }
}

class Program {
    static void Main(string[] items) {
        var foo = new Foo();
        foo.DoSomethingToData("blah");
        ..... // how do we write data field to console without breaking encapsulation?
    }
}

Update: I thought the best way to maintain encapsulation would be to use an observer pattern (events), but no one has mentioned it. Is this a better solution than exposing a property or method result?


Solution

  • It depends;

    • if the value relates only to the method, make it a return value of the method
    • if the value relates to the object, expose it via a property

    I suspect it is the latter, so:

     public string Data { get { return data; } }
    

    Which is simply an accessor - the equivalent of getData() in java, for example. This isn't exposing the field, but ultimately your object should expose some API to the information. It isn't meant to be a complete secret.