- Dart:Scalable Application Development
- Davy Mitchell Sergey Akopkokhyants Ivo Balbaert
- 212字
- 2021-07-09 18:56:18
Accessing private fields
In Dart, as discussed when we covered packages, the privacy is at the library level, but it is still possible to have private fields in a class even though Dart does not have the keywords public, protected, and private. A simple return of a private field's value can be performed with a one-line function:
String getFirstName() => _name;
To retrieve this value, a function call is required, for example, Person.getFirstName();
however, it may be preferable to have a property syntax such as Person.firstName
. Having private fields and retaining the property syntax in this manner is possible using the get
and set
keywords.
Using true getters and setters
The syntax of Dart also supports get
and set
via keywords:
int get score => score + bonus; set score(int increase) => score += increase * level;
Using either get
/set
or simple fields is down to preference. It is perfectly possible to start with simple fields and scale up to getters and setters if more validation or processing is required.
The advantage of the get
and set
keywords in a library is that the intended interface for consumers of the package is very clear. Further, it clarifies which methods may change the state of the object and which merely report current values.
- Java多線程編程實戰(zhàn)指南:設(shè)計模式篇(第2版)
- NumPy Essentials
- The Computer Vision Workshop
- The Data Visualization Workshop
- HTML5 and CSS3 Transition,Transformation,and Animation
- Xamarin.Forms Projects
- H5頁面設(shè)計:Mugeda版(微課版)
- Python數(shù)據(jù)結(jié)構(gòu)與算法(視頻教學(xué)版)
- Instant Nancy Web Development
- Create React App 2 Quick Start Guide
- 編程菜鳥學(xué)Python數(shù)據(jù)分析
- Spring+Spring MVC+MyBatis從零開始學(xué)
- FPGA嵌入式項目開發(fā)實戰(zhàn)
- MySQL 8從零開始學(xué)(視頻教學(xué)版)
- C語言程序設(shè)計與應(yīng)用實驗指導(dǎo)書(第2版)