Encapsulation..most precise description?
I know that encapsulation means something like that one object should not have direct access to members开发者_JS百科 of different objects...but I guess it relates to public fields? I assume public methods do not break encapsulation..? I am just not clear here and would be glad for any explanation.
Encapsulation is that you drive your car by:
- turning the ignition key
- steering the wheel
- changing the gears (if not automatic)
- adding the fuel
and not by:
- igniting the fuel in the cylinders
- friction-ing tires and ground
- and so on...
Expose (make public
) WHAT and hide (make private
) HOW. Now, you're encapsulating.
:)
Encapsulation does not mean that there should be no access to members. It means that you should only allow access to members that should be used, basically restricted access instead of no access.
By making something public you are allowing access, by making it private you are not.
This article goes into more depth as well as the 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 shouldn't have to worry about the various steps that go into that:
- ApplyPenalties
- CalculateFinalInterest
- DeleteAccountFromDB
They should just say they want it closed and that all necessary steps will be taken. That is why CloseAccount
is public and the others are not.
I find it most helpful to think about classes like people with different jobs. For example, if I am a project manager, and you are a developer, my public contract with you is that I will assign you tasks. How do I determine the priority? That is a detail that is private to me; you as a developer don't need to know that to do your job.
So when thinking about encapsulation, separate a class' knowledge into its public contract, and its implementation details. The first should be exposed - whether that is through public properties, methods, or whatever - and the second should be encapsulated inside the class, with no way for an outsider to find out.
Encapsulation is hiding the details of the implementation of an object so that there are no external dependencies on the particular implementation. taken from msdn blog.
Have a look at this CodeProject post.
精彩评论