Private Class Data — C Sharp (C#) — Studysection Blog

Private Class Data — C Sharp (C#) — Studysection Blog
  • It provides control on write access of class properties.
  • It separates the data from the methods where they need to be implemented.
  • Class data get encapsulated during initialization.

Concern
There is a chance that a class can expose its properties to data manipulation when there is no need for it. For example, After constructor method execution. Therefore using this private class data design pattern can prevent this unrequired manipulation.
A class can have properties that are mutable and they can’t be declared final. Therefore this design pattern can help in the one-time setting of the class properties. The main purpose of this design pattern is to protect the class state by hiding its properties (data).

Structure

Let’s understand with an example:-

Without using a design pattern

The property seconds below should not change after the SecondsConverter() constructor. The visibility is already limited by scoping them as private, but the methods of class SecondsConverter like ConvertToHours can still change them. We can also set properties of classes as const (or final or ReadOnly) restricts their manipulation, but the properties are set in the constructor and therefore cannot be marked as such.

Using Design Pattern

The extra openness of the properties creates a type of coupling between methods that access those properties. To reduce the visibility of the properties implement this design pattern.

Conclusion
The private class data design pattern helps to reduce the vulnerability of properties by reducing their visibility. It helps in reducing the number of class properties by encapsulating them in a single object. It allows the developer to remove the write access of properties that are implemented to be set only during construction, even from methods of the target class.

If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.

Originally published at https://studysection.com on March 22, 2022.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Study Section

Study Section

The most loved online platform for eCertification in several subjects including but not limited to Software Development, Aptitude and more.