Search code examples
c#vb.netoopinheritanceencapsulation

Encapsulation VS Inheritance - How to use a protected function?


In OOP languages like C# or VB.NET, if I make the properties or methods in a super class protected I can't access them in my Form - they can only be accessed in my class that inherits from that super class.

To access those properties or methods I need to make them public, which defeats encapsulation, or re-write them into my class, which defeats inheritance.

What is the right way to do this?


Solution

  • "need to make them public which defeats encapsulation"

    Don't conflate good design with the icky visibility rules. The visibility rules are confusing. There are really two orthogonal kinds of visibility -- subclass and client. It's not perfectly clear why we'd ever conceal anything from our subclasses. But we can, with private.

    Here's what's important. Encapsulation does not mean hiding. Protected and private are not an essential part of good encapsulation. You can do good design with everything being public (that's the way Python works, for example).

    The protected/private stuff is -- mostly -- about intellectual property management: are you willing to commit (in a legally binding, "see-you-in-court-if-it-doesn't-work" way) to an interface? If your software development involves lawyers, then you care about adding protect and private to the things you're not committed to.

    If you don't have to cope with lawyers, consider doing encapsulation right but leave everything public.