Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 650
JontyMC Avatar asked May 24 '26 23:05

JontyMC


1 Answers

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.

like image 139
Marc Gravell Avatar answered May 26 '26 13:05

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!