Subscribe via RSS Feed

Google Dart – language of Structural Web Applications

September 12, 2013 7 Comments

Google Dart

Recently we are exploring Google Dart as a choice for web applications in our projects. We have explored previously different concepts of Angular.js for client side development which is Javascript based MV* framework. When we first looked at Google Dart to explore the ways of development, we have seen Dart as a full featured language.

According to wikipedia.org,

Dart is a class-basedsingle inheritanceobject-oriented language with C-style syntax.

So we have decided to write about different features of Google Dart as a language, it’s application in web and other features. In current post we will cover some aspects of Google Dart as purely language. To understand all the concepts deeply, we should refer to -

dartlang.org – https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html 

We have taken all the concepts of Dart from the above url and re-written as per our understanding.

We assume that, reader has familiarity with one Object Oriented Language like Java or C++ to understand Dart within a short period.

1> The import of Packages -

import ‘dart:math’;

This signifies the import of math library from Dart Core Module.

2> An example of Function in dart which returns a number -

showNumber(num aNumber) {
    print('The number is $aNumber.'); // Print to the console.
}

helloName(String aName) {
    print('Hi $aName.');
}

sendBoolean(bool aBool) {
    print('this is $aBool');
}

In the above code we have found -

  • ‘showNumber’,  ’helloName’, ‘sendBoolean’ as function declaration.
  • ‘num’, String, bool as a datatype
  • $aName, $aBool as expression in Dart which indicate replacing of the variable with the function argument value.

3> Testing ability within the code -   

checkAssert()
{
    num myNumber = 10;
    assert(myNumber == 10);
    int anyNo;
    assert(anyNo == null);
}

In the above code we have found -

  • ‘assert’ to unit test the code

If code does not break, it will not show anything in checked mode of compilation, otherwise it will break with exception. In production mode, the implication of assert will simply be ignored.

4> Main entry point of Dart Application -   

void main() {
    showNumber(50);
    helloName("Piyas");
    var thisIsBool = true;
    sendBoolean(false);
    sendBoolean(thisIsBool);
    checkAssert();
    convertVariables();
    manipulateString('Arun','good');
    assert('Arun is good' == returnString('Arun','good'));
    exampleMultiLineString();
    dartLists();
    dartMaps();
    optionalFunction(firstnum:10,secondnum:100);
    optionalFunction(firstnum:10);
    print(showValue('Rima','Kolkata'));
    print(showValue('Sima','Kolkata','9999999999'));
    functionWithinFunction();
    lexicalScope();
    var firstVar = getFullSentence ('Ram');
    var secondVar = getFullSentence ('Sima');

    print(firstVar('male'));
    print(secondVar('female'));
    shortTypeCast();
    longTypeCast();

    RedirectPoint rp = new RedirectPoint.alongXAxis(100);

    Car anyCar = new Car();
    print(anyCar.convertedCar(4, true));

    anyCar = new Car();
    print(anyCar.convertedCar(2, true));

    anyCar = new Car();
    print(anyCar.convertedCar(2, false));

    // Overriding
    SquareofVar sqv = new SquareofVar(2);
    print(sqv*(new SquareofVar(4)));

}

In the above code we have found -

  • ‘main’  as entry point in Dart Application
  • using ‘var’ to define any variable
  • ‘//’ is be used to comment

We have written various functions and classes and tested with main module in the above code, which are discussed later.

Some notable concepts, which we have seen in Dart documentation -

1. Every variable in Dart is object.

2. For a given variable if no static types are defined, then all variables are defined as ‘dynamic’ type.

3. Adding static types for variables are optional in code.

4. ‘==’ checks if two objects are equivalent.

5> Convertion between data types -   

convertVariables()
{
    // String to int convertion
    var ten = int.parse('10');
    assert(ten == 10);

    // int to String convertion
    String tenAsString = 10.toString();
    assert(tenAsString == '10');
}

In the above code we have found -

  • for all the objects we have ‘parse’, ‘toString’ methods which helps convertion of variables
  • ‘int.parse(’10′) converts a String variable to int variable
  • ’10.toString()’ converts int variable to String variable

6> Manipulation of String variables -  

// Dart string manipulation with strings
manipulateString(String name,String character)
{
    print('$name is $character');
}

// return value from function
returnString(String name,String character)
{
    return('$name is $character');
}
// multiline string
exampleMultiLineString()
{
    var s1 = '''
              An example of
              multi-line string is here.
              ''';
    print(s1);
}

In the above code we have found -

  • variables as expression can be concatenated seamlessly.
  • ‘return’ is used to return value from function
  • ”’ is used to print the sentence/s as it is written in actual statement which will be useful feature to show static text in web.

7> Dart List and Map -  

// Dart Lists
dartLists()
{
    var list = [10, 20 ,30];                        // declarative list
    print('list.length '+ list.length.toString());
    print('list[1] is ' + list[1].toString());      // use of variable conversion from int to String
}

// Dart Maps
dartMaps()
{
    var map = new Map();
    map[0] = 'Paul';
    map[1] = 'John';
    map[2] = 'Ruby';
    map[3] = 'Phillip';
    print('map.length '+ map.length.toString());    // use of variable conversion from int to String
    print('map[1] is ' + map[1]);
    print('map[0] is ' + map[0]);
}

In the above code we have found -

  • two types of collection – list and map to work with complex data structures.
  • The collections can be declarative or dynamic in nature
  • Map key can be of int or String type.(String type is not shown here. Reader should try it in IDE (Dart Editor))

8> Dart function with optional parameters -

optionalFunction({num firstnum: 10,num secondnum:0})
{
    print(firstnum);
    print(secondnum);
}

String showValue(String name, String address, [String phoneNo,String landNo = 'N.A' ]) {
    var findPeople = '$name lives in $address.';
    if (phoneNo != null) {
        findPeople = '$findPeople Phone No is $phoneNo.';
        findPeople = '$findPeople LandNo is $landNo';
    }
    return findPeople;
}

In the above code we have found -

  • When calling a function, we should specify named parameters using paramName: value and {}
  • Function parameters in [] will be treated as optional positional parameters
  • We have to use ‘=’ for default values

The above functions are tested with desired output in the main module, mentioned above.

9> Example of Function as parameter to another function -

printAllValue(elValue) {
    print('This one is '+ elValue.toString());
}

functionWithinFunction()
{
    var list = [1,2,3];
    list.forEach(printAllValue); // Note this code
}

10 > Use of lexical Scope Function -

var Level1 = 1;
lexicalScope() {
    var Level2 = 2;
    lexicalScope1() {
        var Level3 = 3;
        print(Level2);
        lexicalScope2() {
            var Level4 = 4;
            assert(Level2); // Inner level function can have access to all upper level variables in lexical scope.
            assert(Level3);
            assert(Level4);
        }
    }
}

11 > Use of lexical Closure -

Function getFullSentence(String name) {
    addGender(String gender) {          // Quite tricky, if not have experience with closures
        return name + ' is ' + gender;
    }
    return addGender;
}

12 > Typecast and value assigning -

class Person {
    String firstName = '';
    String lastName = '';
}

shortTypeCast()  
{
    var person = new Person();
    (person as Person).firstName = 'Bob'; // Typecast in short way
    print(person.firstName);
}

longTypeCast()
{
    var person = new Person();
    if (person is Person) {              // Type check
        person.firstName = 'Paul';       // Typecast in long way, but more elaborative and easy to understand  
    }
}

13 > Writing try, catch, throw – syntax is little different -

try {
    anFunction();
} on Exception catch(e) { // Anything that is an exception
    print('Unknown exception: $e');
} catch(e) {              // No specified type, handles all
    print('Something really unknown: $e');
}

To Note -

  • We can also write our exception, which can be handled in try, catch, throw block

14 > All the control flow statements are like general OOP languages, but switch case with String comparison is here -

// This type of switch case is available only in java 1.7 and above

var command = 'OPEN';
switch (command) {
   case 'CLOSED':
        executeClosed();
        break;
   case 'PENDING':
        executePending();
        break;
   case 'APPROVED':
        executeApproved();
        break;
   case 'DENIED':
        executeDenied();
        break;
   case 'OPEN':
        executeOpen();
        break;
   default:
        executeUnknown();
}

To Note -

15 > Dart Classes -

class Point {
    num firstVar; // initially firstVar is null.
    num secondVar; // initially secondVar is null.
    num thirdVar = 0; // initially thirdVar is 0.

    Point() // Default Constructor
    {
         firstVar = 0;
         secondVar = 0;
         thirdVar = 0;
     }
}

class AlternatePoint {
     num firstVar; // initially firstVar is null.
     num secondVar; // initially secondVar is null.
     num thirdVar = 0; // initially thirdVar is 0.

     AlternatePoint(num fVar,num sVar, num tVar) // Constructor with Arguments
     {
         this.firstVar = fVar;
         this.secondVar = fVar;
         this.thirdVar = fVar;
     }
}

To Note -

  • Every object is an instance of a class, and all classes are type of Object.
  • Constructors in the classes can not be inherited
  • Subclasses don’t inherit constructors from their superclass. A subclass that declares no constructors has only the default (no argument, no name) constructor.

16 > Sub class must call super class constructor to have the functionality of constructor of super class -

// Example of named constructor 
class NamedConstructorPoint {
    num x;
    num y;
    // Example of Named constructor
    NamedConstructorPoint.fromJson(Map json) {
        x = json['x'];
        y = json['y'];
    }
}

// Invoke non-default named superclass constructor

class Institution {
    Institution.fromJson(Map data) {
         print('in Institution');
    }
}

class College extends Institution { // extending classes
     // Person does not have a default constructor;
     // we must call super.fromJson(data).
     College.fromJson(Map data) : super.fromJson(data) {
         print('in College');
     }
}

In the above code we have found -

  • From sub class we need to call the superclass constructor with preceding ':'

17 > Redirecting constructors -

class RedirectPoint {
    num x;
    num y;

    RedirectPoint(this.x, this.y)
    {
        print (this.x + this.y - 50);
    } // The main constructor for this class.

    // This constructor have redirectional values from other constructors
    RedirectPoint.alongXAxis(num x) : this(x, 0); // Calling the main constructor.
}

18 > Instance methods  -

class Car {
    num wheel = 0;
    bool oilNeeded = false;

    String convertedCar(num wheel, bool oilNeeded) {
        this.wheel = wheel;
        this.oilNeeded = oilNeeded;

        if((this.wheel == 4) && (this.oilNeeded))
        {
            return "BMW";
        }
        else if ((this.wheel == 2) && (this.oilNeeded))
        {
            return "Motor Cycle";
        }
        else
        {
            return "Cycle";
        }
    }
}

19 > Abstract methods  -

abstract class someClass {
   // ...Define instance variables and methods...
   void doSomething(); // Define an abstract method.
}

class EffectiveClass extends someClass {
    void doSomething() {
     // ...Provide an implementation, so the method is not abstract here...
     }
}

To Note -

  • Instance, setter, getter methods can be abstract, which will have emplty body and end with ';'.
  • The Abstract methods leave empty body in them and leave implementation for inherited classes.

20 > Operator Overloading  -

// * operator overloading  
// feature we can find in c++ but not in java

class SquareofVar {
    final int x;

    const SquareofVar(this.x);

    int operator *(SquareofVar v) { // Overrides *
        return (x*x)*(v.x*v.x);
    }
}

21 > How to use generics  -

....
var names = new List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']); // Use of Specific String datatypes in List Collection 

abstract class Cache {                   // to change in actual classes for which the generic type T is used
    T getByKey(String key);
    setByKey(String key, T value);
}

Some special notes -

  • To extend classes, we have to use super.<<methodname>> in the work.
  • Static variable values are not changed across the classes.
  • Static variables are not initialized until they are used.
  • Static methods do not operate on instances and do not have access to ‘this’ variable

The above are all for now. We will work and write on Dart in our next posts. So stay tuned. Also, please comment on other concepts in Dart language, which you found useful.

For other advanced concepts like ‘typedef’, ‘metadata’ , reader should go thoroughly -

https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html

If you find this article helpful, you can connect us in Google+ and Twitter.

Want to get blog updates? Subscribe here


Enter your email address:

Delivered by FeedBurner