SlideShare una empresa de Scribd logo
1 de 23
Every Programmer Should Know
         Code Reviews
           Roger Xia
           July 2012
$ whoami
• Programmer
Programming & Code review
• Programming is
  – Taking an algorithm
  – Choosing a language
  – Using that language to implement algorithm and
    solve problems


• Code review is
  –?
Why?
•   Increase Quality & Reduce Defects
•   Improve readability
•   Share knowledge in team
•   Know your workmate better!
•   Two Wrongs Can Make a Right

• NOT personal attack!
• NOT architect reviews everything
methodology
• Team review (Planned 1-2 hour/week, Clear
  roles)
• Pair programming (Share knowledge, 1 task)
• Walkthrough (Author leads, reviewers take
  notes, higher level)
• Peer review (Asynchronous)

• Gerrit
• Reaction & Ask questions
Preparation
•   Code Conventions
•   Findbugs
•   Tested
•   Test case
Take care of
• naming convention
     spelling mistakes
• business logic
• refactoring
• performance
• security (attack, thread safe)
Refactoring
• Refactoring modifies software to improve its
  readability, maintainability, and extensibility without changing what
  it actually does.

• Martin Fowler uses “code smells” to identify when to refactor.

• Boss: "Refactoring is an overhead activity - I'm paid to write
  new, revenue generating features."
Code smells
•   Bad names
•   Duplicate code
•   Long method
•   Large class
•   Long parameter list
•   Temporary field
•   Speculative Generality
•   Data Class
•   Don’t flood log
Use Meaningful Names
Meaningful Names
• Class names
   –   Should be nouns or noun phrases.
   –   Examples: Car, Account, DataRetrievalService, AddressParser


• Method names
   –   Should be verb or verbPhrases
   –   Examples: parseData, deletePage, save
   –   Methods that return boolean values should sound like question.
   –   Examples: isAuthenticated, hasNoErrors, isEmpty


• Interface and Implementation
   –   ICache  LRUCache
   –   IExport  ExportService


• Constants
   –   MAX_VALUE
   –   SEP_COMMA, SEP_SEMICOLON
The Art of Readable code
• The book!

• I want to point out:
  – Use blank to separate logic block.
Comments for complex
process, algorithm, reasons
Aiming for simplicity
• Do one thing in a function (simple responsibility)
• Have no side effects.




• Prefer exceptions to return codes.




• Format your code.
DRY -- Don’t repeat yourself

• Duplicated code should be avoided.
• Object Orientation, Abstract!
• Design pattern!
OO Principles
• Simple responsibility principle: Class should have one and
  only one reason to change.

• Encapsulation: Modules should not know internal details of
  objects it manipulates.

• Polymorphism -- Liskov’s substitution principle: A subclass
  can be used as an argument where a base class is expected.

• Open-closed principle: Class should be open for
  extention, but closed for modification.
Design Patterns
Pay Attention to Performance
• JAVA: JVM usage
   – Don’t create object in loop



   – Use ArrayList, HashMap etc as opposed to Vector, Hashtable etc
     (synchronized) where possible. Even better is to use just arrays
     where possible.

   – Set initial capacity of a collection (e.g. ArrayList, HashMap) and
     StringBuffer/StringBuilder appropriately.

   – Concurrent Collection, Lock

   – Lazy load or multi-threading where applicable.

   – Cache (LRUCache, Distributed Cache)
Pay Attention to Performance
Pay Attention to Security
•   Sandbox (security manager, access manager, Classloaders, policies)

•   Scope: Access modifier to help protect your classes, methods, fields.
     – public, protected, private, package
     – Exceptions: object serialization, reflection,

•   Immutable class
     – final
     – String
     – Insecure direct object reference of mutable object

•   Type safe
     – Casting

•   Thread safe

•   OOM (static), file description handler, release resources (File, DBConnection)

•   SQL injection

•   Single point of failure
• secure code
Have Fun and win
http://rosettacode.org/wiki/Rosetta_Code

Más contenido relacionado

La actualidad más candente

Python introduction
Python introductionPython introduction
Python introduction
Roger Xia
 
Executable specifications for xtext
Executable specifications for xtextExecutable specifications for xtext
Executable specifications for xtext
meysholdt
 

La actualidad más candente (20)

Python introduction
Python introductionPython introduction
Python introduction
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 
Executable specifications for xtext
Executable specifications for xtextExecutable specifications for xtext
Executable specifications for xtext
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Type theory in practice
Type theory in practiceType theory in practice
Type theory in practice
 
ANTLR - Writing Parsers the Easy Way
ANTLR - Writing Parsers the Easy WayANTLR - Writing Parsers the Easy Way
ANTLR - Writing Parsers the Easy Way
 
C sharp
C sharpC sharp
C sharp
 
Core java Classroom training at HarshithaTechnologies
Core java Classroom training at HarshithaTechnologiesCore java Classroom training at HarshithaTechnologies
Core java Classroom training at HarshithaTechnologies
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
PHP - Procedural To Object-Oriented
PHP - Procedural To Object-OrientedPHP - Procedural To Object-Oriented
PHP - Procedural To Object-Oriented
 
Building Your Own DSL with Xtext
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with Xtext
 
Agile xml
Agile xmlAgile xml
Agile xml
 
OOPs fundamentals session for freshers in my office (Aug 5, 13)
OOPs fundamentals session for freshers in my office (Aug 5, 13)OOPs fundamentals session for freshers in my office (Aug 5, 13)
OOPs fundamentals session for freshers in my office (Aug 5, 13)
 
Short notes of oop with java
Short notes of oop with javaShort notes of oop with java
Short notes of oop with java
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorial
 
CS8392 OOP
CS8392 OOPCS8392 OOP
CS8392 OOP
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)
 
C# - Igor Ralić
C# - Igor RalićC# - Igor Ralić
C# - Igor Ralić
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java
 

Destacado

E commerce search strategies
E commerce search strategiesE commerce search strategies
E commerce search strategies
Roger Xia
 
机器学习推动金融数据智能
机器学习推动金融数据智能机器学习推动金融数据智能
机器学习推动金融数据智能
Roger Xia
 
Consistency-New-Generation-Databases
Consistency-New-Generation-DatabasesConsistency-New-Generation-Databases
Consistency-New-Generation-Databases
Roger Xia
 
No sql and data scalability
No sql and data scalabilityNo sql and data scalability
No sql and data scalability
Roger Xia
 
Code reviews
Code reviewsCode reviews
Code reviews
Roger Xia
 
Indefero source code_managment
Indefero source code_managmentIndefero source code_managment
Indefero source code_managment
Roger Xia
 

Destacado (18)

Q con london2011-matthewwall-whyichosemongodbforguardiancouk
Q con london2011-matthewwall-whyichosemongodbforguardiancoukQ con london2011-matthewwall-whyichosemongodbforguardiancouk
Q con london2011-matthewwall-whyichosemongodbforguardiancouk
 
JavaEE6
JavaEE6JavaEE6
JavaEE6
 
构建高效能的Web网站 精选版-by-infoq
构建高效能的Web网站 精选版-by-infoq构建高效能的Web网站 精选版-by-infoq
构建高效能的Web网站 精选版-by-infoq
 
E commerce search strategies
E commerce search strategiesE commerce search strategies
E commerce search strategies
 
新浪微博架构猜想
新浪微博架构猜想新浪微博架构猜想
新浪微博架构猜想
 
机器学习推动金融数据智能
机器学习推动金融数据智能机器学习推动金融数据智能
机器学习推动金融数据智能
 
Mongo db实战
Mongo db实战Mongo db实战
Mongo db实战
 
Ajax Lucence
Ajax LucenceAjax Lucence
Ajax Lucence
 
Consistency-New-Generation-Databases
Consistency-New-Generation-DatabasesConsistency-New-Generation-Databases
Consistency-New-Generation-Databases
 
Java explore
Java exploreJava explore
Java explore
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Eclipse plug in mylyn & tasktop
Eclipse plug in mylyn & tasktopEclipse plug in mylyn & tasktop
Eclipse plug in mylyn & tasktop
 
No sql and data scalability
No sql and data scalabilityNo sql and data scalability
No sql and data scalability
 
Code reviews
Code reviewsCode reviews
Code reviews
 
Ca siteminder
Ca siteminderCa siteminder
Ca siteminder
 
MDD and modeling tools research
MDD and modeling tools researchMDD and modeling tools research
MDD and modeling tools research
 
Indefero source code_managment
Indefero source code_managmentIndefero source code_managment
Indefero source code_managment
 
Jenkins
JenkinsJenkins
Jenkins
 

Similar a Code reviews

Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
cobyst
 
Object Oriented PHP Overview
Object Oriented PHP OverviewObject Oriented PHP Overview
Object Oriented PHP Overview
Larry Ball
 

Similar a Code reviews (20)

TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Clean code
Clean codeClean code
Clean code
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovy
 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best Practices
 
Scala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityScala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and quality
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & Architecture
 
Object Oriented PHP Overview
Object Oriented PHP OverviewObject Oriented PHP Overview
Object Oriented PHP Overview
 

Más de Roger Xia (9)

Learning notes ruby
Learning notes rubyLearning notes ruby
Learning notes ruby
 
Converged open platform for enterprise
Converged open platform for enterpriseConverged open platform for enterprise
Converged open platform for enterprise
 
Saml
SamlSaml
Saml
 
Web Services Atomic Transactio
 Web Services Atomic Transactio Web Services Atomic Transactio
Web Services Atomic Transactio
 
Web service through cxf
Web service through cxfWeb service through cxf
Web service through cxf
 
Spring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_dataSpring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_data
 
Fixing twitter
Fixing twitterFixing twitter
Fixing twitter
 
Secure Multi Tenancy In the Cloud
Secure Multi Tenancy In the CloudSecure Multi Tenancy In the Cloud
Secure Multi Tenancy In the Cloud
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

Code reviews

  • 1. Every Programmer Should Know Code Reviews Roger Xia July 2012
  • 3. Programming & Code review • Programming is – Taking an algorithm – Choosing a language – Using that language to implement algorithm and solve problems • Code review is –?
  • 4. Why? • Increase Quality & Reduce Defects • Improve readability • Share knowledge in team • Know your workmate better! • Two Wrongs Can Make a Right • NOT personal attack! • NOT architect reviews everything
  • 5. methodology • Team review (Planned 1-2 hour/week, Clear roles) • Pair programming (Share knowledge, 1 task) • Walkthrough (Author leads, reviewers take notes, higher level) • Peer review (Asynchronous) • Gerrit • Reaction & Ask questions
  • 6.
  • 7. Preparation • Code Conventions • Findbugs • Tested • Test case
  • 8. Take care of • naming convention spelling mistakes • business logic • refactoring • performance • security (attack, thread safe)
  • 9. Refactoring • Refactoring modifies software to improve its readability, maintainability, and extensibility without changing what it actually does. • Martin Fowler uses “code smells” to identify when to refactor. • Boss: "Refactoring is an overhead activity - I'm paid to write new, revenue generating features."
  • 10. Code smells • Bad names • Duplicate code • Long method • Large class • Long parameter list • Temporary field • Speculative Generality • Data Class • Don’t flood log
  • 12. Meaningful Names • Class names – Should be nouns or noun phrases. – Examples: Car, Account, DataRetrievalService, AddressParser • Method names – Should be verb or verbPhrases – Examples: parseData, deletePage, save – Methods that return boolean values should sound like question. – Examples: isAuthenticated, hasNoErrors, isEmpty • Interface and Implementation – ICache  LRUCache – IExport  ExportService • Constants – MAX_VALUE – SEP_COMMA, SEP_SEMICOLON
  • 13. The Art of Readable code • The book! • I want to point out: – Use blank to separate logic block.
  • 14. Comments for complex process, algorithm, reasons
  • 15. Aiming for simplicity • Do one thing in a function (simple responsibility) • Have no side effects. • Prefer exceptions to return codes. • Format your code.
  • 16. DRY -- Don’t repeat yourself • Duplicated code should be avoided. • Object Orientation, Abstract! • Design pattern!
  • 17. OO Principles • Simple responsibility principle: Class should have one and only one reason to change. • Encapsulation: Modules should not know internal details of objects it manipulates. • Polymorphism -- Liskov’s substitution principle: A subclass can be used as an argument where a base class is expected. • Open-closed principle: Class should be open for extention, but closed for modification.
  • 19. Pay Attention to Performance • JAVA: JVM usage – Don’t create object in loop – Use ArrayList, HashMap etc as opposed to Vector, Hashtable etc (synchronized) where possible. Even better is to use just arrays where possible. – Set initial capacity of a collection (e.g. ArrayList, HashMap) and StringBuffer/StringBuilder appropriately. – Concurrent Collection, Lock – Lazy load or multi-threading where applicable. – Cache (LRUCache, Distributed Cache)
  • 20. Pay Attention to Performance
  • 21. Pay Attention to Security • Sandbox (security manager, access manager, Classloaders, policies) • Scope: Access modifier to help protect your classes, methods, fields. – public, protected, private, package – Exceptions: object serialization, reflection, • Immutable class – final – String – Insecure direct object reference of mutable object • Type safe – Casting • Thread safe • OOM (static), file description handler, release resources (File, DBConnection) • SQL injection • Single point of failure
  • 23. Have Fun and win http://rosettacode.org/wiki/Rosetta_Code

Notas del editor

  1. Loose couple:FacadeSpringMessaging
  2. Temporary fieldAn attribute of an object is only set in certain circumstances; but an object should need all of its attributes Speculative Generality“Oh I think we need the ability to do this kind of thing someday” Data ClassThese are classes that have fields, getting and setting methods for the fields, and nothing else; they are data holders, but objects should be about data AND behavior
  3. http://www.slideshare.net/srikanthps/practices-for-becoming-a-better-programmer-presentation
  4. Are we writing comments because our code is unclear?Will you keep the comments up-to-date whenever code is updated?
  5. If there is a bug in the code or code requires changes, then, one has to change it at multiple places.
  6. http://www.lifeyun.com/design-pattern-diagram.html
  7. http://www.artima.com/insidejvm/ed2/jvm2.html
  8. http://www.artima.com/insidejvm/ed2/jvm2.html
  9. Mitigation of serialization:- Don’t extend java.io.serializable- ImplementreadObject and writeObject as final methods that throw IOException- If serialize you must: use transient or use java.io.Externalizeable plus Encryption