- 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.
- Getting Started with ResearchKit
- 深度學習經典案例解析:基于MATLAB
- Java Web基礎與實例教程(第2版·微課版)
- PostgreSQL 11從入門到精通(視頻教學版)
- RabbitMQ Cookbook
- 劍指大數據:企業級數據倉庫項目實戰(在線教育版)
- 常用工具軟件立體化教程(微課版)
- Unity 2018 Shaders and Effects Cookbook
- OpenResty完全開發指南:構建百萬級別并發的Web應用
- Beginning C++ Game Programming
- Go語言底層原理剖析
- 編程改變生活:用Python提升你的能力(進階篇·微課視頻版)
- App Inventor 2 Essentials
- Mastering Gephi Network Visualization
- Manage Your SAP Projects with SAP Activate