Isolation between classes-do not speak with strangers.

Source: Internet
Author: User

According to my understanding, to reduce the coupling between classes, try to avoid dealing with them directly.
Or, correctly, two classes with clear division of labor should manage their own things separately, instead of"Inquire"Other things.
For example:
The requirement is as follows:
When a class updates data, you need to send an email to the relevant personnel.
Code 1:

Public dataaccess ()
{
//
// Todo: add the constructor logic here
//
}
Public void updatedata (data)
{
//
// Directly initialize the mymail class and call the mail method.
// Use mail Notification after data is updated

New mymail (). Sendmail (Mail );
}
}

Public class mymail
{
Public mymail ()
{
}
Public void Sendmail (mailargs ex)
{

}
}

Code 2
A special event class is defined to accept the trigger events for the data processing class and send emails in the event class.
As a data update class, data is only updated.
It is handled by an intermediate class.

Public class dataaccess
{
Protected eventclass E;
Public dataaccess ()
{
//
// Todo: add the constructor logic here
//
E = new eventclass (this );

}
Public void updatedata (data)
{
//

// Use Event Notification
If (updateevent! = NULL)
Updateevent (this );
}
Define events # region define events
Public Delegate void updateeventhandler (Object sender );
Public event updateeventhandler updateevent;
# Endregion
}

Public class eventclass
{
Public eventclass (dataaccess)
{
A. updateevent + = new maid. hr. biz. dataaccess. updateeventhandler (a_updateevent );
}

Private void a_updateevent (Object sender)
{
New mymail (). Sendmail (Ex );
}
}


Public class mymail
{
Public mymail ()
{
}
Public void Sendmail (mailargs ex)
{

}
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.