Pr ogr amme r 's Doze n T hir te e n R e c omme ndations for - - PowerPoint PPT Presentation

pr ogr amme r s doze n
SMART_READER_LITE
LIVE PREVIEW

Pr ogr amme r 's Doze n T hir te e n R e c omme ndations for - - PowerPoint PPT Presentation

Pr ogr amme r 's Doze n T hir te e n R e c omme ndations for R e vie wing, R R e fac tor e fac tor ing and R ing and R e gaining Contr e gaining Contr ol of Code ol of Code Ke vlin He nne y ke vlin@c ur ke vlin@c ur br br


slide-1
SLIDE 1

Pr

  • gr

amme r 's Doze n

T hir te e n R e c omme ndations for R e vie wing, R e fac tor ing and R e gaining Contr

  • l of Code

R e fac tor ing and R e gaining Contr

  • l of Code

Ke vlin He nne y

ke vlin@c ur br alan.c om ke vlin@c ur br alan.c om

slide-2
SLIDE 2

programmer a person who writes computer programs. d f l dozen a group or set of twelve. The New Oxford Dictionary of English Asymmetric bounds are most convenient to program in a language like C in Asymmetric bounds are most convenient to program in a language like C in which arrays start from zero: the exclusive upper bound of such an array is equal to the number of elements! Thus when we define a C array with [12] elements, 0 is inclusive lower bound and [12] the exclusive upper bound for the elements, 0 is inclusive lower bound and [12] the exclusive upper bound for the subscripts of the array. Andrew Koenig A baker's dozen contains thirteen items as opposed to the familiar twelve. This dates from the time when bakers were subject to heavy fines if they served under-weight bread. To avoid this danger bakers provided a surplus number of l h h h l f h d b ll d h l f loaves, the thirteenth loaf in the dozen being called the vantage loaf. Lock, Stock & Barrel

slide-3
SLIDE 3

Follow Consistent Form 1 Prefer Code to Comments Code Meaning Express Independent Ideas Independently Follow Consistent Form Employ the Contract Metaphor 3 1 2 Code Dependencies p p p y Encapsulate Parameterize from Above 4 5 p Favour Symmetry over Asymmetry Restrict Mutability of State 7 6 Sharpen Fuzzy Logic Go with the Flow Let Code Decide 8 9 10 Code Execution Let Code Decide Omit Needless Code Unify Duplicate Code 10 11 12 Code Consolidation y p

slide-4
SLIDE 4

R e c omme ndation 0

Pr e fe r Code to Comme nts

slide-5
SLIDE 5

1. If a program is incorrect, it matters little what the documentation says. documentation says. 2. If documentation does not agree with the code, it is not worth much. 3 Consequently code must largely document itself If it 3. Consequently, code must largely document itself. If it cannot, rewrite the code rather than increase the supplementary documentation. Good code needs fewer comments than bad code does comments than bad code does. 4. Comments should provide additional information that is not readily obtainable from the code itself. They should never parrot the code should never parrot the code. 5. Mnemonic variable names and labels, and a layout that emphasizes logical structure, help make a program self‐ documenting documenting. Kernighan and Plauger

slide-6
SLIDE 6

R e c omme ndation 1

F

  • llow Consiste nt F
  • r

m F

  • llow Consiste nt F
  • r

m

slide-7
SLIDE 7

Th l h f ll l This principle, that of parallel construction, requires that i i il i d expressions similar in context and function be outwardly similar. The lik f f bl h d likeness of form enables the reader to recognize more readily the lik f d f i likeness of content and function. Strunk and White Strunk and White Strunk and White Strunk and White

slide-8
SLIDE 8

Name based on implementation Client Implementation Implementation name Name based on client usage Client client usage Implementation name

slide-9
SLIDE 9

R e c omme ndation 2

E mploy the p y Contr ac t Me taphor p

slide-10
SLIDE 10

contract a written or spoken agreement, especially one concerning p g , p y g employment, sales, or tenancy, that is intended to be enforceable by law. metaphor a figure of speech in which a word or phrase is applied to an b h h l ll l bl

  • bject or action to which it is not literally applicable.
  • a thing regarded as representative or symbolic of something else,

especially something abstract. p y g The New Oxford Dictionary of English

slide-11
SLIDE 11

postcondition: postcondition: returns size() == 0 postcondition: given: expectedSize = size() + (contains(newItem) ? 0 : 1) postcondition: returns >= 0 postcondition: get(0).equals(newItem) && size() == expectedSize public class RecentlyUsedList { public boolean isEmpty() ... precondition: index >= 0 && index < size() p p y() public int size() ... public void add(String newItem) ... public String get(int index) ... public boolean contains(String item) index >= 0 && index < size() postcondition: returns != null public boolean contains(String item) ... public void clear() ... ... } postcondition: } postcondition: () postcondition: returns whether get(index).equals(item) for any index in [0..size()) isEmpty() any index in [0..size())

slide-12
SLIDE 12

@Test public void constructor() { ()

Constructor Constructor

RecentlyUsedList list = new RecentlyUsedList(); assertEquals(0, list.size()); } @Test public void add() { RecentlyUsedList list new RecentlyUsedList()

Constructor Constructor Add Add

RecentlyUsedList list = new RecentlyUsedList(); list.add("Aardvark"); assertEquals(1, list.size()); list.add("Zebra"); list.add("Mongoose"); assertEquals(3, list.size()); list add("Aardvark");

Add Add

list.add( Aardvark ); assertEquals(3, list.size()); } @Test public void get() { RecentlyUsedList list = new RecentlyUsedList();

Get et

y y (); list.add("Aardvark"); list.add("Zebra"); list.add("Mongoose"); assertEquals("Mongoose", list.get(0)); assertEquals("Zebra", list.get(1)); assertEquals("Aardvark", list.get(2)); ( )

G

list.add("Aardvark"); assertEquals("Aardvark", list.get(0)); assertEquals("Mongoose", list.get(1)); assertEquals("Zebra", list.get(2)); bool thrown; try { list.get(3); thrown = false; } catch(IndexOutOfBoundsException) { thrown = true; thrown = true; } assertTrue(thrown); }

slide-13
SLIDE 13

@Test public void initialListIsEmpty() { RecentlyUsedList list = new RecentlyUsedList();

Initial list Initial list is is empty empty

RecentlyUsedList list = new RecentlyUsedList(); assertEquals(0, list.size()); } @Test public void additionOfSingleItemToEmptyListIsRetained() { RecentlyUsedList list = new RecentlyUsedList();

Addition o ddition of sin single item to le item to Initial list Initial list is is empty empty

y y (); list.add("Aardvark"); assertEquals(1, list.size()); assertEquals("Aardvark", list.get(0)); } @Test public void additionOfDistinctItemsIsRetainedInStackOrder() {

f g f g empty list empty list is is retained retained Addition of Addition of distinct items is distinct items is

{ RecentlyUsedList list = new RecentlyUsedList(); list.add("Aardvark"); list.add("Zebra"); list.add("Mongoose"); assertEquals(3, list.size()); assertEquals("Mongoose" list get(0));

Addition of Addition of distinct items is distinct items is retained in retained in stack order stack order

assertEquals( Mongoose , list.get(0)); assertEquals("Zebra", list.get(1)); assertEquals("Aardvark", list.get(2)); } @Test public void duplicateItemsAreMovedToFrontButNotAdded() { RecentlyUsedList list = new RecentlyUsedList();

Dupli Duplicate e it item ems are moved to s are moved to f b f b dd d

RecentlyUsedList list = new RecentlyUsedList(); list.add("Aardvark"); list.add("Mongoose"); list.add("Aardvark"); assertEquals(2, list.size()); assertEquals("Aardvark", list.get(0)); assertEquals("Mongoose", list.get(1));

front ront but not a ut not add dded

q g g } @Test(expected=IndexOutOfBoundsException.class) public void outOfRangeIndexThrowsException() { RecentlyUsedList list = new RecentlyUsedList(); list.add("Aardvark"); list.add("Mongoose");

Out Out of

  • f range index throws

range index throws except exception

( g ); list.add("Aardvark"); list.get(3); }

slide-14
SLIDE 14

R e c omme ndation 3

E xpr e ss Inde pe nde nt p p Ide as Inde pe nde ntly p y

slide-15
SLIDE 15
slide-16
SLIDE 16

«interface»

UsageInterface

Pure Interface Layer Pure Interface Layer

Interfaces may extend Interfaces may extend interfaces, but there is no interfaces, but there is no implementation defined in implementation defined in this layer this layer this layer. this layer.

Common Code Layer Common Code Layer

Onl abstract classes are Onl abstract classes are

CommonCode CommonCode

Only abstract classes are Only abstract classes are defined in this layer, possibly defined in this layer, possibly with inheritance, factoring out with inheritance, factoring out any common implementation. any common implementation.

Concrete Class Layer Concrete Class Layer

Only concrete classes are Only concrete classes are

ConcreteLeaf ConcreteLeaf

defined, and they do not defined, and they do not inherit from one another. inherit from one another.

ConcreteLeaf

slide-17
SLIDE 17

R e c omme ndation 4

E nc apsulate E nc apsulate

slide-18
SLIDE 18
slide-19
SLIDE 19

encapsulate enclose (something) in or as if in a capsule.

  • express the essential feature of (someone or something) succinctly
  • express the essential feature of (someone or something) succinctly.
  • enclose (a message or signal) in a set of codes which allow use by or

transfer through different computer systems or networks.

  • provide an interface for (a piece of software or hardware) to allow or
  • provide an interface for (a piece of software or hardware) to allow or

simplify access for the user. The New Oxford Dictionary of English

slide-20
SLIDE 20

public class RecentlyUsedList { public void add(String newItem) { list.remove(newItem); list.add(0, newItem); } public ArrayList<String> getList() p y S g g () { return list; } public void setList(ArrayList<String> newList) public void setList(ArrayList String newList) { list = newList; } private ArrayList<String> list; private ArrayList<String> list; } RecentlyUsedList list = new RecentlyUsedList(); list.setList(new ArrayList<String>()); li t dd("H ll W ld!") list.add("Hello, World!"); assert list.getList().size() == 1; list.getList().clear(); assert list.getList().isEmpty();

slide-21
SLIDE 21

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

slide-22
SLIDE 22
slide-23
SLIDE 23

public class RecentlyUsedList public class RecentlyUsedList { public boolean isEmpty() { return list.isEmpty(); p y(); } public int size() { return list.size(); } public void add(String newItem) { list.remove(newItem); li dd(0 I ) list.add(0, newItem); } public void clear() { list clear(); list.clear(); } private List<String> list = new ArrayList<String>(); } l d i li l d i () RecentlyUsedList list = new RecentlyUsedList(); list.add("Hello, World!"); assert list.size() == 1; list.clear(); asse t list isE t () assert list.isEmpty();

slide-24
SLIDE 24

R e c omme ndation 5

Par ame te r ize fr

  • m

Above

slide-25
SLIDE 25

Parameterize Parameterize from Above Hardwire from Below

slide-26
SLIDE 26
slide-27
SLIDE 27
slide-28
SLIDE 28

R e c omme ndation 6

R e str ic t Mutability of y State

slide-29
SLIDE 29

public class Date { ... public int getYear() ... public int getMonth() ... public int getDayInMonth() ... p g y () public void setYear(int newYear) ... public void setMonth(int newMonth) ... public void setDayInMonth(int newDayInMonth) ... ... }

slide-30
SLIDE 30

public class Date { ... public int getYear() ... public int getMonth() ... public int getWeekInYear() ... p g () public int getDayInYear() ... public int getDayInMonth() ... public int getDayInWeek() ... bli id tY (i t Y ) public void setYear(int newYear) ... public void setMonth(int newMonth) ... public void setWeekInYear(int newWeek) ... public void setDayInYear(int newDayInYear) ... public void setDayInYear(int newDayInYear) ... public void setDayInMonth(int newDayInMonth) ... public void setDayInWeek(int newDayInWeek) ... ... }

slide-31
SLIDE 31

public class Date { ... public int getYear() ... public int getMonth() ... public int getWeekInYear() ... p g () public int getDayInYear() ... public int getDayInMonth() ... public int getDayInWeek() ... bli id tY (i t Y ) public void setYear(int newYear) ... public void setMonth(int newMonth) ... public void setWeekInYear(int newWeek) ... public void setDayInYear(int newDayInYear) ... public void setDayInYear(int newDayInYear) ... public void setDayInMonth(int newDayInMonth) ... public void setDayInWeek(int newDayInWeek) ... ... private int year, month, dayInMonth; private int year, month, dayInMonth; }

slide-32
SLIDE 32

public class Date { ... public int getYear() ... public int getMonth() ... public int getWeekInYear() ... p g () public int getDayInYear() ... public int getDayInMonth() ... public int getDayInWeek() ... bli id tY (i t Y ) public void setYear(int newYear) ... public void setMonth(int newMonth) ... public void setWeekInYear(int newWeek) ... public void setDayInYear(int newDayInYear) ... public void setDayInYear(int newDayInYear) ... public void setDayInMonth(int newDayInMonth) ... public void setDayInWeek(int newDayInWeek) ... ... private int daysSinceEpoch; private int daysSinceEpoch; }

slide-33
SLIDE 33

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

slide-34
SLIDE 34

public class Date { ... public int getYear() ... public int getMonth() ... public int getWeekInYear() ... p g () public int getDayInYear() ... public int getDayInMonth() ... public int getDayInWeek() ... ... }

slide-35
SLIDE 35

public class Date { ... public int year() ... public int month() ... public int weekInYear() ... p () public int dayInYear() ... public int dayInMonth() ... public int dayInWeek() ... ... }

slide-36
SLIDE 36

R e c omme ndation 7

F avour Symme tr y ove r y y Asymme tr y y y

slide-37
SLIDE 37

symmetry the quality of being made up of exactly similar parts facing each other or around an axis. correct or pleasing proportion of the parts of a thing. similarity of exact correspondence between different h things. The New Oxford Dictionary of English

slide-38
SLIDE 38

When in doubt, make it symmetrical.

Chr Christo stopher Alexander her Alexander p

slide-39
SLIDE 39

La symétrie, c'est l'ennui, et l'ennui est le La symétrie, c'est l'ennui, et l'ennui est le fond fond même du même du deuil. Le

  • deuil. Le déses

désespoir

  • ir baîll

baîlle. p Victor Hugo

slide-40
SLIDE 40

R e c omme ndation 8

Shar pe n F uzzy L

  • gic

Shar pe n F uzzy L

  • gic
slide-41
SLIDE 41

if(enabled != false) if(enabled != false) enabled = false; else enabled = true; enabled = !enabled; if(value > limit) ( ) markOverLimit(true); else markOverLimit(false); markOverLimit(value > limit); if(loaded() == true) if( lid() t ) if(valid() == true) return true; else return false; return loaded() && valid(); else return false;

slide-42
SLIDE 42

R e c omme ndation 9

Go with the F low Go with the F low

slide-43
SLIDE 43

When the visible appearance of code and the control flow correspond, it greatly aids comprehension and

  • correctness. Using goto subverts this. With goto, you

g y must read every line or you don't know what is going

  • n. A goto completely invalidates the high-level

structure of the code. returning from the middle of a structure of the code. returning from the middle of a procedure is similarly suspect. Don't use either of these constructs. If you feel a burning need to do this, consult your architect consult your architect. Taligent's Guide to Designing Programs

slide-44
SLIDE 44

R e c omme ndation 10

L e t Code De c ide L e t Code De c ide

slide-45
SLIDE 45
slide-46
SLIDE 46

A Visitor Visitor allows type laundering without the clumsiness of An Enumera Enumeration ion Method Method encapsulates traversal mechanics within the object structure, instead of having N d

*

W lk clumsiness of instanceof. structure, instead of having it clutter client code. Node

forEach

Walker

enterCompound leaveCompound

Primitive Compound

visitPrimitive

f

forEach forEach

A Composite Composite offers an A Li Lifec ecycle Callback cle Callback reflects the traversal and object structure in the callback set. A Composite Composite offers an interesting object structure to traverse. in the callback set.

slide-47
SLIDE 47

N d

*

collect(collectingParameter) {

Node

collect { collectingParameter.add(this); } nodes

Primitive Compound

collect collect collect(collectingParameter) { collectingParameter.add(this); for(each : nodes) each.collect(collectingParameter); }

slide-48
SLIDE 48

Common operations on objects in the same state Collections for states Transition of objects b t t t Object in a state between states

slide-49
SLIDE 49

R e c omme ndation 11

Omit Ne e dle ss Code Omit Ne e dle ss Code

slide-50
SLIDE 50

public class RecentlyUsedList { public RecentlyUsedList() { list = new ArrayList<String>(); } public class RecentlyUsedList { public void add(String newItem) { list.remove(newItem); li dd( I ) } public void add(String newItem) { if(list.contains(newItem)) { int position; list.add(newItem); } public int size() { return list.size(); } p ; position = list.indexOf(newItem); string existingItem; existingItem = list.get(position); list.remove(position); list.add(0, existingItem); } } public String get(int index) { return list.get(size() - index – 1); } private List<String> list = new ArrayList<String>(); } } else { list.add(0, newItem); } } bli i t i () } public int size() { int size; size = list.size(); return size; } public String get(int index) { int position; position = 0; for(String value : list) { if(position == index) { return value; } ++position; } throw new IndexOutOfBoundsException(); } private List<String> list; }

slide-51
SLIDE 51

public class Date { public Date(Year year, Month month, int dayInMonth) ... public Date(int dayInMonth, Month month, Year year) ... public Date(Month month, int dayInMonth, Year year) ... p ( , y , y ) ... } public class Date { public Date(Year year, Month month, int dayInMonth) ... ... }

slide-52
SLIDE 52

R e c omme ndation 12

Unify Duplic ate Code Unify Duplic ate Code

slide-53
SLIDE 53
slide-54
SLIDE 54

The only thing to do with good advice is to pass it on The only thing to do with good advice is to pass it on. It is never any use to oneself.

O Wild Oscar Wilde