rspec/rules/S5414/cfamily/rule.adoc

67 lines
1.9 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
Mixing (non-const) ``++public++`` and ``++private++`` data members is a bad practice because it causes confusion about the intention of the class:
* If the class is a collection of loosely related values, all the data members should be ``++public++``.
* On the other hand, if the class is trying to maintain an invariant, all the data members should be ``++private++``.
If we mix data members with different levels of accessibility, the purpose of the class is muddled.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
class MyClass // Noncompliant
{
public:
int firstNumber1() const { return firstNumber; }
void setFirstNumber(int firstNumber) { this->firstNumber = firstNumber; }
int secondNumber = 2;
const int constNumber = 0; // const data members are fine
private:
int firstNumber = 1;
};
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
class MyClass // Depending on the case, the solution might be different. Here, since this class does not enforce any invariant, we make all the data members public
{
public:
int firstNumber;
int secondNumber;
const int constNumber = 0;
};
----
2021-04-28 16:49:39 +02:00
== Exceptions
Since ``++const++`` data members cannot be modified, it's not breaking encapsulation to make a const value public, even in a class that enforces an invariant.
2021-04-28 16:49:39 +02:00
== See
* https://github.com/isocpp/CppCoreGuidelines/blob/036324/CppCoreGuidelines.md#c134-ensure-all-non-const-data-members-have-the-same-access-level[{cpp} Core Guidelines C.134]: Ensure all non-const data members have the same access level
* https://github.com/isocpp/CppCoreGuidelines/blob/036324/CppCoreGuidelines.md#c9-minimize-exposure-of-members[{cpp} Core Guidelines C.9]: Minimize exposure of members
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]