Clean code, Better coding practices

Preview:

DESCRIPTION

Why is there so much emphasis on reading the code rather than writing? Because: Ratio of time spent reading vs. writing code is well over 10:1 So if we are spending 1 hour writing code, on an average we have to spend 10 hours reading some code. Each time we change in logic of some code, add or remove some feature, resolve some bug, understand the context of what is going on, or just use a third party API, what we do? We READ code. At HomeShop18, we strive for clean code.

Citation preview

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

Recommended