SlideShare a Scribd company logo
1 of 30
Download to read offline
Design and Implementation 
The Answer to Life, the Universe and Everything 
Hans Verkuil 
Cisco Systems Norway 
© 2013 Cisco and/or its affiliates. All rights reserved. 1
Overview 
● Design and implementation guidelines. 
● Simple techniques to keep your code nice and short. 
● General guidelines to help you stay sane. 
© 2013 Cisco and/or its affiliates. All rights reserved. 2
Disclaimer 
● These are guidelines only, for every guideline I can think of exceptions 
where it doesn't apply. In other words, use common sense. 
● This presentation reflects my opinions, not those of my employer. 
● I am not responsible for any adverse effects this presentation might have 
on your career. I am, of course, responsible for any positive effects this 
presentation might have. 
© 2013 Cisco and/or its affiliates. All rights reserved. 3
Design and Implementation 
Guidelines 
© 2013 Cisco and/or its affiliates. All rights reserved. 4
Do As Little As Possible! 
© 2013 Cisco and/or its affiliates. All rights reserved. 5
Design Guidelines 
● Initial design should be fairly high-level. So don't start designing function 
prototypes, stick to the global picture. 
● Identify which parts are 'risky' because you do not know how to 
implement it, or do not know how long it will take to implement it, or do 
not know if it even can be done. 
● Highly dependent on experience and capabilities of the S/W engineer. 
● Start with the high-risk parts. Just research and implement enough to be 
able to test these parts of the code. 
● Try to plan the time you'll need to research these high-risk areas. 
© 2013 Cisco and/or its affiliates. All rights reserved. 6
Implementation Guidelines 
● Evolutionary prototyping. 
● Coding == learning. 
● Design → coding → learning → design → … 
● Avoid too many layers: that is hard to debug and understand. 
● Avoid too few layers: a certain amount of abstraction makes the code 
much more understandable. 
● Lean and mean: only code what you need, not what you might need. 
But keep the door open for future developments. 
● It is your responsibility to warn your project lead as soon as you know 
you are not going to make the planning! 
© 2013 Cisco and/or its affiliates. All rights reserved. 7
Code Classification 
● Absent code: that's where you earn your pay. 
● Working code: that's where someone earned his pay. 
● Buggy code: that's where someone didn't earn his pay, but you will. 
● Dead code: that's when someone should be fired and you are really 
going to earn your pay. 
© 2013 Cisco and/or its affiliates. All rights reserved. 8
Keep It Simple, 
Keep It Short 
© 2013 Cisco and/or its affiliates. All rights reserved. 9
Increasingly, people seem to misinterpret 
complexity as sophistication, which is baffling: 
the incomprehensible should cause suspicion 
rather than admiration. 
Niklaus Wirth 
© 2013 Cisco and/or its affiliates. All rights reserved. 10
Keep It Simple, Keep It Short 
● Keeping it simple is very, very hard. 
● Keeping it short is much easier and is the first step to simplicity. 
● Short code is easier to understand and therefore easier to maintain. 
● Short code highlights bad code which might be a candidate for a 
rewrite. 
● Removal of non-essential code does not help a bad design. But it 
does make a bad design more obvious. 
© 2013 Cisco and/or its affiliates. All rights reserved. 11
Example 1: Keep It Short 
/** 
@see DVBT_DEMOD_FP_IS_SIGNAL_LOCKED 
*/ 
int 
rtl2832_IsSignalLocked( 
DVBT_DEMOD_MODULE *pDemod, 
int *pAnswer 
) 
{ 
unsigned long FsmStage; 
// Get FSM stage from FSM_STAGE. 
if(pDemod->GetRegBitsWithPage(pDemod, DVBT_FSM_STAGE, &FsmStage) != FUNCTION_SUCCESS) 
goto error_status_get_registers; 
// Determine answer according to FSM stage. 
if(FsmStage == 11) 
*pAnswer = YES; 
else 
*pAnswer = NO; 
return FUNCTION_SUCCESS; 
error_status_get_registers: 
return FUNCTION_ERROR; 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 12
Example 1: Rewritten 
Old code: 32 lines. New code: 13 lines. 
/** 
@see DVBT_DEMOD_FP_IS_SIGNAL_LOCKED 
*/ 
int rtl2832_IsSignalLocked(DVBT_DEMOD_MODULE *pDemod, int *pAnswer) 
{ 
unsigned long FsmStage; 
if (pDemod->GetRegBitsWithPage(pDemod, DVBT_FSM_STAGE, &FsmStage) != FUNCTION_SUCCESS) 
return FUNCTION_ERROR; 
*pAnswer = (FsmStage == 11) ? YES : NO; 
return FUNCTION_SUCCESS; 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 13
Example 2: Keep It Short 
/* 19 lines of comment removed */ 
AiUInt8 UnivWriteRegister(AiUInt32 RegBaseAddr, 
AiUInt16 Register, AiUInt32 regValue) 
{ 
AiUInt32 *addr_value, regvalue; 
regvalue = (BSWAP32(regValue)); 
addr_value = (AiUInt32*) (Register + RegBaseAddr); 
#ifdef AVI_REGISTER_IO_TEST 
printf("____UnivWriteRegister: Address:%08x / Data=%08x(BE), %08x(LE)rn", (int)addr_value, 
(int)regValue,(int)regvalue); 
#endif 
*addr_value = regvalue; 
return(TRUE); 
} /* end: UnivWriteRegister */ 
© 2013 Cisco and/or its affiliates. All rights reserved. 14
Example 2: Rewritten 
Old code: 36 lines, new code 11 lines 
/*! Write the specified register value to the specified 
* register offset in the Universe memory space. 
* 
* param RegBaseAddr Register base address in Universe memory space 
* param Register Offset from the register base address 
* param regValue The value to be written 
*/ 
void UnivWriteRegister(uint32_t RegBaseAddr, uint16_t Register, uint32_t regValue) 
{ 
*(uint32_t *)(RegBaseAddr + Register) = aviCpuToPci(regValue); 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 15
Spacing 
Alice was beginning to get very tired of sitting by her sister on the bank ,and of 
having nothing to do:once or twice she 
had peeped into the book her 
sister was reading,but it had no pictures or conversations in it , “ and what is the use of 
a book,” thought Alice“without pictures or conversation ? ” 
Alice was beginning to get very tired of sitting by her sister on the bank, and of having 
nothing to do: once or twice she had peeped into the book her sister was reading, but it 
had no pictures or conversations in it, “and what is the use of a book,” thought Alice 
“without pictures or conversation?” 
© 2013 Cisco and/or its affiliates. All rights reserved. 16
Example 3: Spacing 
bool RTSPMsg::findCSeq(char *line){ 
char *findCSeq = strstr(line,"cseq:"); 
int seqNum = 0; 
if(findCSeq && ( sscanf(findCSeq,"cseq: %d",&seqNum) == 1)){ 
aCSeq = seqNum; 
return true; 
}else{ 
return false; 
} 
} 
bool RTSPMsg::findCSeq(const char *line) 
{ 
const char *findCSeq = strstr(line, "cseq:"); 
int seqNum = 0; 
if (findCSeq && sscanf(findCSeq, "cseq: %d", &seqNum) == 1) { 
aCSeq = seqNum; 
return true; 
} 
return false; 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 17
Example 4: Ridiculous Comments 
/*****************************************************************************/ 
/* */ 
/* Module : API_SYS Submodule : API_SYS_RESET */ 
/* */ 
/* Author : XXXXX XXXX Project : FOOBAR */ 
/* */ 
/* Source : C Tools : PC/AT; Norton Editor; */ 
/* CYGNUS, GNU-C, As, and LD */ 
/* IDT-C 5.1 Toolkit */ 
/*---------------------------------------------------------------------------*/ 
/* Create : 01.05.98 Update : 11.12.00 */ 
/*---------------------------------------------------------------------------*/ 
/* Descriptions */ 
/* ------------ */ 
/* Inputs : Reset control [rc] */ 
/* */ 
/* Outputs : Instruction acknowledge type [ackfl] */ 
/* */ 
/* Description : */ 
/* This function handles the 'API_RESET' instruction to initialize the */ 
/* FOOBAR hardware and software to an initial state. */ 
/* */ 
/*****************************************************************************/ 
© 2013 Cisco and/or its affiliates. All rights reserved. 18
Control Flow 1: Return void if possible 
AiUInt8 UnivWriteRegister(AiUInt32 RegBaseAddr, AiUInt16 Register, AiUInt32 regValue) 
{ 
*(AiUInt32*)(Register + RegBaseAddr) = BSWAP32(regValue); 
return TRUE; 
} 
AiUInt8 Foo(...) 
{ 
if (UnivWriteRegister(BoSta[BoNo].BoRegBasAddr, VINT_EN, Mask)) 
return TRUE; 
return IntEnErr; 
} 
void UnivWriteRegister(AiUInt32 RegBaseAddr, AiUInt16 Register, AiUInt32 regValue) 
{ 
*(AiUInt32*)(Register + RegBaseAddr) = BSWAP32(regValue); 
} 
void Foo(...) 
{ 
UnivWriteRegister(BoSta[BoNo].BoRegBasAddr, VINT_EN, Mask); 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 19
Control Flow 2: Use early return 
foo() 
{ 
if (condition) { 
<long code> 
} else { 
<short code> 
} 
} 
foo() 
{ 
if (!condition) { 
<short code> 
return; 
} 
<long code> 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 20
Control Flow 3: Use early continue 
for (...) { 
if (condition) { 
<long code> 
} else { 
<short code> 
} 
} 
for (...) { 
if (!condition) { 
<short code> 
continue; 
} 
<long code> 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 21
Control Flow 4: Avoid if-return-else 
if (condition)) { 
/* ... */ 
return 1; 
} else { 
/* ... */ 
return 0; 
} 
if (condition) { 
/* ... */ 
return 1; 
} 
/* ... */ 
return 0; 
© 2013 Cisco and/or its affiliates. All rights reserved. 22
Debugging Code 
Don’t clutter the source with trivial debug code once you’re done 
developing. 
void ReRouter::setName ( String str ) 
{ 
debug.in ("ReRouter::setName") ; 
config.copyString (name, str) ; 
debug.print (5, "ReRouter::setName: name =", name) ; 
debug.out ("ReRouter::setName") ; 
} 
© 2013 Cisco and/or its affiliates. All rights reserved. 23
C++ 
● Use STL container templates for lists, maps, vectors. 
● Never use ‘using namespace’. 
● Use bool/true/false. 
● If possible, pass arguments by reference. 
● Don’t put related classes in separate source files. Keep them 
together (within reason). 
● Avoid classeritis! 
© 2013 Cisco and/or its affiliates. All rights reserved. 24
Example: Classeritis 
class MECmdCut : public MECmdClear 
class MECmdClear : public MEMultiDirCommand 
class MEMultiDirCommand : public MEMultiNodeCommand<MEDirData> 
template <class DataType> 
class MEMultiNodeCommand : public MENodeCommand 
class MENodeCommand : public GFCommand 
class MECmdCut : public MECmdDelete 
class MECmdDelete : public GFCommand 
© 2013 Cisco and/or its affiliates. All rights reserved. 25
Miscellaneous 
● Use const religiously. 
● Compile with all warnings on (-Wall) and fix the warnings. 
● Premature optimization is the root of all evil. 
© 2013 Cisco and/or its affiliates. All rights reserved. 26
How To Stay Sane 
© 2013 Cisco and/or its affiliates. All rights reserved. 27
General Guidelines 
● Know yourself: discover your strengths and weaknesses. 
● Know when you are at your best/worst and plan accordingly. 
● The importance of sleep after learning new things. 
● The importance of taking a pool/foosball/dart/bathroom/... break. 
© 2013 Cisco and/or its affiliates. All rights reserved. 28
Overtime 
● Don't, unless: 
– It is of a short duration (< 2 weeks), happens rarely and is to reach a realistic 
deadline that is tied to a fixed date like a trade show or something similar. 
– You are having fun! But don't neglect your family, friends, social life. 
● Structural overtime is pointless: your productivity will remain the same 
at best, or (more likely) go down. You get tired, cranky, it's harder to 
think and remain concentrated. 
● Seek another job if you are forced to do this. 
© 2013 Cisco and/or its affiliates. All rights reserved. 29
Questions? 
e-mail: 
hansverk@cisco.com 
hverkuil@xs4all.nl 
© 2013 Cisco and/or its affiliates. All rights reserved. 30

More Related Content

What's hot

[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection
Moabi.com
 

What's hot (20)

Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
 
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farm
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farmKernel Recipes 2016 - Speeding up development by setting up a kernel build farm
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farm
 
Kernel Recipes 2015 - The Dronecode Project – A step in open source drones
Kernel Recipes 2015 - The Dronecode Project – A step in open source dronesKernel Recipes 2015 - The Dronecode Project – A step in open source drones
Kernel Recipes 2015 - The Dronecode Project – A step in open source drones
 
[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory Analysis[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory Analysis
 
Kernel Recipes 2015: Speed up your kernel development cycle with QEMU
Kernel Recipes 2015: Speed up your kernel development cycle with QEMUKernel Recipes 2015: Speed up your kernel development cycle with QEMU
Kernel Recipes 2015: Speed up your kernel development cycle with QEMU
 
Digging for Android Kernel Bugs
Digging for Android Kernel BugsDigging for Android Kernel Bugs
Digging for Android Kernel Bugs
 
syzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzersyzkaller: the next gen kernel fuzzer
syzkaller: the next gen kernel fuzzer
 
QEMU - Binary Translation
QEMU - Binary Translation QEMU - Binary Translation
QEMU - Binary Translation
 
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMUSFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
 
[Defcon] Hardware backdooring is practical
[Defcon] Hardware backdooring is practical[Defcon] Hardware backdooring is practical
[Defcon] Hardware backdooring is practical
 
Linux Kernel Debugging Essentials workshop
Linux Kernel Debugging Essentials workshopLinux Kernel Debugging Essentials workshop
Linux Kernel Debugging Essentials workshop
 
Hardware backdooring is practical : slides
Hardware backdooring is practical : slidesHardware backdooring is practical : slides
Hardware backdooring is practical : slides
 
FreeRTOS introduction
FreeRTOS introductionFreeRTOS introduction
FreeRTOS introduction
 
LAS16-403: GDB Linux Kernel Awareness
LAS16-403: GDB Linux Kernel AwarenessLAS16-403: GDB Linux Kernel Awareness
LAS16-403: GDB Linux Kernel Awareness
 
[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection
 
Ищем уязвимости нулевого дня в ядре Linux
Ищем уязвимости нулевого дня в ядре LinuxИщем уязвимости нулевого дня в ядре Linux
Ищем уязвимости нулевого дня в ядре Linux
 
Testing CAN network with help of CANToolz
Testing CAN network with help of CANToolzTesting CAN network with help of CANToolz
Testing CAN network with help of CANToolz
 
The Silence of the Canaries
The Silence of the CanariesThe Silence of the Canaries
The Silence of the Canaries
 
Qemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System EmulationQemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System Emulation
 
How to Root 10 Million Phones with One Exploit
How to Root 10 Million Phones with One ExploitHow to Root 10 Million Phones with One Exploit
How to Root 10 Million Phones with One Exploit
 

Similar to Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!

Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersDefcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Alexandre Moneger
 
07 -pointers_and_memory_alloc
07  -pointers_and_memory_alloc07  -pointers_and_memory_alloc
07 -pointers_and_memory_alloc
Hector Garzo
 
Instructions 3-5 pages double space research paper about Eric Sc.docx
Instructions 3-5 pages double space research paper about Eric Sc.docxInstructions 3-5 pages double space research paper about Eric Sc.docx
Instructions 3-5 pages double space research paper about Eric Sc.docx
normanibarber20063
 

Similar to Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid! (20)

Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersDefcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
 
07 - Bypassing ASLR, or why X^W matters
07 - Bypassing ASLR, or why X^W matters07 - Bypassing ASLR, or why X^W matters
07 - Bypassing ASLR, or why X^W matters
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Javascript Deofuscation A manual Approach
Javascript Deofuscation A manual ApproachJavascript Deofuscation A manual Approach
Javascript Deofuscation A manual Approach
 
ROP ‘n’ ROLL, a peak into modern exploits
ROP ‘n’ ROLL, a peak into modern exploitsROP ‘n’ ROLL, a peak into modern exploits
ROP ‘n’ ROLL, a peak into modern exploits
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
07 -pointers_and_memory_alloc
07  -pointers_and_memory_alloc07  -pointers_and_memory_alloc
07 -pointers_and_memory_alloc
 
Deeper Look Into HSAIL And It's Runtime
Deeper Look Into HSAIL And It's Runtime Deeper Look Into HSAIL And It's Runtime
Deeper Look Into HSAIL And It's Runtime
 
NSC #2 - D2 01 - Andrea Allievi - Windows 8.1 Patch Protections
NSC #2 - D2 01 - Andrea Allievi - Windows 8.1 Patch ProtectionsNSC #2 - D2 01 - Andrea Allievi - Windows 8.1 Patch Protections
NSC #2 - D2 01 - Andrea Allievi - Windows 8.1 Patch Protections
 
Metasepi team meeting #7: Snatch application on tiny OS
Metasepi team meeting #7: Snatch application on tiny OSMetasepi team meeting #7: Snatch application on tiny OS
Metasepi team meeting #7: Snatch application on tiny OS
 
리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3
 
Gluster Cloud Night in Tokyo 2013 -- Tips for getting started
Gluster Cloud Night in Tokyo 2013 -- Tips for getting startedGluster Cloud Night in Tokyo 2013 -- Tips for getting started
Gluster Cloud Night in Tokyo 2013 -- Tips for getting started
 
05 - Bypassing DEP, or why ASLR matters
05 - Bypassing DEP, or why ASLR matters05 - Bypassing DEP, or why ASLR matters
05 - Bypassing DEP, or why ASLR matters
 
C++ Core Guidelines
C++ Core GuidelinesC++ Core Guidelines
C++ Core Guidelines
 
Instructions 3-5 pages double space research paper about Eric Sc.docx
Instructions 3-5 pages double space research paper about Eric Sc.docxInstructions 3-5 pages double space research paper about Eric Sc.docx
Instructions 3-5 pages double space research paper about Eric Sc.docx
 
Gas leakage detection system
Gas leakage detection systemGas leakage detection system
Gas leakage detection system
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Rodrigo Almeida - Microkernel development from project to implementation
Rodrigo Almeida - Microkernel development from project to implementationRodrigo Almeida - Microkernel development from project to implementation
Rodrigo Almeida - Microkernel development from project to implementation
 
Strategy and best practice for modern RPG
Strategy and best practice for modern RPGStrategy and best practice for modern RPG
Strategy and best practice for modern RPG
 

More from Anne Nicolas

Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Anne Nicolas
 

More from Anne Nicolas (20)

Kernel Recipes 2019 - Driving the industry toward upstream first
Kernel Recipes 2019 - Driving the industry toward upstream firstKernel Recipes 2019 - Driving the industry toward upstream first
Kernel Recipes 2019 - Driving the industry toward upstream first
 
Kernel Recipes 2019 - No NMI? No Problem! – Implementing Arm64 Pseudo-NMI
Kernel Recipes 2019 - No NMI? No Problem! – Implementing Arm64 Pseudo-NMIKernel Recipes 2019 - No NMI? No Problem! – Implementing Arm64 Pseudo-NMI
Kernel Recipes 2019 - No NMI? No Problem! – Implementing Arm64 Pseudo-NMI
 
Kernel Recipes 2019 - Metrics are money
Kernel Recipes 2019 - Metrics are moneyKernel Recipes 2019 - Metrics are money
Kernel Recipes 2019 - Metrics are money
 
Kernel Recipes 2019 - Kernel documentation: past, present, and future
Kernel Recipes 2019 - Kernel documentation: past, present, and futureKernel Recipes 2019 - Kernel documentation: past, present, and future
Kernel Recipes 2019 - Kernel documentation: past, present, and future
 
Embedded Recipes 2019 - Knowing your ARM from your ARSE: wading through the t...
Embedded Recipes 2019 - Knowing your ARM from your ARSE: wading through the t...Embedded Recipes 2019 - Knowing your ARM from your ARSE: wading through the t...
Embedded Recipes 2019 - Knowing your ARM from your ARSE: wading through the t...
 
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
 
Kernel Recipes 2019 - Analyzing changes to the binary interface exposed by th...
Kernel Recipes 2019 - Analyzing changes to the binary interface exposed by th...Kernel Recipes 2019 - Analyzing changes to the binary interface exposed by th...
Kernel Recipes 2019 - Analyzing changes to the binary interface exposed by th...
 
Embedded Recipes 2019 - Remote update adventures with RAUC, Yocto and Barebox
Embedded Recipes 2019 - Remote update adventures with RAUC, Yocto and BareboxEmbedded Recipes 2019 - Remote update adventures with RAUC, Yocto and Barebox
Embedded Recipes 2019 - Remote update adventures with RAUC, Yocto and Barebox
 
Embedded Recipes 2019 - Making embedded graphics less special
Embedded Recipes 2019 - Making embedded graphics less specialEmbedded Recipes 2019 - Making embedded graphics less special
Embedded Recipes 2019 - Making embedded graphics less special
 
Embedded Recipes 2019 - Linux on Open Source Hardware and Libre Silicon
Embedded Recipes 2019 - Linux on Open Source Hardware and Libre SiliconEmbedded Recipes 2019 - Linux on Open Source Hardware and Libre Silicon
Embedded Recipes 2019 - Linux on Open Source Hardware and Libre Silicon
 
Embedded Recipes 2019 - From maintaining I2C to the big (embedded) picture
Embedded Recipes 2019 - From maintaining I2C to the big (embedded) pictureEmbedded Recipes 2019 - From maintaining I2C to the big (embedded) picture
Embedded Recipes 2019 - From maintaining I2C to the big (embedded) picture
 
Embedded Recipes 2019 - Testing firmware the devops way
Embedded Recipes 2019 - Testing firmware the devops wayEmbedded Recipes 2019 - Testing firmware the devops way
Embedded Recipes 2019 - Testing firmware the devops way
 
Embedded Recipes 2019 - Herd your socs become a matchmaker
Embedded Recipes 2019 - Herd your socs become a matchmakerEmbedded Recipes 2019 - Herd your socs become a matchmaker
Embedded Recipes 2019 - Herd your socs become a matchmaker
 
Embedded Recipes 2019 - LLVM / Clang integration
Embedded Recipes 2019 - LLVM / Clang integrationEmbedded Recipes 2019 - LLVM / Clang integration
Embedded Recipes 2019 - LLVM / Clang integration
 
Embedded Recipes 2019 - Introduction to JTAG debugging
Embedded Recipes 2019 - Introduction to JTAG debuggingEmbedded Recipes 2019 - Introduction to JTAG debugging
Embedded Recipes 2019 - Introduction to JTAG debugging
 
Embedded Recipes 2019 - Pipewire a new foundation for embedded multimedia
Embedded Recipes 2019 - Pipewire a new foundation for embedded multimediaEmbedded Recipes 2019 - Pipewire a new foundation for embedded multimedia
Embedded Recipes 2019 - Pipewire a new foundation for embedded multimedia
 
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all startedKernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all started
 
Kernel Recipes 2019 - Suricata and XDP
Kernel Recipes 2019 - Suricata and XDPKernel Recipes 2019 - Suricata and XDP
Kernel Recipes 2019 - Suricata and XDP
 
Kernel Recipes 2019 - Marvels of Memory Auto-configuration (SPD)
Kernel Recipes 2019 - Marvels of Memory Auto-configuration (SPD)Kernel Recipes 2019 - Marvels of Memory Auto-configuration (SPD)
Kernel Recipes 2019 - Marvels of Memory Auto-configuration (SPD)
 
Kernel Recipes 2019 - CVEs are dead, long live the CVE!
Kernel Recipes 2019 - CVEs are dead, long live the CVE!Kernel Recipes 2019 - CVEs are dead, long live the CVE!
Kernel Recipes 2019 - CVEs are dead, long live the CVE!
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Recently uploaded (20)

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 

Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!

  • 1. Design and Implementation The Answer to Life, the Universe and Everything Hans Verkuil Cisco Systems Norway © 2013 Cisco and/or its affiliates. All rights reserved. 1
  • 2. Overview ● Design and implementation guidelines. ● Simple techniques to keep your code nice and short. ● General guidelines to help you stay sane. © 2013 Cisco and/or its affiliates. All rights reserved. 2
  • 3. Disclaimer ● These are guidelines only, for every guideline I can think of exceptions where it doesn't apply. In other words, use common sense. ● This presentation reflects my opinions, not those of my employer. ● I am not responsible for any adverse effects this presentation might have on your career. I am, of course, responsible for any positive effects this presentation might have. © 2013 Cisco and/or its affiliates. All rights reserved. 3
  • 4. Design and Implementation Guidelines © 2013 Cisco and/or its affiliates. All rights reserved. 4
  • 5. Do As Little As Possible! © 2013 Cisco and/or its affiliates. All rights reserved. 5
  • 6. Design Guidelines ● Initial design should be fairly high-level. So don't start designing function prototypes, stick to the global picture. ● Identify which parts are 'risky' because you do not know how to implement it, or do not know how long it will take to implement it, or do not know if it even can be done. ● Highly dependent on experience and capabilities of the S/W engineer. ● Start with the high-risk parts. Just research and implement enough to be able to test these parts of the code. ● Try to plan the time you'll need to research these high-risk areas. © 2013 Cisco and/or its affiliates. All rights reserved. 6
  • 7. Implementation Guidelines ● Evolutionary prototyping. ● Coding == learning. ● Design → coding → learning → design → … ● Avoid too many layers: that is hard to debug and understand. ● Avoid too few layers: a certain amount of abstraction makes the code much more understandable. ● Lean and mean: only code what you need, not what you might need. But keep the door open for future developments. ● It is your responsibility to warn your project lead as soon as you know you are not going to make the planning! © 2013 Cisco and/or its affiliates. All rights reserved. 7
  • 8. Code Classification ● Absent code: that's where you earn your pay. ● Working code: that's where someone earned his pay. ● Buggy code: that's where someone didn't earn his pay, but you will. ● Dead code: that's when someone should be fired and you are really going to earn your pay. © 2013 Cisco and/or its affiliates. All rights reserved. 8
  • 9. Keep It Simple, Keep It Short © 2013 Cisco and/or its affiliates. All rights reserved. 9
  • 10. Increasingly, people seem to misinterpret complexity as sophistication, which is baffling: the incomprehensible should cause suspicion rather than admiration. Niklaus Wirth © 2013 Cisco and/or its affiliates. All rights reserved. 10
  • 11. Keep It Simple, Keep It Short ● Keeping it simple is very, very hard. ● Keeping it short is much easier and is the first step to simplicity. ● Short code is easier to understand and therefore easier to maintain. ● Short code highlights bad code which might be a candidate for a rewrite. ● Removal of non-essential code does not help a bad design. But it does make a bad design more obvious. © 2013 Cisco and/or its affiliates. All rights reserved. 11
  • 12. Example 1: Keep It Short /** @see DVBT_DEMOD_FP_IS_SIGNAL_LOCKED */ int rtl2832_IsSignalLocked( DVBT_DEMOD_MODULE *pDemod, int *pAnswer ) { unsigned long FsmStage; // Get FSM stage from FSM_STAGE. if(pDemod->GetRegBitsWithPage(pDemod, DVBT_FSM_STAGE, &FsmStage) != FUNCTION_SUCCESS) goto error_status_get_registers; // Determine answer according to FSM stage. if(FsmStage == 11) *pAnswer = YES; else *pAnswer = NO; return FUNCTION_SUCCESS; error_status_get_registers: return FUNCTION_ERROR; } © 2013 Cisco and/or its affiliates. All rights reserved. 12
  • 13. Example 1: Rewritten Old code: 32 lines. New code: 13 lines. /** @see DVBT_DEMOD_FP_IS_SIGNAL_LOCKED */ int rtl2832_IsSignalLocked(DVBT_DEMOD_MODULE *pDemod, int *pAnswer) { unsigned long FsmStage; if (pDemod->GetRegBitsWithPage(pDemod, DVBT_FSM_STAGE, &FsmStage) != FUNCTION_SUCCESS) return FUNCTION_ERROR; *pAnswer = (FsmStage == 11) ? YES : NO; return FUNCTION_SUCCESS; } © 2013 Cisco and/or its affiliates. All rights reserved. 13
  • 14. Example 2: Keep It Short /* 19 lines of comment removed */ AiUInt8 UnivWriteRegister(AiUInt32 RegBaseAddr, AiUInt16 Register, AiUInt32 regValue) { AiUInt32 *addr_value, regvalue; regvalue = (BSWAP32(regValue)); addr_value = (AiUInt32*) (Register + RegBaseAddr); #ifdef AVI_REGISTER_IO_TEST printf("____UnivWriteRegister: Address:%08x / Data=%08x(BE), %08x(LE)rn", (int)addr_value, (int)regValue,(int)regvalue); #endif *addr_value = regvalue; return(TRUE); } /* end: UnivWriteRegister */ © 2013 Cisco and/or its affiliates. All rights reserved. 14
  • 15. Example 2: Rewritten Old code: 36 lines, new code 11 lines /*! Write the specified register value to the specified * register offset in the Universe memory space. * * param RegBaseAddr Register base address in Universe memory space * param Register Offset from the register base address * param regValue The value to be written */ void UnivWriteRegister(uint32_t RegBaseAddr, uint16_t Register, uint32_t regValue) { *(uint32_t *)(RegBaseAddr + Register) = aviCpuToPci(regValue); } © 2013 Cisco and/or its affiliates. All rights reserved. 15
  • 16. Spacing Alice was beginning to get very tired of sitting by her sister on the bank ,and of having nothing to do:once or twice she had peeped into the book her sister was reading,but it had no pictures or conversations in it , “ and what is the use of a book,” thought Alice“without pictures or conversation ? ” Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, “and what is the use of a book,” thought Alice “without pictures or conversation?” © 2013 Cisco and/or its affiliates. All rights reserved. 16
  • 17. Example 3: Spacing bool RTSPMsg::findCSeq(char *line){ char *findCSeq = strstr(line,"cseq:"); int seqNum = 0; if(findCSeq && ( sscanf(findCSeq,"cseq: %d",&seqNum) == 1)){ aCSeq = seqNum; return true; }else{ return false; } } bool RTSPMsg::findCSeq(const char *line) { const char *findCSeq = strstr(line, "cseq:"); int seqNum = 0; if (findCSeq && sscanf(findCSeq, "cseq: %d", &seqNum) == 1) { aCSeq = seqNum; return true; } return false; } © 2013 Cisco and/or its affiliates. All rights reserved. 17
  • 18. Example 4: Ridiculous Comments /*****************************************************************************/ /* */ /* Module : API_SYS Submodule : API_SYS_RESET */ /* */ /* Author : XXXXX XXXX Project : FOOBAR */ /* */ /* Source : C Tools : PC/AT; Norton Editor; */ /* CYGNUS, GNU-C, As, and LD */ /* IDT-C 5.1 Toolkit */ /*---------------------------------------------------------------------------*/ /* Create : 01.05.98 Update : 11.12.00 */ /*---------------------------------------------------------------------------*/ /* Descriptions */ /* ------------ */ /* Inputs : Reset control [rc] */ /* */ /* Outputs : Instruction acknowledge type [ackfl] */ /* */ /* Description : */ /* This function handles the 'API_RESET' instruction to initialize the */ /* FOOBAR hardware and software to an initial state. */ /* */ /*****************************************************************************/ © 2013 Cisco and/or its affiliates. All rights reserved. 18
  • 19. Control Flow 1: Return void if possible AiUInt8 UnivWriteRegister(AiUInt32 RegBaseAddr, AiUInt16 Register, AiUInt32 regValue) { *(AiUInt32*)(Register + RegBaseAddr) = BSWAP32(regValue); return TRUE; } AiUInt8 Foo(...) { if (UnivWriteRegister(BoSta[BoNo].BoRegBasAddr, VINT_EN, Mask)) return TRUE; return IntEnErr; } void UnivWriteRegister(AiUInt32 RegBaseAddr, AiUInt16 Register, AiUInt32 regValue) { *(AiUInt32*)(Register + RegBaseAddr) = BSWAP32(regValue); } void Foo(...) { UnivWriteRegister(BoSta[BoNo].BoRegBasAddr, VINT_EN, Mask); } © 2013 Cisco and/or its affiliates. All rights reserved. 19
  • 20. Control Flow 2: Use early return foo() { if (condition) { <long code> } else { <short code> } } foo() { if (!condition) { <short code> return; } <long code> } © 2013 Cisco and/or its affiliates. All rights reserved. 20
  • 21. Control Flow 3: Use early continue for (...) { if (condition) { <long code> } else { <short code> } } for (...) { if (!condition) { <short code> continue; } <long code> } © 2013 Cisco and/or its affiliates. All rights reserved. 21
  • 22. Control Flow 4: Avoid if-return-else if (condition)) { /* ... */ return 1; } else { /* ... */ return 0; } if (condition) { /* ... */ return 1; } /* ... */ return 0; © 2013 Cisco and/or its affiliates. All rights reserved. 22
  • 23. Debugging Code Don’t clutter the source with trivial debug code once you’re done developing. void ReRouter::setName ( String str ) { debug.in ("ReRouter::setName") ; config.copyString (name, str) ; debug.print (5, "ReRouter::setName: name =", name) ; debug.out ("ReRouter::setName") ; } © 2013 Cisco and/or its affiliates. All rights reserved. 23
  • 24. C++ ● Use STL container templates for lists, maps, vectors. ● Never use ‘using namespace’. ● Use bool/true/false. ● If possible, pass arguments by reference. ● Don’t put related classes in separate source files. Keep them together (within reason). ● Avoid classeritis! © 2013 Cisco and/or its affiliates. All rights reserved. 24
  • 25. Example: Classeritis class MECmdCut : public MECmdClear class MECmdClear : public MEMultiDirCommand class MEMultiDirCommand : public MEMultiNodeCommand<MEDirData> template <class DataType> class MEMultiNodeCommand : public MENodeCommand class MENodeCommand : public GFCommand class MECmdCut : public MECmdDelete class MECmdDelete : public GFCommand © 2013 Cisco and/or its affiliates. All rights reserved. 25
  • 26. Miscellaneous ● Use const religiously. ● Compile with all warnings on (-Wall) and fix the warnings. ● Premature optimization is the root of all evil. © 2013 Cisco and/or its affiliates. All rights reserved. 26
  • 27. How To Stay Sane © 2013 Cisco and/or its affiliates. All rights reserved. 27
  • 28. General Guidelines ● Know yourself: discover your strengths and weaknesses. ● Know when you are at your best/worst and plan accordingly. ● The importance of sleep after learning new things. ● The importance of taking a pool/foosball/dart/bathroom/... break. © 2013 Cisco and/or its affiliates. All rights reserved. 28
  • 29. Overtime ● Don't, unless: – It is of a short duration (< 2 weeks), happens rarely and is to reach a realistic deadline that is tied to a fixed date like a trade show or something similar. – You are having fun! But don't neglect your family, friends, social life. ● Structural overtime is pointless: your productivity will remain the same at best, or (more likely) go down. You get tired, cranky, it's harder to think and remain concentrated. ● Seek another job if you are forced to do this. © 2013 Cisco and/or its affiliates. All rights reserved. 29
  • 30. Questions? e-mail: hansverk@cisco.com hverkuil@xs4all.nl © 2013 Cisco and/or its affiliates. All rights reserved. 30