Learning The Dart Language–Classes–Part 2
Apr 29th, 2012 | By sankarsan | Category: Programming & LanguagesIn the last post we have discussed about classes and object instantiation/initialization in Dart.In this post we will take a look methods and getter/setters.
Methods in Dart are two types : instance methods and class level static methods like any other OO language. The code below shows the definition & invocation of a typical instance method.
class Customer
{
int id;
String fn;
String ln;
String getFullName(){
return fn + " " + ln;
}
}
void main() {
var a = new Customer();
a.fn ="Sankarsan";
a.ln ="Bose";
print(a.getFullName());
}
//Prints: Sankarsan Bose
The following example shows the definition & invocation of a typical class level static method.
class Logger
{
static void LogToConsole(String msg)
{
print(msg);
}
}
void main() {
Logger.LogToConsole("Hello World !!");
}
Dart also let you define getter/setter using get and set keywords as shown below:
class Customer
{
int id;
String fn;
String ln;
String get firstName() => fn;
set firstName(String value) => fn = value;
String get lastName() => ln;
set lastName(String value) => ln = value;
String get fullName() => firstName + " " + lastName;
}
void main() {
var c = new Customer();
c.firstName ="Sankarsan";
c.lastName = "Bose";
print(c.fullName);
}
The getter/setter are defined as methods and accessed as fields/properties.Since these are defined as methods you can provide additional validations here as shown below:
set firstName(String value) {
if(value != null && value.trim().length>0) fn = value;
}
But if I compare to a language like C# where there is support for properties, the major difference is that Dart does not let you define access modifier (private) at class level and the whole purpose from encapsulation standpoint seems to be lost.
However the Dart designers feel differently – http://www.dartlang.org/articles/idiomatic-dart/#fields-getters-setters
This blurring the line between fields and getters/setters is fundamental to the language. The clearest way to think of it is that fields are just getters and setters with magical implementations. This means that you can do fun stuff like override an inherited getter with a field and vice versa. If an interface defines a getter, you can implement it by simply having a field with the same name and type. If the field is mutable (not
final) it can implement a setter that an interface requires.In practice, what this means is that you don’t have to insulate your fields by defensively hiding them behind boilerplate getters and setters like you would in Java or C#. If you have some exposed property, feel free to make it a public field. If you don’t want it to be modified, just make it
final.