OOP : Why are there access modifier in OOP? Public/Protected/Private

In my opinion, all of them have different purposes to fulfill. I have tried to list them below. If you want to understand the concept of OOP then first go through this post “Atomic Analogy of OOP Concept“.

Private

  • Primarily, it is to converge / decrease the dependencies of outer world to these data/method. It makes sure that the developers are not going to use these data/methods and are safe to be modified if deemed.
  • So, it makes sure that its fine to make some tweak in this portion of code. It confirms that its safe and its not gonna trouble the library users.
  • Also, since outer world has no direct connect strings whatsoever, therefore, I can freely change the behavior and be confident that only the same class is gonna be affected.
  • I might(not) have test coverage for this.

Public

  •  Public keyword makes sure that the code under the Public header are gonna be used by clients and they reply upon these. So, its very risky to change / modify this portion of the code. If you feel the urge to modify the behavior then you must do it in upcoming versions with appropriate version numbers(may be a major release).
  • These are the public API of your library.
  • Good to have full test coverage.

 

Protected

  • When sibling objects desire to send messages to each other but, no one else can; then, you make the properties project.
  • I might(not) have test coverage for this.
  • Use cases:
    • If are desiring to design a classes with ability to chain method(internally) calls but do not want to allow the outer world to have idea about this.
    • def search
        base.keywords.order.limit
      end
      protected
      def base; ...;self; end
      def keywords; ...;self; end
      def order; ...;self; end
      def limit; ...;self; end

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s