12.4 Access functions and encapsulation

주홍영·2022년 3월 17일
0

Learncpp.com

목록 보기
128/199

https://www.learncpp.com/cpp-tutorial/access-functions-and-encapsulation/

Why make member variables private?

separation of interface and implementation is extremely useful because it allows us to use objects without understanding how they work.

This vastly reduces the complexity of using these objects, and increases the number of objects we’re capable of interacting with.

For similar reasons, the separation of implementation and interface is useful in programming.

예를들어 자동차를 운전하는데 모든 implementation을 이해할 필요 없이
우리에게 제공되는 interface (ex. 페달, 핸들)을 이용해 상호작용하는데 더욱 편리함 제공

Encapsulation

Encapsulation (also called information hiding)
구체적인 프로그램의 구현은 감춰두고 사용자는 public interface를 이용해 object와 상호작용할 수있다. 이러한 방식으로 전적으로 이해하지 않아도 object를 사용할 수 있는 이점을 준다

즉, 사용자가 object를 사용함에 있어 불필요한 요소들은, 접근해서 수정하면 오작동을 일으킬 수 있는 부분들은 private하게 숨겨두고 제작자의 의도대로 object를 사용할 수 있는 가이드를 제공

Benefit: encapsulated classes are easier to use and reduce the complexity of your programs

사용자는 public한 멤버 function을 이용해 필요한 argument가 무엇인지 return 값은 무엇인지 어떠한 역할을 수행하는지에 대한 이해만 있으면 내부적으로 어떻게 작동하는지 모두 이해할 필요가 없다. 따라서 프로그램의 복잡도를 낮춰주고 쉽게 사용할 수 있도록 도와준다

Benefit: encapsulated classes help protect your data and prevent misuse

데이터를 보호하고 오작동을 일으키지 못하도록 보호한다

Benefit: encapsulated classes are easier to change

프로그램을 고치지 않고 argument와 return에 대한 규칙만 지켜준다면
내부에서 클래스를 고치는 것은 프로그램에 문제가 되지 않는다

Benefit: encapsulated classes are easier to debug

Access functions

이렇게 private한 member variable에 접근하기 위해서 public으로 설정한
짧은 function들을 말한다
예를 들어 getMember()와 setMember(int x)와 같은 interface로 member variable을 read하거나 write하거나 할 수 있도록 한다

Access functions concerns

  • 외부에서 접근할 필요가 없는 member variable에 대해서는 access function을 제공 x
  • setAlive(bool) 혹은 kill()과 같이 직접적으로 member variable에 접근해서 수정하는 것 보다 하나의 action으로 정하는 것이 더 낫다
  • If you can’t, consider whether you can provide only a getter.
profile
청룡동거주민

0개의 댓글