Writing Beautiful Code. Anand Chitipothu

Similar documents
Database Programming Style Guidelines

WRITING QUALITY CODE IDEAS, TECHNIQUES AND TOOLS FOR IMPROVING THE QUALITY OF WRITTEN CODE

Sardar Patel University S Y BSc. Computer Science CS-201 Introduction to Programming Language Effective from July-2002

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Big Data XML Parsing in Pentaho Data Integration (PDI)

Smaller, simpler, subcomponent of program Provides abstraction

M275 - Web Development using PHP and MySQL

Write for your audience

Lab Manual Access Module

Spring 2017 CS 1110/1111 Exam 3

CS101 Lecture 30: How Search Works and searching algorithms.

Package httpcache. October 17, 2017

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

(the bubble footer is automatically inserted into this space)

Spring 2017 CS 1110/1111 Exam 2

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

SDMX self-learning package No. 3 Student book. SDMX-ML Messages

Sorting is a problem for which we can prove a non-trivial lower bound.

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation.

Structural Text Features. Structural Features

Overview: Understanding the Toolbox

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CS 111X - Spring Final Exam - KEY

Beginning Style. 16-Nov-15

EECS 311 Data Structures Midterm Exam Don t Panic!

#o o

2. Don t forget semicolons and RUN statements The two most common programming errors.

Microsoft Excel Level 2

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Fortran Coding Standards and Style

ORACLE TRAINING CURRICULUM. Relational Databases and Relational Database Management Systems

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

CA Productivity Accelerator 12.1 and Later

2. You are required to enter a password of up to 100 characters. The characters must be lower ASCII, printing characters.

Chapter 11: Going All Out with FrontPage

Clean code. Why? What is "clean code"? Bjarne Stroustrup. Grady Booch. Dave Thomas. 1 z 5. Petr Pošík. Department of Cybernetics, FEE CTU in Prague

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Information Retrieval

CSV Files & Breeze User Guide Version 1.3

django-simple-sms Documentation

Python for C programmers

CPSC 217 Midterm (Python 3 version)

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

frameset rows cols <frameset> rows cols

peval Documentation Release Bogdan Opanchuk

CS 373: Combinatorial Algorithms, Spring 1999

8. Control statements

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Data Abstraction. UW CSE 160 Spring 2015

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

The American University in Cairo. Academic Computing Services. Excel prepared by. Maha Amer

XQ: An XML Query Language Language Reference Manual

Computational Physics - Fortran February 1997

Bourne Shell Reference

Variables, expressions and statements

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

$99.95 per user. SQL Server 2008 Integration Services CourseId: 158 Skill level: Run Time: 42+ hours (210 videos)

Object-Oriented Analysis and Design

APPENDIX A : Example Standard <--Prev page Next page -->

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

UPLOAD DOC OR USING PHP STACK OVERFLOW


Agent-Enabling Transformation of E-Commerce Portals with Web Services

Test #2 October 8, 2015

Release Notes.

Computer Systems C S Cynthia Lee Today s materials adapted from Kevin Webb at Swarthmore College

CSC148-Section:L0301

User Interface Design. Interface Design 4. User Interface Design. User Interface Design. User Interface Design. User Interface Design

Lecture 7 Tao Wang 1

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

Tips & Tricks. With lots of help from other SUG and SUGI presenters. SAS HUG Meeting, November 18, 2010

Functions. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

Artificial Intelligence Lecture 1

Structure and Interpretation of Computer Programs

Review: Cohesion and Coupling, Mutable, Inheritance Screen Layouts. Object-Oriented Design CRC Cards - UML class diagrams

Cisco IOS ISO Connectionless Network Service Commands

CS140 Operating Systems and Systems Programming Final Exam

How to speed up a database which has gotten slow

Data Transfer Utility Transfer Strategies

Short Answer Questions (40 points)

Do not start the test until instructed to do so!

Object-Oriented Software Engineering Practical Software Development using UML and Java

Data visualization with kdb+ using ODBC

Enhancing a text collection with a document-oriented database model

SML: Specialized Matrix Language White Paper

WEB ANALYTICS A REPORTING APPROACH

Final Exam Solutions. Structure and Interpretation of Computer Programs. Fall 2011 /12 /16 /12 /18 /10 /12 /80 INSTRUCTIONS

CSV Roll Documentation

Agilent E2929A/B Opt. 200 PCI-X Performance Optimizer. User s Guide

CSC148 Fall 2017 Ramp Up Session Reference

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

URL Signing and Validation

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Writer 5.4 Guide. Chapter 12 Lists: Tips and Tricks

3. Almost always use system options options compress =yes nocenter; /* mostly use */ options ps=9999 ls=200;

Cache Coherence Tutorial

Tutorial: Functions and Functional Abstraction. Nathaniel Osgood CMPT

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Transcription:

Writing Beautiful Code Anand Chitipothu

quality without a name

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity. - The Tao of Programming

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity. - The Tao of Programming

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity. - The Tao of Programming

Programs must be written for people to read, and only incidentally for machines to execute. - Structure and Interpretation of Computer Programs (The Wizard Book)

Choose Meaningful Names

Two hard things in computer science are cache invalidation and naming things. - Phil Karlton

Avoid Generic Names tmp tmp2 manager data

Avoid Abbreviations ucf = UpperCaseFormatter() ba = BankAccount() formatter = UpperCaseFormatter() account = BankAccount()

Avoid using datatype as name sum(list) count_words(string) sum(numbers) count_words(sentence)

Nouns & Verbs Use nouns for variables and classes. size, price, Task, Scheduler, Bank Account Use verbs for functions. get_file_size, make_account, deposit

Use plural for a list largest_line(lines) files = os.listdir(directory) file = os.listdir(directory) for lines in open(filename).readlines(): sum += int(lines)

Reserve Loop Indexes Use i, j only as loop indexes. for i in range(10): print i for i in numbers: result += i for n in numbers: result += n

Example 1 Can you improve this? def get_data(x, y): z = [] for i in x: z.append(i[y]) return z

Example 1 def get_column(dataset, col_index): column = [] for row in dataset: column.append(row[col_index]) return column

Similar names Never use similar names for completely different datatypes. a1 = [1, 2, 3] a2 = len(x) values = [1, 2, 3] n = len(x)

Program Organization

Divide & Conquer Split the program into small independent modules and functions.

The 7 ± 2 Rule The number of objects an average human can hold in working memory is 7 ± 2. - Miller's Law

Avoid too many nested levels def update_post(...): post = get_post(..) if action == 'update-title': if title == '':... else:... elif action == "add-tag":...

Avoid too many nested levels def update_post(...): post = get_post(..) if action == "update-title": update_post_title(...) elif action == "add-tag": update_post_add_tag(...)

Separate what and how def main(): filename = sys.argv[1] words = read_words(filename) freq = wordfreq(words) print_freq(freq)

Handle errors separately def get_user(email): if valid_user(email): if is_user_blocked(email): return Exception("Account is blocked") else: query = "..." row = db.select(query).first() return User(row) else: raise Exception("Invalid email")

Handle errors separately def get_user(email): if not valid_user(email): raise ValueError("Invalid email") if is_email_blocked(email): raise Exception("Account blocked") query = "..." row = db.select(query).first() return User(row)

Comments

Don t say the obvious # increments x by 2 x = x + 2 # compensate for border on both the sides x = x + 2

Explain why you made that choice # The following is an optimization to saves # lot of memcache calls. Handle with care!...

Document special cases # -- XXX -- Anand - Sep 2015 -- # UTF-conversion was failing for a chinese # user for reasons I couldn't understand. # Added "ignore" as second argument to handle # that temporarily. name = name.encode("utf-8", "ignore")

Make Comments Unnecessary # find length of the longest line n = max([len(line) for line in lines]) n = len(longest(lines))

Make Comments Unnecessary # process documents # upload them to search engine docs = process_documents(...) search_engine_submit(docs)

Summary Choose meaningful variable names Use smaller functions Separate what from how Always optimize for readability

Questions?