The "Encapsulate field" refactoring creates (fortunately) non-compiling code in some cases, and (unfortunately) compiling code with different behaviour in others:
class Foo {
public:
int m_value;
};
class Bar {
public:
Foo m_foo;
};
void baz() {
Bar bar;
bar.m_foo.m_value = 13;
}
Trying to encapsulate m_value in Foo works fine.
However trying to encapsulate m_foo in Bar creates the following code:
class Bar {
public:
Foo getFoo() const { return m_foo; }
void setFoo(Foo val) { m_foo = val; }
private:
Foo m_foo;
};
void baz() {
Bar bar;
bar.getFoo().m_value = 13;
}
Fortunately bar.getFoo() is not a lvalue, which prevents direct assignment, so compilation fails. However if we previously encapsulated m_value in Foo we end up with
void baz() {
Bar bar;
bar.getFoo().setValue(13);
}
Which does compile but has vastly different behaviour (m_value is set in the copy of Foo returned by getFoo(), leaving the value in the "real" Foo unchanged)
VA version 10.9.2318.0 built 2019.02.17