Seven Ineffective Coding Habits of Many

Similar documents
Seven Ineffective Coding Habits of Many

5 ineffective. MANY F# programmers. DON T have. coding habits

Programming with GUTs

Programming with GUTs


Small Is Beautiful. A talk on code as if people mattered A talk on code as if economics

Programmer's Dozen. Thirteen Recommendations for Reviewing, Kevlin Henney

Know Your Units TDD, DDT, POUTing and GUTs Kevlin Henney

Good Object- Oriented Development

Turning Development Outside

It Is Possible to Do Object-Oriented Programming in Java

CS159. Nathan Sprague. September 30, 2015

CSE 331 Midterm Exam Sample Solution 2/18/15

SML Style Guide. Last Revised: 31st August 2011

Here is a hierarchy of classes to deal with Input and Output streams.

Writing usable APIs in practice. ACCU 2012 Conference, Oxford, UK Giovanni

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC 1214: Object-Oriented Programming

Exceptions. CSC207 Winter 2017

Five Considerations for Software Architects

Bit level Binaries and Generalized Comprehensions in Erlang. Per Gustafsson and Kostis Sagonas Dept of Information Technology Uppsala University

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

The Stack, Free Store, and Global Namespace

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

public class SomeClass OtherClass SomeInterface { }

The next several pages summarize some of the best techniques to achieve these three goals.

ITI Introduction to Computing II

Lecture 19 Programming Exceptions CSE11 Fall 2013

ITI Introduction to Computing II

Exception handling in Java. J. Pöial

Upcoming Features in C# Mads Torgersen, MSFT

Programming II (CS300)

Final Examination --- SAMPLE SOLUTIONS May

Chapter 3: Operators, Expressions and Type Conversion

Organizing Information. Organizing information is at the heart of information science and is important in many other

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Will the Real OO Please Stand Up?

Classes, interfaces, & documentation. Review of basic building blocks

Programming II (CS300)

School of Informatics, University of Edinburgh

AXIOMS OF AN IMPERATIVE LANGUAGE PARTIAL CORRECTNESS WEAK AND STRONG CONDITIONS. THE AXIOM FOR nop

Chapter 13 Exception Handling

Notes on Programming in C By: Rob Pike

Disability Advisory Service

Defensive Programming

10 Tips For Effective Content

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Principles of Software Construction: Testing: One, Two, Three

CS 1044 Project 5 Fall 2009

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Exceptions. What exceptional things might our programs run in to?

COMP1406 Tutorial 3. // A simple constructor public Customer(String n, int a, char g, float m) { name = n; age = a; gender = g; money = m; }

MITOCW ocw f99-lec07_300k

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Subclassing for ADTs Implementation

The Way of the Semicolon -or- Three Things I Wish I Had Known Before I Ever Coded One Patricia Hettinger, Oakbrook Terrace, IL

1.2 Adding Integers. Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line

05. SINGLETON PATTERN. One of a Kind Objects

RAIK 183H Examination 2 Solution. November 10, 2014

Stacks. Common data structures - useful for organizing data for specific tasks Lists Stacks - an Abstract Data Type

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

CIT 590 Homework 10 Battleship

(that s not what we meant) Steve

Lecture Notes on Memory Layout

Visual Design. Simplicity, Gestalt Principles, Organization/Structure

Sliders. If we start this script, we get a window with a vertical and a horizontal slider:

COMP 111. Introduction to Computer Science and Object-Oriented Programming. Week 3

Java Programming Language Mr.Rungrote Phonkam

The Calculator CS571. Abstract syntax of correct button push sequences. The Button Layout. Notes 16 Denotational Semantics of a Simple Calculator

List ADT. B/W Confirming Pages

CSE 70 Final Exam Fall 2009

Recursion Examples. Factorial Recursive: Factorial Iterative: #include <iostream> using namespace std; long fact(long n) { if (n == 1) return 1;

A. PE1676/A submission from the Scottish Government of 6th March 2018 unsigned**, - and

Object Oriented Programming Exception Handling

Program development plan

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Building Java Programs

Dealing with Bugs. Kenneth M. Anderson University of Colorado, Boulder CSCI 5828 Lecture 27 04/21/2009

DO NOT REPRODUCE. CS61B, Fall 2008 Test #3 (revised) P. N. Hilfinger


Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

CSE 331. Programming by contract: pre/post conditions; Javadoc

COMP-202 Unit 4: Programming with Iterations

CMP-338 Solutions Midterm Spring Version 1

CSE 143. More ArrayIntList; pre/post; exceptions; debugging. Computer Programming II. CSE 143: Computer Programming II

Goals: Define the syntax of a simple imperative language Define a semantics using natural deduction 1

GRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013

Adam Blank Lecture 3 Autumn 2016 CSE 143. Computer Programming II

Class 26: Linked Lists

OOP Design Conclusions and Variations

Note that if both p1 and p2 are null, equals returns true.

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

Compositional Design Principles

Transcription:

Seven Ineffective Coding Habits of Many Programmers @KevlinHenney

It turns out that style matters in programming for the same reason that it matters in writing. It makes for better reading. Douglas Crockford JavaScript: The Good Parts

Noisy Code

Signal-to-noise ratio (often abbreviated SNR or S/N) is a measure used in science and engineering that compares the level of a desired signal to the level of background noise. Signal-to-noise ratio is sometimes used informally to refer to the ratio of useful information to false or irrelevant data in a conversation or exchange. http://en.wikipedia.org/wiki/signal_to_noise_ratio

To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? William Shakespeare Hamlet

Continuing existence or cessation of existence: those are the scenarios. Is it more empowering mentally to work towards an accommodation of the downsizings and negative outcomes of adversarial circumstance, or would it be a greater enhancement of the bottom line to move forwards to a challenge to our current difficulties, and, by making a commitment to opposition, to effect their demise? Tom Burton Long Words Bother Me

public class RecentlyUsedList private List<string> items; public RecentlyUsedList() items = new List<string>(); public void Add(string newitem) if (items.contains(newitem)) int position = items.indexof(newitem); string existingitem = items[position]; items.removeat(position); items.insert(0, existingitem); else items.insert(0, newitem); public int Count get int size = items.count; return size; public string this[int index] get int position = 0; foreach (string item in items) if (position == index) return item; ++position; throw new ArgumentOutOfRangeException();

public class RecentlyUsedList private List<string> items; public RecentlyUsedList() items = new List<string>(); public void Add(string newitem) if (items.contains(newitem)) int position = items.indexof(newitem); string existingitem = list[position]; items.removeat(position); items.insert(0, existingitem); else items.insert(0, newitem); public int Count get int size = items.count; return size; public string this[int index] get int position = 0; foreach (string value in items) if (position == index) return value; ++position; throw new ArgumentOutOfRangeException(); public class RecentlyUsedList private List<string> items = new List<string>(); public void Add(string newitem) items.remove(newitem); items.add(newitem); public int Count get return items.count; public string this[int index] get return items[count - index - 1];

Comments A delicate matter, requiring taste and judgement. I tend to err on the side of eliminating comments, for several reasons. First, if the code is clear, and uses good type names and variable names, it should explain itself. Second, comments aren't checked by the compiler, so there is no guarantee they're right, especially after the code is modified. A misleading comment can be very confusing. Third, the issue of typography: comments clutter code. Rob Pike, "Notes on Programming in C"

There is a famously bad comment style: i=i+1; /* Add one to i */ and there are worse ways to do it: /********************************** * * * Add one to i * * * **********************************/ i=i+1; Don't laugh now, wait until you see it in real life. Rob Pike, "Notes on Programming in C"

A common fallacy is to assume authors of incomprehensible code will somehow be able to express themselves lucidly and clearly in comments. Kevlin Henney https://twitter.com/kevlinhenney/status/381021802941906944

Unsustainable Spacing

To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? William Shakespeare Hamlet

Continuing existence or cessation of existence: those are the scenarios. Is it more empowering mentally to work towards an accommodation of the downsizings and negative outcomes of adversarial circumstance, or would it be a greater enhancement of the bottom line to move forwards to a challenge to our current difficulties, and, by making a commitment to opposition, to effect their demise? Tom Burton Long Words Bother Me

Continuing existence or cessation of existence: those are the more empowe to work towa accommodati downsizings outcomes of circumstance a greater enh the bottom li forwards to a our current d by making a opposition, t demise?

Column 80 How many programmers lay out their code

How people read

To answer the question "What is clean design?" most succinctly: a clean design is one that supports visual thinking so people can meet their informational needs with a minimum of conscious effort. Daniel Higginbotham "Clean Up Your Mess A Guide to Visual Design for Everyone" http://www.visualmess.com/

You convey information by the way you arrange a design's elements in relation to each other. This information is understood immediately, if not consciously, by the people viewing your designs. Daniel Higginbotham "Clean Up Your Mess A Guide to Visual Design for Everyone" http://www.visualmess.com/

This is great if the visual relationships are obvious and accurate, but if they're not, your audience is going to get confused. They'll have to examine your work carefully, going back and forth between the different parts to make sure they understand. Daniel Higginbotham "Clean Up Your Mess A Guide to Visual Design for Everyone" http://www.visualmess.com/

public int hownottolayoutamethodheader(int firstargument, String secondargument) public int ensureargumentsarealignedlikethis( int firstargument, String secondargument) public int orensureargumentsaregroupedlikethis( int firstargument, String secondargument) public int butnotalignedlikethis(int firstargument, String secondargument)

int donotformat = likethis(someargumentorexpression, anotherargumentorexpression); int insteadformat = somethinglikethis( someargumentorexpression, anotherargumentorexpression); int orformat = somethinglikethis( someargumentorexpression, anotherargumentorexpression);

int asitis = unstable(someargumentorexpression, anotherargumentorexpression); int butthisis = stable( someargumentorexpression, anotherargumentorexpression); int andthisis = stable( someargumentorexpression, anotherargumentorexpression);

public ResultType arbitrarymethodname(firstargumenttype firs SecondArgumentType sec ThirdArgumentType thir LocalVariableType localvariable = method(firstargument, secondargument) if (localvariable.issomething(thirdargument, SOME_SHOUTY_CONSTANT)) dosomethingwith(localvariable); return localvariable.getsomething();

public ResultType arbitrarymethodname( FirstArgumentType firstargument, SecondArgumentType secondargument, ThirdArgumentType thirdargument) LocalVariableType localvariable = method(firstargument, secondargument); if (localvariable.issomething( thirdargument, SOME_SHOUTY_CONSTANT)) dosomething(localvariable); return localvariable.getsomething();

XXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXX XXXXXXXXXXXX

public ResultType arbitrarymethodname( FirstArgumentType firstargument, SecondArgumentType secondargument, ThirdArgumentType thirdargument) LocalVariableType localvariable = method(firstargument, secondargument); if (localvariable.issomething( thirdargument, SOME_SHOUTY_CONSTANT)) dosomething(localvariable); return localvariable.getsomething();

XXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXX XXXXXXXXXXXX

public ResultType arbitrarymethodname( FirstArgumentType firstargument, SecondArgumentType secondargument, ThirdArgumentType thirdargument) LocalVariableType localvariable = method(firstargument, secondargument); if (localvariable.issomething( thirdargument, SOME_SHOUTY_CONSTANT)) dosomething(localvariable); return localvariable.getsomething();

XXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXX XXXXXXXXXXXX

Lego Naming

Agglutination is a process in linguistic morphology derivation in which complex words are formed by stringing together morphemes, each with a single grammatical or semantic meaning. Languages that use agglutination widely are called agglutinative languages. http://en.wikipedia.org/wiki/agglutination

pneumonoultramicroscopicsilicovolcanoconiosis fylkestrafikksikkerhetsutvalgssekretariatslederfunksjonene Rindfleischetikettierungsüberwachungsaufgabenübertragungsgesetz

add validate Proxy Controller Value get Exception Factory Manager set enable process create Object check disable do Service remove

public interface ConditionChecker boolean checkcondition();

public interface Condition boolean istrue();

public Connection createconnection(provider...) throws ConnectionFailureException...

public Connection connectto(provider...) throws ConnectionFailure...

ClassNotFoundException EnumConstantNotPresentException IllegalArgumentException IllegalAccessException IndexOutOfBoundsException NegativeArraySizeException NoSuchMethodException TypeNotPresentException UnsupportedOperationException

ClassNotFound EnumConstantNotPresent IllegalArgument IllegalAccess IndexOutOfBounds NegativeArraySize NoSuchMethod TypeNotPresent UnsupportedOperation

ArithmeticException ArrayStoreException ClassCastException InstantiationException NullPointerException SecurityException

Arithmetic ArrayStore ClassCast Instantiation NullPointer Security

IntegerDivisionByZero IllegalArrayElementType CastToNonSubclass ClassCannotBeInstantiated NullDereferenced SecurityViolation

Omit needless words. William Strunk and E B White The Elements of Style

Underabstraction

http://fragmental.tw/2009/04/29/tag-clouds-see-how-noisy-your-code-is/

http://fragmental.tw/2009/04/29/tag-clouds-see-how-noisy-your-code-is/

if (portfolioidsbytraderid.get(trader.getid()).containskey(portfolio.getid()))... Dan North, "Code in the Language of the Domain" 97 Things Every Programmer Should Know

if (trader.canview(portfolio))... Dan North, "Code in the Language of the Domain" 97 Things Every Programmer Should Know

Unencapsulated State

An affordance is a quality of an object, or an environment, which allows an individual to perform an action. For example, a knob affords twisting, and perhaps pushing, while a cord affords pulling. http://en.wikipedia.org/wiki/affordance

public class RecentlyUsedList private List<string> items = new List<string>(); public List<string> Items get return items; public void Add(string newitem) if(newitem == null) throw new ArgumentNullException(); items.remove(newitem); items.insert(0, newitem);...

public class RecentlyUsedList private List<string> items = new List<string>(); public List<string> Items get return items; public void Add(string newitem) if(newitem == null) throw new ArgumentNullException(); items.remove(newitem); items.insert(0, newitem);...

public class RecentlyUsedList private List<string> items = new List<string>(); public List<string> Items get return items; public void Add(string newitem) if(newitem == null) throw new ArgumentNullException(); items.remove(newitem); items.insert(0, newitem);... var list = new RecentlyUsedList(); list.add("hello, World!"); Console.WriteLine(list.Items.Count); list.items.add("hello, World!"); Console.WriteLine(list.Items.Count); list.items.add(null);

Don't ever invite a vampire into your house, you silly boy. It renders you powerless.

public class RecentlyUsedList private IList<string> items = new List<string>(); public int Count get return items.count; public string this[int index] get return items[index]; public void Add(string newitem) if(newitem == null) throw new ArgumentNullException(); items.remove(newitem); items.insert(0, newitem);...

public class RecentlyUsedList private IList<string> items = new List<string>(); public int Count get return items.count; public string this[int index] get return items[count index - 1]; public void Add(string newitem) if(newitem == null) throw new ArgumentNullException(); items.remove(newitem); items.add(newitem);...

Getters and Setters

public class Money implements...... public int getunits()... public int gethundredths()... public Currency getcurrency()...... public void setunits(int newunits)... public void sethundredths(int newhundredths)... public void setcurrency(currency newcurrency)......

public final class Money implements...... public int getunits()... public int gethundredths()... public Currency getcurrency()......

public final class Money implements...... public int units()... public int hundredths()... public Currency currency()......

When it is not necessary to change, it is necessary not to change. Lucius Cary

Uncohesive Tests

Everybody knows that TDD stands for Test Driven Development. However, people too often concentrate on the words "Test" and "Development" and don't consider what the word "Driven" really implies. For tests to drive development they must do more than just test that code performs its required functionality: they must clearly express that required functionality to the reader. That is, they must be clear specifications of the required functionality. Tests that are not written with their role as specifications in mind can be very confusing to read. Nat Pryce and Steve Freeman "Are Your Tests Really Driving Your Development?"

public class RecentlyUsedList... public RecentlyUsedList()... public int Count get... public string this[int index] get... public void Add(string newitem)......

[TestFixture] public class RecentlyUsedListTests [Test] public void TestConstructor()... [Test] public void TestCountGet()... [Test] public void TestIndexerGet()... [Test] public void TestAdd()......

test test test test method method method test

namespace RecentlyUsedList_spec [TestFixture] public class A_new_list [Test] public void Is_empty() [TestFixture] public class An_empty_list [Test] public void Retains_a_single_addition() [Test] public void Retains_unique_additions_in_stack_order() [TestFixture] public class A_non_empty_list [Test] public void Is_unchanged_when_head_item_is_readded() [Test] public void Moves_non_head_item_to_head_when_it_is_readded() [TestFixture] public class Any_list_rejects [Test] public void Addition_of_null_items() [Test] public void Indexing_past_its_end() [Test] public void Negative_indexing()

namespace RecentlyUsedList_spec [TestFixture] public class A_new_list [Test] public void Is_empty() [TestFixture] public class An_empty_list [Test] public void Retains_a_single_addition() [Test] public void Retains_unique_additions_in_stack_order() [TestFixture] public class A_non_empty_list [Test] public void Is_unchanged_when_head_item_is_readded() [Test] public void Moves_non_head_item_to_head_when_it_is_readded() [TestFixture] public class Any_list_rejects [Test] public void Addition_of_null_items() [Test] public void Indexing_past_its_end() [Test] public void Negative_indexing()

A test case should be just that: it should correspond to a single case.

At some level the style becomes the substance.