Writing a clean code takes an extra step! Looking at the code I have developed in the past week, I found it difficult to understand the purpose of the code although I did commented my code. Sometimes, if the code is concise and names are meaningful, comments can be eliminated because the code explains itself.
Bad example
double functionA(var1, var2) {
return var1 % var2;
}
Good example
double performMod(dividend, divisor) {
return dividend % divisor;
}
One thing I found quite interesting is that a class structure that is too small, meaning that it does not do enough work on its own, should not exist. “A class that isn’t doing enough to pay for itself should be eliminated” (Martin, 2008, p68). For example,
class Planet {
final name;
final description;
Planet(this.name, this.description);
}
class PlaneterySystem {
final name;
List planets;
PlaneterySystem(this.name, this.planets);
get numOfPlanets {
//return the number of planets in the planetary system
}
void displayPalents() {
//display planets info
}
}
The Planet class seems to be unnecessary; it does not do enough work to stay on its own. It can be replaced with another data structure for example a list, map would work better. The above code can be replaced with
class PlaneterySystem {
final name;
Map<String, String> planets = {};
PlaneterySystem(this.name);
get numOfPlanets {
//return the number of planets in the planetary system
}
void displayPalents() {
//display planets info
}
void addPlanet() {
//add another planet to the planetery system
}
}
Encapsulation is another important thing which keeps the integrity of the code. Most of the code I have written in the past did not involve exposing the code to other people as a service. For example when developing a plug-in or an API, encapsulation can be crucial;private data should be protected and private.
Code implementation is different from a programming language to another. For example, in statically typed programming languages, variables data type is explicitly declared. For example in C++
String star;
The variable start is clearly a string. However in dynamically typed programming languages, variables not explicitly declared and the data type is defined during the run time which sometimes makes harder to understand the code, if the code is not clean and well commented. For example,
Var student;
Looking at the variable student is hard to determined its data type without looking at the rest fo the code. A good practice would make the code meaningful. If the name is not meaningful, a comment would be necessary !
For example,
Var studentName ; //is quite clear that the data type of the studentName would be a String as the name suggests
References
Martin, Robert C. Clean Code: A Handbook of Agile Software Craftsmanship. 1st edition, Pearson, 2008.