C LEAN CODE Predrag Danulabs, 2014. O VERVIEW Introduction Meaningful Names Functions Comments Formatting C# Standards and Conventions.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Software Engineering Reading Group: Clean Code Chapter 4 Led by Nicholas Vaidyanathan Lead Visionary, Visionary Software.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
Procedural programming in Java
Chapter 1: Computer Systems
Programming with Java. Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: –Understand the.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
1 Java Programming Basics SE-1011 Dr. Mark L. Hornick.
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
Coding Standards for Java An Introduction. Why Coding Standards are Important? Coding Standards lead to greater consistency within your code and the code.
Software Engineering Reading Group: Clean Code Chapter 3 Led by Nicholas Vaidyanathan Lead Visionary, Visionary Software.
Software Engineering Reading Group: Clean Code Chapter 2 Led by Nicholas Vaidyanathan Lead Visionary, Visionary Software.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
Copyright 2013 by Pearson Education Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Clean Code III Functions Object Mentor, Inc. Copyright  2008 by Object Mentor, Inc All Rights Reserved objectmentor.com Robert C. Martin.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Java: Chapter 1 Computer Systems Computer Programming II.
Java Language and SW Dev’t
Testing CSE 140 University of Washington 1. Testing Programming to analyze data is powerful It’s useless if the results are not correct Correctness is.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
The Java Programming Language
CSC204 – Programming I Lecture 4 August 28, 2002.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
CPS120: Introduction to Computer Science
CIT 590 Intro to Programming First lecture on Java.
Java Coding Standards and Best Practices Coding Standards Introduction: After completing this chapter, you will able to keep your code up to standards.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Applications Development
Programming with Microsoft Visual Basic th Edition
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
CPS120: Introduction to Computer Science Variables and Constants.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Written by: Dr. JJ Shepherd
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Clean Code Maciej Grabek Software Engineer | Holte Software Poland.
Copyright 2010 by Pearson Education APCS Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading:
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Variable Scope & Lifetime
Bill Tucker Austin Community College COSC 1315
The need for Programming Languages
A variable is a name for a value stored in memory.
Working with Java.
CS1022 Computer Programming & Principles
Introduction To Repetition The for loop
Testing UW CSE 160 Winter 2017.
The Pseudocode Programming Process
University of Central Florida COP 3330 Object Oriented Programming
About the Presentations
Testing UW CSE 160 Spring 2018.
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Testing UW CSE 160 Winter 2016.
Introduction to Java Programming
Variables ICS2O.
Chapter 1: Computer Systems
Focus of the Course Object-Oriented Software Development
Programming Introduction to C++.
Coding practices For IT and Computing students 2014.
Chap 2. Identifiers, Keywords, and Types
Variables in C Topics Naming Variables Declaring Variables
Arrays.
Presentation transcript:

C LEAN CODE Predrag Danulabs, 2014

O VERVIEW Introduction Meaningful Names Functions Comments Formatting C# Standards and Conventions

I NTRODUCTION You are here for two reasons: You are programmers You want to be better programmers

I NTRODUCTION Learning craftsmanship: Knowledge and work Learning to write clean code requires: Knowledge of principles and patterns Practice yourself Watch yourself fail Watch others practice it and fail See them stumble and retrace their steps

M EANINGFUL N AMES Use Intention-Revealing Names Take care with your names and change them when you find better ones The names should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.

M EANINGFUL N AMES Example 1: public List getThem() { List list1 = new ArrayList (); for (int[] x : theList) if (x[0] == 4) list1.add(x); return list1; } Questions: 1. What kinds of things are in theList? 2. What is the significance of the zeroth subscript of an item in theList? 3. What is the significance of the value 4? 4. How would I use the list being returned? Example 2: public List getFlaggedCells() { List flaggedCells = new ArrayList (); for (int[] cell : gameBoard) if (cell[STATUS_VALUE] == FLAGGED) flaggedCells.add(cell); return flaggedCells; }

M EANINGFUL N AMES Avoid Disinformation Avoid words whose entrenched meanings vary from our intended meaning Do not refer to a grouping of accounts as an accountList unless it’s actually a List. Use ( accountGroup or accounts ) Beware of using names which vary in small ways XYZControllerForEfficientHandlingOfStrings XYZControllerForEfficientStorageOfStrings

M EANINGFUL N AMES Make Meaningful Distinctions Number-series naming ( a1, a2,.. aN ) is the opposite of intentional naming Noise words are another meaningless distinction Product, ProductInfo, ProductData Use Pronounceable Names private Date genymdhms; private Date modymdhms; or private Date generationTimestamp; private Date modificationTimestamp;

M EANINGFUL N AMES Use Searchable Names Avoid: single letter names numeric constants Example: for (int j=0; j<34; j++) { s += (t[j]*4)/5; } or int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; for (int j=0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] * realDaysPerIdealDay; int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; }

M EANINGFUL N AMES Hungarian notation PhoneNumber phoneString; // name not changed when type changed! Class Names noun Method Names verb Pick One Word per Concept fetch, retreive, get Use Solution Domain Names People who read your code will be programmers. So go ahead and use computer science (CS) terms

M EANINGFUL N AMES Avoid Mental Mapping “One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.”

M EANINGFUL N AMES Add Meaningful Context Context: firstname, lastname, street, city, state Context: state Solution: Class Address adrState Don’t Add Gratuitous Context GSDAccountAddress (“ Gas Station Deluxe”)

F UNCTIONS Size They should be small They should be smaller than that History 80s – one screen ( 24(-4) lines 80 columns) 2010s – one screen (100 lines 150 characters) Functions should hardly ever been 20 lines long

F UNCTIONS Size Blocks and indenting If, else, while should be one line long Probably function call with descriptive name Do one thing “FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY.”

F UNCTIONS What is one thing? public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite) throws Exception { if (isTestPage(pageData)) includeSetupAndTeardownPages(pageData, isSuite); return pageData.getHtml(); } 1. Determining whether the page is a test page. 2. If so, including setups and teardowns. 3. Rendering the page in HTML. Three steps of the function are one level of abstraction below the stated name of the function Describing “To” paragraph: “TO RenderPageWithSetupsAndTeardowns, we check to see whether the page is a test page and if so, we include the setups and teardowns. In either case we render the page in HTML. “

F UNCTIONS Reading Code from Top to Bottom The Stepdown Rule Switch Statements public Money calculatePay(Employee e) throws InvalidEmployeeType { switch (e.type) { case COMMISSIONED: return calculateCommissionedPay(e); case HOURLY: return calculateHourlyPay(e); case SALARIED: return calculateSalariedPay(e); default: throw new InvalidEmployeeType(e.type); }

F UNCTIONS Switch Statements Problems Large It will grow when new type is added Does more than one thing Violates Single Responsibility Principle Unlimited number of other functions with same structure Use AbstractFactory

F UNCTIONS Switch Statements Employee and Factory public abstract class Employee { public abstract boolean isPayday(); public abstract Money calculatePay(); public abstract void deliverPay(Money pay); } public interface EmployeeFactory { public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType; } public class EmployeeFactoryImpl implements EmployeeFactory { public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType { switch (r.type) { case COMMISSIONED: return new CommissionedEmployee(r) ; case HOURLY: return new HourlyEmployee(r); case SALARIED: return new SalariedEmploye(r); default: throw new InvalidEmployeeType(r.type); }

F UNCTIONS Use Descriptive Names “ You know you are working on clean code when each routine turns out to be pretty much what you expected. ” The smaller and more focused a function is, the easier it is to choose a descriptive name A long descriptive name is better than a short enigmatic name. A long descriptive name is better than a long descriptive comment

F UNCTIONS Function Arguments Ideal is 0 (niladic), then 1 (monadic), then 2 (dyadic), then 3 (triadic). More is unacceptable (create new class) Flag Arguments Avoid (function do 2 things, avoid mouse over) Make two functions with meaningful names

F UNCTIONS Have No Side Effects public boolean checkPassword(String userName, String password) { User user = UserGateway.findByName(userName); if (user != User.NULL) { String codedPhrase = user.getPhraseEncodedByPassword(); String phrase = cryptographer.decrypt(codedPhrase, password); if ("Valid Password".equals(phrase)) { Session.initialize(); return true; } return false; } checkPasswordAndInitializeSession ? Output arguments public void appendFooter(StringBuffer report) report.appendFooter();

F UNCTIONS Command Query Separation Functions should: do something or answer something don’t both Example: public boolean set(String attribute, String value); if (set("username", "unclebob")) Prefer Exceptions to Returning Error Codes Error Handling Is One Thing (one function) Don’t Repeat Yourself

F UNCTIONS Structured Programming Dijkstra said, ”Every function, and every block, should have one entry and one exit”. This means that there should only be one return statement in a function, no break or continue statements in a loop, and never, ever, any goto statements. If you keep your functions small, then there is no problem to break this rule

F UNCTIONS Conclusion Writing software is like any other kind of writing. You wordsmith it and restructure it and refine it until it reads the way you want it to read. So then refine that code, splitting out functions, changing names, eliminating duplication. Shrink the methods and reorder them. Sometimes break out whole classes, all the while keeping the tests passing. Never forget that your real goal is to tell the story of the system, and that the functions you write need to fit cleanly together into a clear and precise language to help you with that telling.

C OMMENTS “ Don’t comment bad code—rewrite it.” Nothing can be quite so helpful as a well-placed comment. Nothing can clutter up a module more than frivolous dogmatic comments. Nothing can be quite so damaging as an old crufty comment that propagates lies and misinformation

C OMMENTS Comments compensates our failure to express ourself in code. When you find yourself in a position where you need to write a comment, think it through and see whether there isn’t some way to express yourself in code Truth can only be found in one place: the code // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) &&(employee.age > 65)) Or if (employee.isEligibleForFullBenefits())

G OOD COMMENTS Legal Comments // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. Informative Comments // format matched kk:mm:ss EEE, MMM dd, yyyy Pattern timeMatcher = Pattern.compile("\\d*:\\d*:\\d* \\w*, \\w* \\d*, \\d*"); Explanation of Intent Comparison function Clarification assertTrue(a.compareTo(a) == 0); // a == a assertTrue(a.compareTo(b) != 0); // a != b assertTrue(ab.compareTo(ab) == 0); // ab == ab

G OOD COMMENTS Warning of Consequences // Don't run unless you // have some time to kill. public void _testWithReallyBigFile() TODO Comments 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.

B AD C OMMENTS Mumbling catch(IOException e) { // No properties files means all defaults are loaded } Redundant Comments // Utility method that returns when this.closed is true. Throws an exception // if the timeout is reached. public synchronized void waitForClose(final long timeoutMillis) throws Exception { if(!closed) { wait(timeoutMillis); if(!closed) throw new Exception("MockResponseSender could not be closed"); }

B AD C OMMENTS Misleading Comments Mandated Comments Rule that says that every function must have a javadoc, or every variable must have a comment Journal Comments Log of a repository? Noise Comments /** * Default constructor. */ protected AnnualDateRule() {

B AD C OMMENTS Position Markers // Actions ////////////////////////////////// Closing Brace Comments Functions are to long Commented-Out Code Just don’t do this!!! Too Much Information

F ORMATING First rule: Let’s be clear “Code formatting is about communication, and communication is the professional developer’s first order of business.”

F ORMATING Vertical Formatting The Newspaper Metaphor Write code like newspaper article (General description on the top and detailed on the bottom) Vertical Openness Between Concepts Each blank line is a visual cue that identifies a new and separate concept. As you scan down the listing, your eye is drawn to the first line that follows a blank line. Vertical Density vertical density implies close association don’t break it with unimportant blank lines and comments

F ORMATING Vertical formatting Vertical Distance Concepts that are closely related should be kept vertically close to each other Variable Declarations close to their usage top of the function before loops or blocks Instance variables Well known place (top or bottom) Dependent Functions Conceptual Affinity

F ORMATING Horizontal formatting you should never have to scroll to the right average limit is ~120 Horizontal Openness and Density Horizontal Alignment Indentation Team Rules

O THER CONCEPTS Object and Data Structures Error Handling Concurrency Unit tests ….

C# S TANDARDS