Encapsulation .. exact description?

I know that encapsulation means something like that one object should not have direct access to members of different objects ... but I think it refers to public fields? I guess public methods don't break encapsulation ..? I just do not understand here and will be happy for any explanation.

+6
source share
4 answers

Encapsulation does not mean that there should not be access to members. This means that you should allow access only to those members that should be used, mainly restricted access, and not access.

By making something publicly available, you allow access by making it private, and you are not.

In this article, we will look at more detailed information about various access modifiers:

http://www.csharp-station.com/Tutorials/lesson19.aspx

In this article, they give a good example:

using System; class BankAccountProtected { public void CloseAccount() { ApplyPenalties(); CalculateFinalInterest(); DeleteAccountFromDB(); } protected virtual void ApplyPenalties() { // deduct from account } protected virtual void CalculateFinalInterest() { // add to account } protected virtual void DeleteAccountFromDB() { // send notification to data entry personnel } } 

When a programmer wants to close an account, they donโ€™t need to worry about the various steps that go into this:

  • ApplyPenalties
  • CalculateFinalInterest
  • DeleteAccountFromDB

They should simply say that they want it to close and that all necessary steps will be taken. This is why CloseAccount is publicly available and others are not.

+1
source

Encapsulation is that you drive a car:

  • turn ignition key
  • steering wheel
  • gear change (if not automatic)
  • fuel addition

but not:

  • ignition of fuel in cylinders
  • friction tires and ground.
  • etc.

Open (make public ) WHAT and hide (make private ) HOW. Now you are encapsulating.

:)

+11
source

Itโ€™s very useful for me to think about classes like people with different tasks. For example, if I am a project manager and you are a developer, my open contract with you is that I will assign you tasks. How to determine the priority? This is a private part that will be useful to me; you as a developer do not need to know what to do your job.

Therefore, when thinking about encapsulation, separate class knowledge from your public contract and its implementation details. The first must be exposed - whether through public properties, methods, or something else - and the second must be encapsulated inside the class, and neither side can find out about it.

+1
source

Encapsulation hides the implementation details of an object, so there are no external bindings to a specific implementation. taken from msdn blog .

Take a look at this CodeProject post .

+1
source

Source: https://habr.com/ru/post/887962/


All Articles