DEV Community

arpitgupta1250
arpitgupta1250

Posted on

Tips to write smart code

1. Cascades

Normal way -

Paint x = Paint();
x.color = Colors.red;

Smarter way -

Paint x = Paint();
..color = Colors.red

2. Null-aware operator

Normal way -

int money;
if(money == null){
money = 0;
}

Smarter way -

int money;
money ??=0;

3. Ternary Operator

Normal way -

String env;
if (temp > 35){
env = "hot";
}else{
env = "cold";
}

Smarter way -

String env = temp > 35
? "hot"
: "cold";

4. Assert statement

Normal way -

if(x == null){
throw AssertionError("x is null");
}

Smarter way -

assert(x !=null , "x is null")

5. Getters

Normal way -

List mylist = [1,2,3,4,5];
int len = mylist.length;
int length(){
return len;
}

Smarter way -

List mylist = [1,2,3,4,5];
int get length(){
return mylist.length;
}

These were the 5 tips.
Hope you like them.

Top comments (0)