Modular Reusable Easy to Read Maintainable Testable Easy to Change Easy to Understand The Goal S Singletons T U P I D Dont write stupid code The antipattern Means Global State Hardcoded dependencies ID: 435239
Download Presentation The PPT/PDF document "Basics of Code Design" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Basics of Code DesignSlide2
Modular
Reusable
Easy to ReadMaintainableTestableEasy to ChangeEasy to Understand
The GoalSlide3
S = Singletons
T
UPIDDon’t write stupid codeSlide4
The anti-pattern
Means Global State
Hard-coded dependencies“Spooky Action at a Distance”The functionality of my method changed, … but my function’s code did not!
SingletonsSlide5
S = Singletons
T = Tight Coupling
UPID
Don’t write stupid codeSlide6
2 pieces of code are intertwined
Effects:
Code reuseCode modificationFixing BugsTestingEach piece of code should have only 1 responsibility
Tight CouplingSlide7
checkForm
:
make sure 1st 3 characters are digitsmake sure 4th is a dash
make sure characters 5-6 are digits
make sure 7
th
is a dash
make sure characters 8-11 are digits
make sure the SSN created appears in the registry table
make sure the SSN created matches the name in the name database
ExampleSlide8
Previous code couples the SSN format, the registry table, and the name database
S
eparate functionality to de-couplecouplingSlide9
S = Singletons
T = Tight Coupling
U = Untestable CodePID
Don’t write stupid codeSlide10
Globals
Tight coupling
Doing too much! Long methods and Complex codeIf it isn’t (easily) testable, it will not be maintainable.
What makes code untestable?Slide11
S = Singletons
T = Tight Coupling
U = Untestable CodeP = Premature OptimizationID
Don’t write stupid codeSlide12
Code Optimization is at odds with Code Design
Three “rules” of optimization:
Don’t.Don’t yet.If you are an optimization expert, then okay, but only if you run profiles first."More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity." -- W.A.
Wulf
“Premature optimization is the root of all evil” -- Don Knuth
optimizationSlide13
S = Singletons
T = Tight Coupling
U = Untestable CodeP = Premature OptimizationI = Indescriptive NamingD
Don’t write stupid codeSlide14
Use naming conventions
Be consistent
It’s not easyFavor clarity over brevityCode is read far more often than it is written
NamingSlide15
S = Singletons
T = Tight Coupling
U = Untestable CodeP = Premature OptimizationI = Indescriptive NamingD = Duplication
Don’t write stupid codeSlide16
DRY = Don’t Repeat Yourself!
Duplication makes code hard to reuse, debug, and change
DuplicationSlide17
(Largely for object-oriented code, but still…)
S = Single Responsibility Principle
O = Open/Closed PrincipleL = Liskov Substitution PrincipleI = Interface Substitution Principle
D = Dependency Inversion Principle
SOLID CodeSlide18
Code should be open to extension, closed to modification
It should be easy to add functionality
Adding functionality should minimize changing existing codeOpen/ClosedSlide19
Symptoms that are easily identified in code that point to a violation of the principles
Not bugs
Sign that REFACTORING is neededCode SmellsSlide20
Duplicated code
Large pieces of code
Too many parametersFreeloader – a piece of code that does too littleMagic NumbersCyclomatic
Complexity – loops within loops
Long if statements
Too few comments/ too many comments
Any piece of code that looks one way but functions another (
ints
used as
booleans
, for example)
Code smellsSlide21
Remember this?
typedef
enum {START, PLAY, FINISH} game_state_t;
game_state_t
gameState
;
void
(*
stateFunction
[])() = {
startState
,
playState
,
finishState
};
C FixesSlide22
typedef
enum {START, PLAY, FINISH} game_state_t; game_state_t
gameState
;
They are just
ints
:
for(
game_state_t
x = START; x <= FINISH; x++)
int
x = array[
gameState
];
Enumerated typesSlide23
Consider function:
void foo(
int x){}Pointer to function:
void (*
ptr
) (
int
); // Means
ptr
is a pointer to a
// function that takes an
int
// and returns void
Initialize it:
ptr
= &foo;
Call it:
ptr
(3); // Calls foo(3); Can also write (*
ptr
)(3);
Pointers to functionsSlide24
void (*
stateFunction
[])() = { startState, playState,
finishState
};
void loop(){
stateFunction
[
gameState
]();
}
Arrays of function pointersSlide25
void
setBottom
(int pin){ if (pin == SHORTS){
digitalWrite
(SHORTS, HIGH);
digitalWrite
(PANTS, LOW);
}
if (pin == PANTS){
digitalWrite
(SHORTS, LOW);
digitalWrite
(PANTS, HIGH);
}
}
Example 1: What’s the code smell?Slide26
void
setBottom
(int pin){ if (pin == SHORTS){
digitalWrite
(SHORTS, HIGH);
digitalWrite
(PANTS, LOW);
}
if (pin == PANTS){
digitalWrite
(SHORTS, LOW);
digitalWrite
(PANTS, HIGH);
}
}
Example 1: Why is it a problem?Slide27
void
setBottom
(int pin){ if (pin == SHORTS){
digitalWrite
(SHORTS, HIGH);
digitalWrite
(PANTS, LOW);
}
if (pin == PANTS){
digitalWrite
(SHORTS, LOW);
digitalWrite
(PANTS, HIGH);
}
}
Example 1: what’s a fix?Slide28
void
setState(String condition){ if (condition == “cloud”){
weatherState
= CLOUDY;
}
else if (condition == “sun”){
weatherState
= SUNNY;
}
…
}
Example 2Slide29
String
myScoreMyWin
= “0”;String myScoreOtherWin = “1”;String myScoreTie = “2”;
…
Example 3Slide30
int
convertWasher(String command){ int num
= WASHERTIME – washer1Timer;
wLeft
=
convertToMins
(
num
);
return 1;
}
int
convertDryer
(String command){
int
num
= DRYERTIME – dryer1Timer;
dLeft
=
convertToMins
(
num
);
return 1;
}
Example 4Slide31
int
update(String
sTemp){ int temp =
atoi
(
sTemp
);
if(temp >
highThreshold
){
digitalWrite
(
tshirt_light
, LOW);
digitalWrite
(
cold_light
, LOW);
digitalWrite
(
hot_light
, HIGH);
}
else if (temp <=
highThreshold
&& temp >-
lowThreshold
){
digitalWrite
(
tshirt_light
,
HIGH)
;
digitalWrite
(
cold_light
, LOW);
digitalWrite
(
hot_light
,
LOW);
}
else…
example 5Slide32
void
myWeather
(String data){ if (data == “Rain” || data == “Light Rain” || data == “Showers” || data == “AM Showers || data == “PM Showers” || data == “Thunderstorms” || data == “Scattered Thunderstorms”){
digitalWrite
(
ledBlue
, 255);
}
example 6Slide33
// this is called by IFTTT so can’t take
more
parameters.int teamOneInPlay
(String
param
)
if(
param.equals
(“in”)){
digitalWrite
(LEDPIN1, HIGH);
}
else
digitalWrite
(LEDPIN1, LOW);
}
int
teamTwoInPlay
(String
param
)
if
(
param.equals
(“in”)){
digitalWrite
(
LEDPIN2,
HIGH);
}
else
digitalWrite
(
LEDPIN2,
LOW)
;
}
example 6Slide34
tone(OUT,B6);
digitalWrite
(LED, HIGH);delay(400);noTone
(OUT);
digitalWrite
(LED, LOW);
delay(100);
tone(OUT
,Gsharp6)
;
digitalWrite
(LED, HIGH);
delay
(150)
;
noTone
(OUT);
digitalWrite
(LED, LOW);
delay
(
5
);
etc…
example 7