Task #2022
closedcode-style: short methods in class declaration
0%
Description
Update code-style.rst
to establish a guideline to choose between these two styles on short methods:
Definition inside class declaration:
class C : noncopyable
{
public:
int
getN() const
{
return m_n;
}
private:
int m_n;
};
Definition outside class declaration:
class C : noncopyable
{
public:
int
getN() const;
private:
int m_n;
};
inline int
C::getN() const
{
return m_n;
}
This guideline is necessary to ensure consistency in code style.
Updated by Davide Pesavento about 10 years ago
For one-liners (getters and setters mostly) I'd argue that the following is the most readable solution, in my opinion:
class C : noncopyable
{
public:
int getN() const { return m_n; }
void setN(int n) { m_n = n; }
private:
int m_n;
};
Unfortunately it's incompatible with several other guidelines that we established some time ago.
Updated by Junxiao Shi about 10 years ago
Many setters are not one-liner.
They include return *this;
to allow chaining.
Updated by Alex Afanasyev about 10 years ago
I'm against any additional guidelines. All ways listed, including the one Davide mentioned and some others that are not mentioned, are acceptable and reasonable. Which one to use is up to the discretion and preference of the developer.
Updated by Junxiao Shi about 10 years ago
There should be one and only one way to do a thing. This ensures code is consistent and readable.
Updated by Davide Pesavento about 10 years ago
I'm with Alex on this one. All 3 proposed ways make sense depending on the circumstance and they're all readable, even if mixed together in the same file. The only recommendation we should make is to avoid writing long methods inline inside the class declaration (note that this recommendation mostly applies to templates, which require the method implementation in the header file, normal classes should not have long inline methods in the first place).
Updated by Junxiao Shi about 10 years ago
- Assignee set to Davide Pesavento
- Estimated time set to 1.50 h
@Davide, please update code-style.rst
to state that all three styles are acceptable.
Updated by Davide Pesavento about 10 years ago
- Assignee deleted (
Davide Pesavento)
Err... what's the point? Moreover, the style guide is already long enough as it is, I have no desire to add more (non-)rules to it.
Updated by Junxiao Shi about 10 years ago
Without a new rule, the third style is not acceptable because it violates rule 1.5.
Updated by Junxiao Shi about 10 years ago
- Subject changed from Establish code-style guideline on short methods in class declaration to code-style: short methods in class declaration
- Status changed from New to Rejected