clean code, better coding practices
Post on 31-May-2015
273 Views
Preview:
DESCRIPTION
TRANSCRIPT
Clean code
Better coding practices
What is clean code?
Bjarne Stroustrup, inventor of C++Elegant and Efficient
"Reading it should make you smile the way a well-crafted music or well-designed car would."
Ratio of time spent reading vs. writing code is well over 10:1
Dave Thomas- Easy to enhance- Has unit and acceptance tests- Has one way of doing one thing
Michael Feathers“Clean code looks like it was written by someone
who cares.”
Clean code
(bad code is just like this slide, shows carelessness)
Wyh U should, right clean Code.?
80% or more of what we do is called Maintenance.
Broken windows.
Where to start?NamingMethodsClassesCommentsError handling
NamingIt should tell you why it exists, what it does, and
how it is used.
No harm in re-naming if you find better names.
Namingpublic List<int[]> getProductList() {
List<int[]> list1 = new ArrayList<int[]>();for (int[] x : theList)
if (x[0] == 4)list1.add(x);
return list1;}
public List<int[]> getFlaggedProducts() {
List<int[]> flaggedProducts = new ArrayList<int[]>();
for (int[] product: inventory)
if (product[STATUS_VALUE] == FLAGGED)
flaggedProducts .add(product);
return flaggedProducts ;
}
NamingUse Pronounceable Names
genTimstmp generationTimestamprcrdId recordIdtxtViewRltion textToViewRelation
NamingUse searchable names
int realDaysPerIdealWeek = 4;const int WORK_DAYS_PER_WEEK = 5;int sum = 0;for (int j=0; j < NUMBER_OF_TASKS; j++) {int realTaskDays = taskEstimate[j] * realDaysPerIdealWeek;int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);sum += realTaskWeeks;}
for (int j=0; j<34; j++) {
s += (t[j]*4)/5;
}
Naming
You will probably end up surprising someone
when you rename, just like you might with any
other code improvement. Don’t let it stop you
in your tracks.
-Robert C. Martin
MethodsFirst rule: they should be small!
Second rule: they should be smaller than that!!
MethodsDo one thing
Methods Use descriptive names
MethodsUse less number of arguments
MethodsHave no side-effects
ClassesOrganization
Classes Size
ClassesSingle Responsibility Principle
CommentsExplain yourself in code
Error handlingUse exceptions than return codes
Error handlingDo not return null
Do not pass null
Conclusion“Always leave the ground cleaner than you
found it.”
Paramvir Singh, Senior Android Developer,HomeShop18
top related