encapsulation is the abstraction of related methods or properties into an object. The meaning of encapsulation:
- External hidden internal implementation, the interface is unchanged, the internal implementation of free modification.
- Only the data and methods that are needed are returned.
- Provides a way to prevent data from being modified.
- Better code reuse.
In order to improve the readability and maintainability of the code, we can encapsulate the conditions when the code contains a lot of conditional judgments. There are two kinds of encapsulation methods: first, no parameter condition judgment, encapsulation is the pre-reconstruction code of the property.
Public classRemotecontrol {Private string[] Functions {Get;Set; } Private stringName {Get;Set; } Private intCreatedyear {Get;Set; } Public stringPerformcoolfunction (stringbuttonpressed) { //determine if we are controlling some extra function//That requires special conditions if(Functions.length >1&& Name = ="RCA"&& createdyear > DateTime.Now.Year-2) return "dosomething"; } }
Post-Refactoring Code
Public classRemotecontrol {Private string[] Functions {Get;Set; } Private stringName {Get;Set; } Private intCreatedyear {Get;Set; } Private BOOLhasextrafunctions {Get{returnFunctions.length >1&& Name = ="RCA"&& createdyear > DateTime.Now.Year-2; } } Public stringPerformcoolfunction (stringbuttonpressed) { //determine if we are controlling some extra function//That requires special conditions if(hasextrafunctions)return "dosomething"; } }Second, the parameters of the conditional judgment, encapsulation as a method of reconstruction before the code
Public classRemotecontrol {Private string[] Functions {Get;Set; } Private intCreatedyear {Get;Set; } Public stringPerformcoolfunction (stringbuttonpressed) { //determine if we are controlling some extra function//That requires special conditions if(Functions.length >1&& buttonpressed=="RCA"&& createdyear > DateTime.Now.Year-2) return "dosomething"; } }
Post-Refactoring Code
Public classRemotecontrol {Private string[] Functions {Get;Set; } Private stringName {Get;Set; } Private intCreatedyear {Get;Set; } Private BOOLHasextrafunctions (stringbuttonpressed) {Get{returnFunctions.length >1&& buttonpressed=="RCA"&& createdyear > DateTime.Now.Year-2; } } Public stringPerformcoolfunction (stringbuttonpressed) { //determine if we are controlling some extra function//That requires special conditions if(Hasextrafunctions (buttonpressed))return "dosomething"; } }
Package conditions (encapsulate Conditional)