새소식

App/Flutter

[Flutter] Class(model) getter setter 패턴 알아보기 (w.Dart)

  • -

2023-11-28


 

사진: Unsplash 의 Ian Chen


1. 패턴

 

Getter

 

아래는 getter를 사용한 패턴이다. get 키워드를 이용해 직사각형의 넓이를 추출하는 간단한 예제이다.

 

class Rectangle {
  final int width, height;
  
  Rectangle(this.width, this.height);
    
  // This computed property is treated like a function
  // that returns a value.
  int get area => width * height;
}

 


Setter

 

아래는 Setter 를 활용한 패턴으로 Point  클래스로 x와 y와 받아 중앙값을 구한다.

 

class Rectangle {
  final int width, height;
  
  Rectangle(this.width, this.height);
    
  int get area => width * height;

   // Use a private variable to 
   // expose the value with a getter; 
   Point _center;
   Point get center => _center;
   set center(Point origin) {
     _center = Point(
       origin.x + width / 2,
       origin.y + height / 2,
     );
   } 
}

void main() {
  var rectangle = Rectangle(12,6);
  print(rectangle.area);
  // The setter will calculate the center based on what we tell it is the
  // _origin_ (top left corner) of the rectangle on a plot.
  // in this case, we're setting the origin at (4,4). 
  rectangle.center = Point(4,4);  
  print(rectangle.cernter);
}

2. 주의점

 

다만 Effective Dart에서는 지양하는 getter setter 패턴이 있다.

 

 

Bad

 

아래 코드는 안좋은 패턴이다.

 

class Box {
  var _contents;
  get contents => _contents;
  set contents(value) {
    _contents = value;
  }
}

Good

 

아래 코드는 좋은 패턴이다.

 

class Box {
  var contents;
}

 

AVOID wrapping fields in getters and setters just to be “safe”.

 

Dart에서는 단순한 필드의 안전한 사용을 위해 getter와  setter를 사용하지 말라고 하고 있다. 그 이유는 Fields and getters/setters are completely indistinguishable(필드와 getter/setter 들은 완전히 구별할  수 없기 때문이다.) 또한 Dart에서는 public 데이터 멤버가 있으면 해당 getter 및 setter가 클래스 인터페이스의 일부로 암시적으로 선언되기 때문에 굳이 해당 부분을 선언할 필요가 없어진다. 


클린 코드를 위해서 linter > rules in your analysis_options.yaml file 에 해당 부분을 추가하는 것을 고려해 볼 수 있다.

 

linter:
  rules:
    - unnecessary_getters_setters

3. 참고링크

https://flutterbyexample.com/lesson/getters-and-setters

 

Getters and setters

Getters and setters are special methods that provide explicit read and write access to an object's properties. ### Getters Getters are often useful to set _computed properties_. In other words, instance variables that rely on other, non-constant variables.

flutterbyexample.com

https://dart.dev/tools/linter-rules/unnecessary_getters_setters

 

unnecessary_getters_setters

unnecessary_getters_setters linter rule documentation.

dart.dev

https://stackoverflow.com/questions/61720221/why-should-i-avoid-wrapping-fields-in-getters-and-setters

 

Why should I avoid wrapping fields in getters and setters?

I am building a Flutter app. I have a class that looks like this: class ToDo { String _title; bool _done; String get title => _title; void set title(String newTitle) { _title =

stackoverflow.com


메인 이미지 출처 : 사진: UnsplashIan Chen

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.