Protected Data Members vs Public Data Members
Developers should use protected data members when designing class hierarchies where subclasses need direct access to certain data for extension or customization, such as in frameworks or libraries that allow inheritance for specialization meets developers should use public data members when designing simple data structures, such as plain old data (pod) classes in c++ or data classes in kotlin, where the primary purpose is to hold data without complex behavior. Here's our take.
Protected Data Members
Developers should use protected data members when designing class hierarchies where subclasses need direct access to certain data for extension or customization, such as in frameworks or libraries that allow inheritance for specialization
Protected Data Members
Nice PickDevelopers should use protected data members when designing class hierarchies where subclasses need direct access to certain data for extension or customization, such as in frameworks or libraries that allow inheritance for specialization
Pros
- +For example, in a game engine, a base 'GameObject' class might have protected health or position fields that derived 'Enemy' or 'Player' classes can modify
- +Related to: object-oriented-programming, encapsulation
Cons
- -Specific tradeoffs depend on your use case
Public Data Members
Developers should use public data members when designing simple data structures, such as Plain Old Data (POD) classes in C++ or data classes in Kotlin, where the primary purpose is to hold data without complex behavior
Pros
- +It is also common in scripting languages like Python, where all members are public by default, to facilitate quick prototyping and reduce boilerplate code
- +Related to: object-oriented-programming, encapsulation
Cons
- -Specific tradeoffs depend on your use case
The Verdict
Use Protected Data Members if: You want for example, in a game engine, a base 'gameobject' class might have protected health or position fields that derived 'enemy' or 'player' classes can modify and can live with specific tradeoffs depend on your use case.
Use Public Data Members if: You prioritize it is also common in scripting languages like python, where all members are public by default, to facilitate quick prototyping and reduce boilerplate code over what Protected Data Members offers.
Developers should use protected data members when designing class hierarchies where subclasses need direct access to certain data for extension or customization, such as in frameworks or libraries that allow inheritance for specialization
Disagree with our pick? nice@nicepick.dev