SlideShare a Scribd company logo
Kuliah umum OOP,
Computer Science IPB
Ifnu, 28 Maret 2017
Who am I?
• Ifnu Bima
• Ilmu Komputer IPB, 38
• Join blibli in 2012
• Was working for Deustche Bank Singapore
• Employee no 69
• Engineers no ~13
• Development Manager
– blibli.com Web UI
– Mobile Apps : Android, iOS, Windows Phone
– Content Management System
– Search
– Product Discovery : Wishlist, Product Review
Survey
Ingin bekerja sebagai
Software Developer?
Survey
Ingin bekerja sebagai
Software Developer seumur
hidup?
Clean Code Agenda
• Code Quality
– External quality
– Internal quality
• Clean Code
– Meaningful Names
– High quality function
– Comments
– Unit Test
Code quality metrics
Robert C. Martin (Uncle Bob) Book
External Quality
• Easy to use Application
• Zero bug
• Fast
• Scalable
Internal Code Quality
• Readable
• Mantainable
• Testable
• Elegant
Why do we care?
• There’s no such thing as write-once code
• Code written, read & modified hundreds times
Why do we care?
• Bug Fixes
• Business Changes
• Enhancements
• New Functionality
What Prevents Clean Code?
• Ignorance
• Stubbornness
• Short-Timer Syndrome
• Arrogance
• Job Security
• Scheduling, Deadline Driven Development
What Prevents Clean Code?
Number one reason:
“I’ll clean it up later.”
“Ahh, gampang, ntar
aja, yang penting
beres dulu”
The Truth about Clean Code
• Clean Code saves time.
• We can’t take a short-term view of software.
• We need to look at the lifespan of the
application.
How Do You Write Clean Code?
Rule of Thumb:
Imagine that the developer who
comes after you is a homicidal
maniac who knows where you
live.
-Unknown
The next developer
The next
developer
that mantain
code you
write
Better motivation
Clean Code : Maningful Names
Clean Code : Meaningful Names
• Intention-Revealing Names
• Self Explained Names
• theList, x1, y1, i, j, k, index
– Not very good
• productList, indexOfProductList
– A bit better
Intention-Revealing Names : Bad
List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList) {
if (x[0] == 4) {
list1.add(x);
}
}
return list1;
}
Intention-Revealing Names : Good
List<Cell> getFlaggedCells() {
List<Cell> flaggedCells = new ArrayList<Cell>();
for (Cell cell : gameBoard) {
if (cell.isFlagged()) {
flaggedCells.add(cell);
}
}
return flaggedCells;
}
Clean Code : Meaningful Names
• Avoid Disinformation
int a = l;
if (O == l) a = O1;
else l = 01;
• Make Meaningful Distinctions
public static void copyChars(char a1[], char a2[]) {
for (int i = 0; i < a1.length; i++) {
a2[i] = a1[i];
}
}
Meaningful Names
• Use Pronounceable Names : Bad
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/* ... */
}
• Use Pronounceable Names : Good
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;
private final String recordId = "102";
/* ... */ };
}
Meaningful Names
• Use Searchable Names : Bad
for (int j = 0; j < 34; j++) {
s += (t[j] * 4) / 5;
}
• Use Searchable Names : Good
int realDaysPerIdealDay = 4;const
int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j = 0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
Meaningful Names
• Avoid mental mapping : Bad
for (i = 0; i < arr.length; i++) {
for (j = i; j < arr.length; j++) {
//bubble sort
}
}
• Dont try to be funny : Bad
public void canggih() {
//TODO
}
Meaningful Names
• Code Convention
• Class should be noun
• Method should be verb
High Quality Function
• Small!
• rules of functions:
1. should be small
2. should be smaller than that
• < 150 characters per line
• < 20 lines
• Do One Thing
1. FUNCTIONS SHOULD DO ONE THING. THEY
SHOULD DO IT WELL.
2. THEY SHOULD DO IT ONLY.
High Quality Function
• DRY : Dont repeat yourself
– Copy paste code everywhere is root of all evil in
software
Comments
• Do Not Make Up for Bad Code
– don’t comment bad code, rewrite it!
//edan ini kode siapa yang bikin!!
for (int j = 0; j < 34; j++) {
s += (t[j] * 4) / 5;
}
• Explain yourself in code
// Check to see if the employee is eligible for full
// benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))
{
if (employee.isEligibleForFullBenefits()) {
}
}
Comments (good)
• Legal Comments
// Copyright (C) 2017 by blibli.com. All rights reserved.
// Released under the terms of the GNU General Public License
// version 2 or later
• Informative Comments
// Returns an instance of the Responder being tested.
protected abstract Responder responderInstance();
// format matched kk:mm:ss EEE, MMM dd, yyyy
Pattern timeMatcher = Pattern.compile(
"d*:d*:d* w*, w* d*, d*");
Comments (good)
• Explanation of Intent
//This is our best attempt to get a race condition
//by creating large number of threads.
for (int i = 0; i < 25000; i++) {
WidgetBuilderThread widgetBuilderThread =
new WidgetBuilderThread(
widgetBuilder, text, failFlag);
Thread thread =
new Thread(widgetBuilderThread);
thread.start();
}
Comments (good)
• Clarification
assertTrue(a.compareTo(b) == -1); // a < b
assertTrue(b.compareTo(a) == 1); // b > a
• Warning of Consequences
public static SimpleDateFormat
makeStandardHttpDateFormat() {
//SimpleDateFormat is not thread safe,
//so we need to create each instance independently.
SimpleDateFormat df =
new SimpleDateFormat("dd MM yyyy");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}
Comments (good)
• TODO Comments
//TODO - MdM these are not needed
//We expect this to go away when we do the checkout model
• Amplification
String listItemContent = match.group(3).trim();
// the trim is real important. It removes the starting
// spaces that could cause the item to be recognized
// as another list.
new ListItemWidget(this, listItemContent,
this.level + 1);
return buildList(text.substring(match.end()));
Comments (bad)
• Mumbling
try {
String propertiesPath = propertiesLocation
+ "/" + PROPERTIES_FILE;
FileInputStream propertiesStream =
new FileInputStream(propertiesPath);
loadedProperties.load(propertiesStream);
} catch (IOException e) {
// No properties files means all defaults are loaded
}
Comments (bad)
• Redundant Comments
/** * The processor delay for this component. */
protected int backgroundProcessorDelay = -1;
/** * The lifecycle event support for this component. */
protected LifecycleSupport lifecycle =
new LifecycleSupport(this);
/** * The container event listeners for this Container. */
protected ArrayList listeners = new ArrayList();
Comments (bad)
• Mandated Comments
/**
* @param title The title of the CD
* @param author The author of the CD
* @param tracks The number of tracks on the CD
* @param durationInMinutes The duration of the CD in minutes
*/
public void addCD(String title, String author,
int tracks, int durationInMinutes) {
CD cd = new CD();
cd.title = title;
cd.author = author;
cd.tracks = tracks;
cd.duration = durationInMinutes;
}
Comments (bad)
• Journal Comments
/** Changes (from 11-Oct-2001)
* --------------------------
* 11-Oct-2001 : Re-organised the class and moved it to new
* package com.jrefinery.date (DG);
* 05-Nov-2001 : Added a getDescription() method, and
* eliminated NotableDate class (DG);
* 12-Nov-2001 : IBD requires setDescription() method, now
* that NotableDate class is gone (DG); Changed
* getPreviousDayOfWeek(),
* getFollowingDayOfWeek() and
* getNearestDayOfWeek() to correct bugs (DG);
* 05-Dec-2001 : Fixed bug in SpreadsheetDate class (DG);
* 29-May-2002 : Moved the month constants into a separate
* interface (MonthConstants) (DG);
*/
Comments (bad)
• Noise Comments
/**
* Default constructor.
*/
protected AnnualDateRule() {
}
/**
* The day of the month.
*/
private int dayOfMonth;
/**
* Returns the day of the month.
* @return the day of the month.
*/
public int getDayOfMonth() {
return dayOfMonth;
}
Comments (bad)
• Scary Noise
/**
* The name.
*/
private String name;
/**
* The version.
*/
private String version;
/**
* The licenceName.
*/
private String licenceName;
/**
* The version.
*/
private String info;
Comments (bad)
• Position Markers
// Actions //////////////////////////////////
//End of Actions ///////////////////////////
Comments (bad)
• All sort of funny comments and stupid code
// For the sins I am about to commit, may James Gosling forgive me
// If this code works, it was written by Ifnu.
// If not, I don’t know who wrote it
Exception up = new Exception(“Something is really wrong.”);
throw up; //ha ha
//When I wrote this, only God and I understood what I was doing
//Now, God only knows
// I dedicate all this code, all my work, to my wife, Dian, who will
// have to support me and our two children and the cupang once it gets
// released into the public.
• All sort of funny comment and stupid code
//Dear future me. Please forgive me.
//I can’t even begin to express how sorry I am.
// Magic. Do not touch.
return 1; # returns 1
/////////////////////////////////////// this is a well
commented line
// I am not sure if we need this, but too scared to
delete.
// I am not responsible of this code.
// They made me write it, against my will.
// If I from the future read this I’ll back in time and
kill myself.
Unit Test
• Mengetes logic aplikasi secara otomatis dan
berulang-ulang
• Menghindarkan developer mengetes dengan
manual menggunkan mata
• Menghindari “regression bug”: mengubah
satu kode membuat kode lain jadi error
Unit Test
• Membuat developer percaya diri untuk
melakukan refactoring karena ada Unit Testing
• Digunakan secara luas sebagai ukuran internal
code quality
• JUnit secara de facto diterima sebagai tools
untuk Unit Testing di Java
Unit Test
Demo
Unit Test
• Buat kode untuk melakukan grading dari nilai
0-100 menjadi grade A-D
Agile, Clean Code, Refactor, Automation Test
We Are Hiring!!
THANK YOU

More Related Content

What's hot

Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
YeurDreamin'
 
Clean Code
Clean CodeClean Code
Clean Code
Dmytro Turskyi
 
Clean Code
Clean CodeClean Code
Clean Code
Hendrik Ebel
 
Clean Code
Clean CodeClean Code
Clean Code
Victor Rentea
 
Clean code
Clean codeClean code
Clean code
Mahmoud Zizo
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
Angel Garcia Olloqui
 
Clean code
Clean code Clean code
Clean code
Achintya Kumar
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
Paul Nguyen
 
Clean code
Clean codeClean code
Clean code
Knoldus Inc.
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
Victor Rentea
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
Bhavin Gandhi
 
Clean Code
Clean CodeClean Code
Clean Code
swaraj Patil
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
Victor Rentea
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
Victor Rentea
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Asim Rais Siddiqui
 
Clean Code
Clean CodeClean Code
Clean Code
Luigi De Russis
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
Geshan Manandhar
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
Victor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
Victor Rentea
 

What's hot (20)

Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Clean code
Clean code Clean code
Clean code
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Clean code
Clean codeClean code
Clean code
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Clean Code
Clean CodeClean Code
Clean Code
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
Clean Code
Clean CodeClean Code
Clean Code
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 

Similar to Clean code

Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
Fredrik Wendt
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
Gianluca Padovani
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2R. herves. clean code (theme)2
R. herves. clean code (theme)2
saber tabatabaee
 
Commenting in Agile Development
Commenting in Agile DevelopmentCommenting in Agile Development
Commenting in Agile DevelopmentJan Rybák Benetka
 
Static analysis works for mission-critical systems, why not yours?
Static analysis works for mission-critical systems, why not yours? Static analysis works for mission-critical systems, why not yours?
Static analysis works for mission-critical systems, why not yours?
Rogue Wave Software
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)
Gianluca Padovani
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
The Ring programming language version 1.10 book - Part 7 of 212
The Ring programming language version 1.10 book - Part 7 of 212The Ring programming language version 1.10 book - Part 7 of 212
The Ring programming language version 1.10 book - Part 7 of 212
Mahmoud Samir Fayed
 
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Igalia
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software ValidationJames Pascoe
 
Javascript done right - Open Web Camp III
Javascript done right - Open Web Camp IIIJavascript done right - Open Web Camp III
Javascript done right - Open Web Camp IIIDirk Ginader
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
Saeid Zebardast
 
Your Own Metric System
Your Own Metric SystemYour Own Metric System
Your Own Metric System
Erin Dees
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
Golang
GolangGolang
Golang
Felipe Mamud
 
Fuzzing - Part 1
Fuzzing - Part 1Fuzzing - Part 1
Fuzzing - Part 1
UTD Computer Security Group
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
Md. Aftab Uddin Kajal
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier
Christian Hujer
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Fwdays
 

Similar to Clean code (20)

Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2R. herves. clean code (theme)2
R. herves. clean code (theme)2
 
Commenting in Agile Development
Commenting in Agile DevelopmentCommenting in Agile Development
Commenting in Agile Development
 
Static analysis works for mission-critical systems, why not yours?
Static analysis works for mission-critical systems, why not yours? Static analysis works for mission-critical systems, why not yours?
Static analysis works for mission-critical systems, why not yours?
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)
 
Clean Code
Clean CodeClean Code
Clean Code
 
The Ring programming language version 1.10 book - Part 7 of 212
The Ring programming language version 1.10 book - Part 7 of 212The Ring programming language version 1.10 book - Part 7 of 212
The Ring programming language version 1.10 book - Part 7 of 212
 
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software Validation
 
Javascript done right - Open Web Camp III
Javascript done right - Open Web Camp IIIJavascript done right - Open Web Camp III
Javascript done right - Open Web Camp III
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 
Your Own Metric System
Your Own Metric SystemYour Own Metric System
Your Own Metric System
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Golang
GolangGolang
Golang
 
Fuzzing - Part 1
Fuzzing - Part 1Fuzzing - Part 1
Fuzzing - Part 1
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
Алексей Ященко и Ярослав Волощук "False simplicity of front-end applications"
 

More from ifnu bima

Northstar Metrics and OKR
Northstar Metrics and OKRNorthstar Metrics and OKR
Northstar Metrics and OKR
ifnu bima
 
A brief history of metrics
A brief history of metricsA brief history of metrics
A brief history of metrics
ifnu bima
 
Blibli.com Technology Team
Blibli.com Technology TeamBlibli.com Technology Team
Blibli.com Technology Team
ifnu bima
 
IT Today IPB 2017 : bring new era of business with e-commerce
IT Today IPB 2017 : bring new era of business with e-commerceIT Today IPB 2017 : bring new era of business with e-commerce
IT Today IPB 2017 : bring new era of business with e-commerce
ifnu bima
 
Our Battle Against Technical Debt
Our Battle Against Technical DebtOur Battle Against Technical Debt
Our Battle Against Technical Debt
ifnu bima
 
Architecting for Hyper Growth and Great Engineering Culture
Architecting for Hyper Growth and Great Engineering CultureArchitecting for Hyper Growth and Great Engineering Culture
Architecting for Hyper Growth and Great Engineering Cultureifnu bima
 
Lesson learned in developing UI and mobile apps blibli.com
Lesson learned in developing UI and mobile apps blibli.comLesson learned in developing UI and mobile apps blibli.com
Lesson learned in developing UI and mobile apps blibli.comifnu bima
 
java-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPB
java-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPBjava-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPB
java-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPBifnu bima
 
Development di Blibli
Development di BlibliDevelopment di Blibli
Development di Blibliifnu bima
 
solr @ blibli
solr @ bliblisolr @ blibli
solr @ blibliifnu bima
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
ifnu bima
 
Why Java
Why JavaWhy Java
Why Java
ifnu bima
 
Rembug Presentation
Rembug PresentationRembug Presentation
Rembug Presentation
ifnu bima
 
IT Carier
IT CarierIT Carier
IT Carier
ifnu bima
 
Free Software Foundation,FSF,Opensource
Free Software Foundation,FSF,OpensourceFree Software Foundation,FSF,Opensource
Free Software Foundation,FSF,Opensource
ifnu bima
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Spring
ifnu bima
 

More from ifnu bima (17)

Northstar Metrics and OKR
Northstar Metrics and OKRNorthstar Metrics and OKR
Northstar Metrics and OKR
 
A brief history of metrics
A brief history of metricsA brief history of metrics
A brief history of metrics
 
Blibli.com Technology Team
Blibli.com Technology TeamBlibli.com Technology Team
Blibli.com Technology Team
 
IT Today IPB 2017 : bring new era of business with e-commerce
IT Today IPB 2017 : bring new era of business with e-commerceIT Today IPB 2017 : bring new era of business with e-commerce
IT Today IPB 2017 : bring new era of business with e-commerce
 
Our Battle Against Technical Debt
Our Battle Against Technical DebtOur Battle Against Technical Debt
Our Battle Against Technical Debt
 
Architecting for Hyper Growth and Great Engineering Culture
Architecting for Hyper Growth and Great Engineering CultureArchitecting for Hyper Growth and Great Engineering Culture
Architecting for Hyper Growth and Great Engineering Culture
 
Lesson learned in developing UI and mobile apps blibli.com
Lesson learned in developing UI and mobile apps blibli.comLesson learned in developing UI and mobile apps blibli.com
Lesson learned in developing UI and mobile apps blibli.com
 
java-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPB
java-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPBjava-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPB
java-fundamental-dan-java-web-blibli-dot-com-ilmu-komputer-IPB
 
Development di Blibli
Development di BlibliDevelopment di Blibli
Development di Blibli
 
solr @ blibli
solr @ bliblisolr @ blibli
solr @ blibli
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
 
Why Java
Why JavaWhy Java
Why Java
 
Rembug Presentation
Rembug PresentationRembug Presentation
Rembug Presentation
 
IT Carier
IT CarierIT Carier
IT Carier
 
Free Software Foundation,FSF,Opensource
Free Software Foundation,FSF,OpensourceFree Software Foundation,FSF,Opensource
Free Software Foundation,FSF,Opensource
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Spring
 

Recently uploaded

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 

Recently uploaded (20)

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 

Clean code

  • 1. Kuliah umum OOP, Computer Science IPB Ifnu, 28 Maret 2017
  • 2. Who am I? • Ifnu Bima • Ilmu Komputer IPB, 38 • Join blibli in 2012 • Was working for Deustche Bank Singapore • Employee no 69 • Engineers no ~13 • Development Manager – blibli.com Web UI – Mobile Apps : Android, iOS, Windows Phone – Content Management System – Search – Product Discovery : Wishlist, Product Review
  • 4. Survey Ingin bekerja sebagai Software Developer seumur hidup?
  • 5. Clean Code Agenda • Code Quality – External quality – Internal quality • Clean Code – Meaningful Names – High quality function – Comments – Unit Test
  • 7. Robert C. Martin (Uncle Bob) Book
  • 8. External Quality • Easy to use Application • Zero bug • Fast • Scalable
  • 9. Internal Code Quality • Readable • Mantainable • Testable • Elegant
  • 10. Why do we care? • There’s no such thing as write-once code • Code written, read & modified hundreds times
  • 11. Why do we care? • Bug Fixes • Business Changes • Enhancements • New Functionality
  • 12. What Prevents Clean Code? • Ignorance • Stubbornness • Short-Timer Syndrome • Arrogance • Job Security • Scheduling, Deadline Driven Development
  • 13. What Prevents Clean Code? Number one reason: “I’ll clean it up later.” “Ahh, gampang, ntar aja, yang penting beres dulu”
  • 14. The Truth about Clean Code • Clean Code saves time. • We can’t take a short-term view of software. • We need to look at the lifespan of the application.
  • 15. How Do You Write Clean Code? Rule of Thumb: Imagine that the developer who comes after you is a homicidal maniac who knows where you live. -Unknown
  • 16. The next developer The next developer that mantain code you write
  • 18. Clean Code : Maningful Names
  • 19. Clean Code : Meaningful Names • Intention-Revealing Names • Self Explained Names • theList, x1, y1, i, j, k, index – Not very good • productList, indexOfProductList – A bit better
  • 20. Intention-Revealing Names : Bad List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) { if (x[0] == 4) { list1.add(x); } } return list1; }
  • 21. Intention-Revealing Names : Good List<Cell> getFlaggedCells() { List<Cell> flaggedCells = new ArrayList<Cell>(); for (Cell cell : gameBoard) { if (cell.isFlagged()) { flaggedCells.add(cell); } } return flaggedCells; }
  • 22. Clean Code : Meaningful Names • Avoid Disinformation int a = l; if (O == l) a = O1; else l = 01; • Make Meaningful Distinctions public static void copyChars(char a1[], char a2[]) { for (int i = 0; i < a1.length; i++) { a2[i] = a1[i]; } }
  • 23. Meaningful Names • Use Pronounceable Names : Bad class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /* ... */ } • Use Pronounceable Names : Good class Customer { private Date generationTimestamp; private Date modificationTimestamp; private final String recordId = "102"; /* ... */ }; }
  • 24. Meaningful Names • Use Searchable Names : Bad for (int j = 0; j < 34; j++) { s += (t[j] * 4) / 5; } • Use Searchable Names : Good int realDaysPerIdealDay = 4;const int WORK_DAYS_PER_WEEK = 5; int sum = 0; for (int j = 0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] * realDaysPerIdealDay; int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; }
  • 25. Meaningful Names • Avoid mental mapping : Bad for (i = 0; i < arr.length; i++) { for (j = i; j < arr.length; j++) { //bubble sort } } • Dont try to be funny : Bad public void canggih() { //TODO }
  • 26. Meaningful Names • Code Convention • Class should be noun • Method should be verb
  • 27. High Quality Function • Small! • rules of functions: 1. should be small 2. should be smaller than that • < 150 characters per line • < 20 lines • Do One Thing 1. FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. 2. THEY SHOULD DO IT ONLY.
  • 28. High Quality Function • DRY : Dont repeat yourself – Copy paste code everywhere is root of all evil in software
  • 29. Comments • Do Not Make Up for Bad Code – don’t comment bad code, rewrite it! //edan ini kode siapa yang bikin!! for (int j = 0; j < 34; j++) { s += (t[j] * 4) / 5; } • Explain yourself in code // Check to see if the employee is eligible for full // benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) { if (employee.isEligibleForFullBenefits()) { } }
  • 30. Comments (good) • Legal Comments // Copyright (C) 2017 by blibli.com. All rights reserved. // Released under the terms of the GNU General Public License // version 2 or later • Informative Comments // Returns an instance of the Responder being tested. protected abstract Responder responderInstance(); // format matched kk:mm:ss EEE, MMM dd, yyyy Pattern timeMatcher = Pattern.compile( "d*:d*:d* w*, w* d*, d*");
  • 31. Comments (good) • Explanation of Intent //This is our best attempt to get a race condition //by creating large number of threads. for (int i = 0; i < 25000; i++) { WidgetBuilderThread widgetBuilderThread = new WidgetBuilderThread( widgetBuilder, text, failFlag); Thread thread = new Thread(widgetBuilderThread); thread.start(); }
  • 32. Comments (good) • Clarification assertTrue(a.compareTo(b) == -1); // a < b assertTrue(b.compareTo(a) == 1); // b > a • Warning of Consequences public static SimpleDateFormat makeStandardHttpDateFormat() { //SimpleDateFormat is not thread safe, //so we need to create each instance independently. SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy"); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df; }
  • 33. Comments (good) • TODO Comments //TODO - MdM these are not needed //We expect this to go away when we do the checkout model • Amplification String listItemContent = match.group(3).trim(); // the trim is real important. It removes the starting // spaces that could cause the item to be recognized // as another list. new ListItemWidget(this, listItemContent, this.level + 1); return buildList(text.substring(match.end()));
  • 34. Comments (bad) • Mumbling try { String propertiesPath = propertiesLocation + "/" + PROPERTIES_FILE; FileInputStream propertiesStream = new FileInputStream(propertiesPath); loadedProperties.load(propertiesStream); } catch (IOException e) { // No properties files means all defaults are loaded }
  • 35. Comments (bad) • Redundant Comments /** * The processor delay for this component. */ protected int backgroundProcessorDelay = -1; /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this); /** * The container event listeners for this Container. */ protected ArrayList listeners = new ArrayList();
  • 36. Comments (bad) • Mandated Comments /** * @param title The title of the CD * @param author The author of the CD * @param tracks The number of tracks on the CD * @param durationInMinutes The duration of the CD in minutes */ public void addCD(String title, String author, int tracks, int durationInMinutes) { CD cd = new CD(); cd.title = title; cd.author = author; cd.tracks = tracks; cd.duration = durationInMinutes; }
  • 37. Comments (bad) • Journal Comments /** Changes (from 11-Oct-2001) * -------------------------- * 11-Oct-2001 : Re-organised the class and moved it to new * package com.jrefinery.date (DG); * 05-Nov-2001 : Added a getDescription() method, and * eliminated NotableDate class (DG); * 12-Nov-2001 : IBD requires setDescription() method, now * that NotableDate class is gone (DG); Changed * getPreviousDayOfWeek(), * getFollowingDayOfWeek() and * getNearestDayOfWeek() to correct bugs (DG); * 05-Dec-2001 : Fixed bug in SpreadsheetDate class (DG); * 29-May-2002 : Moved the month constants into a separate * interface (MonthConstants) (DG); */
  • 38. Comments (bad) • Noise Comments /** * Default constructor. */ protected AnnualDateRule() { } /** * The day of the month. */ private int dayOfMonth; /** * Returns the day of the month. * @return the day of the month. */ public int getDayOfMonth() { return dayOfMonth; }
  • 39. Comments (bad) • Scary Noise /** * The name. */ private String name; /** * The version. */ private String version; /** * The licenceName. */ private String licenceName; /** * The version. */ private String info;
  • 40. Comments (bad) • Position Markers // Actions ////////////////////////////////// //End of Actions ///////////////////////////
  • 41. Comments (bad) • All sort of funny comments and stupid code // For the sins I am about to commit, may James Gosling forgive me // If this code works, it was written by Ifnu. // If not, I don’t know who wrote it Exception up = new Exception(“Something is really wrong.”); throw up; //ha ha //When I wrote this, only God and I understood what I was doing //Now, God only knows // I dedicate all this code, all my work, to my wife, Dian, who will // have to support me and our two children and the cupang once it gets // released into the public.
  • 42. • All sort of funny comment and stupid code //Dear future me. Please forgive me. //I can’t even begin to express how sorry I am. // Magic. Do not touch. return 1; # returns 1 /////////////////////////////////////// this is a well commented line // I am not sure if we need this, but too scared to delete. // I am not responsible of this code. // They made me write it, against my will. // If I from the future read this I’ll back in time and kill myself.
  • 43. Unit Test • Mengetes logic aplikasi secara otomatis dan berulang-ulang • Menghindarkan developer mengetes dengan manual menggunkan mata • Menghindari “regression bug”: mengubah satu kode membuat kode lain jadi error
  • 44. Unit Test • Membuat developer percaya diri untuk melakukan refactoring karena ada Unit Testing • Digunakan secara luas sebagai ukuran internal code quality • JUnit secara de facto diterima sebagai tools untuk Unit Testing di Java
  • 46. Unit Test • Buat kode untuk melakukan grading dari nilai 0-100 menjadi grade A-D
  • 47. Agile, Clean Code, Refactor, Automation Test