Source Code Quality

Alberto Simões
Alberto SimõesTeacher, programmer at University of Minho
source code quality
Alberto Simões
March 10, 2015 – ESEIG-IPP – Vila do Conde
Departamento de Informática
Universidade do Minho
outline
Motivation
Code Structure
Code Documentation
Testing
1
motivation
no bad code initiative
3
code problems
∙ Legibility Issues;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
∙ Documentation should exist;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
∙ Documentation should exist;
∙ Documentation should follow standards;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
∙ Documentation should exist;
∙ Documentation should follow standards;
∙ Documentation should document!
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
∙ Documentation should exist;
∙ Documentation should follow standards;
∙ Documentation should document!
∙ Testing Issues;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
∙ Documentation should exist;
∙ Documentation should follow standards;
∙ Documentation should document!
∙ Testing Issues;
∙ Code should work on correct input;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
∙ Documentation should exist;
∙ Documentation should follow standards;
∙ Documentation should document!
∙ Testing Issues;
∙ Code should work on correct input;
∙ Code should work on incorrect input;
4
code problems
∙ Legibility Issues;
∙ Code should document itself;
∙ Code should be easy to read;
∙ Code should be elegant!
∙ Documentation Issues;
∙ Documentation should exist;
∙ Documentation should follow standards;
∙ Documentation should document!
∙ Testing Issues;
∙ Code should work on correct input;
∙ Code should work on incorrect input;
∙ Code should be tested on every change!
4
code structure
code structure
6
use meaningful identifiers
What does this code do?
int x(string g[]) {
string p = g[0]; int o = p.length();
for (z=1;z<g.length;++z) {
if (g[z].length()>o) { p=g[z];o=p.length(); }
}
return o;
}
7
use meaningful identifiers
Is this better?
int x(string list[]) {
string maxString = list[0];
int maxSize = maxString.length();
for (i=1;i<list.length;++i) {
if (list[i].length()>maxSize) { maxString=list[i];
maxSize=maxString.length(); }
}
return maxSize;
}
8
use coherent indentation
Do you prefer this…
int x(string list[]) {
string maxString = list[0];
int maxSize = maxString.length();
for (i=1;i<list.length;++i) {
if (list[i].length()>maxSize) { maxString=list[i];
maxSize=maxString.length(); }
}
return maxSize;
}
9
use coherent indentation
or this?
int x(string list[]) {
string maxString = list[0];
int maxSize = maxString.length();
for (i=1;i<list.length;++i) {
if (list[i].length()>maxSize) {
maxString=list[i];
maxSize=maxString.length();
}
}
return maxSize;
}
10
use coherent identifiers
int x(string Lists[]) {
string max_String = Lista[0];
int maxSize = max_String.length();
for (i=1;i<Lista.length;++i) {
if (Lista[i].length()>maxSize) {
max_String=Lista[i];
maxSize=max_String.length();
}
}
return maxSize;
}
11
use coherent identifiers
Choose:
∙ One language:
I prefer English given keywords are English, but any will work!
12
use coherent identifiers
Choose:
∙ One language:
I prefer English given keywords are English, but any will work!
∙ Use one variable style:
If you prefer use CamelCaseIdentifiers;
Or, why not, underscores_identifiers;
but not both!
12
use coherent identifiers
Choose:
∙ One language:
I prefer English given keywords are English, but any will work!
∙ Use one variable style:
If you prefer use CamelCaseIdentifiers;
Or, why not, underscores_identifiers;
but not both!
∙ Note that some languages have conventions:
Java libraries use CamelCase;
GNU Toolkit (GTK+) use underscores;
So, probably a good idea to follow the flow…
12
use standard code structure
Does this work?
int x(string list[]) {
; string maxString = list[0]
; int maxSize = maxString.length()
; for (i=1;i<list.length;++i)
if (list[i].length()>maxSize) {
; maxString=list[i]
; maxSize=maxString.length()
; }
; return maxSize
; }
Isn’t it cute?
13
use standard and coherent code structure
Choose one, but stick to it!
int x(string list[]) {
string maxString = list[0];
int maxSize = maxString.length();
for (i=1;i<list.length;++i)
if (list[i].length()>maxSize) {
maxString=list[i];
maxSize=maxString.length();
}
return maxSize;
}
int x(string list[])
{
string maxString = list[0];
int maxSize = maxString.length();
for (i=1;i<list.length;++i)
if (list[i].length()>maxSize)
{
maxString=list[i];
maxSize=maxString.length();
}
return maxSize;
}
14
use vertical alignment
Most editors suck and mess with vertical alignment.
Nevertheless, it is useful.
See the error?
Sprite tank=LoadSprite(”path/to/sprites/tank.png”);
Sprite chopper=LoadSprite(”path/to/sprtes/chopper.png”);
Sprite balloons=LoadSprite(”path/to/sprites/balloons.png”);
15
use vertical alignment
Most editors suck and mess with vertical alignment.
Nevertheless, it is useful.
See the error?
Sprite tank=LoadSprite(”path/to/sprites/tank.png”);
Sprite chopper=LoadSprite(”path/to/sprtes/chopper.png”);
Sprite balloons=LoadSprite(”path/to/sprites/balloons.png”);
And now?
Sprite tank = LoadSprite(”path/to/sprites/tank.png”);
Sprite chopper = LoadSprite(”path/to/sprtes/chopper.png”);
Sprite balloons = LoadSprite(”path/to/sprites/balloons.png”);
15
be explicit
C, Java and C# are tolerant, so you can write
if (foo < bar)
do_something(foo, bar);
Look, m’a! No curly brackets!
16
be explicit
C, Java and C# are tolerant, so you can write
if (foo < bar)
do_something(foo, bar);
Look, m’a! No curly brackets!
Problem? Later you might need to add an action and probably you
will add it like this:
if (foo < bar)
do_something(foo, bar);
do_something_else(foo, bar);
And does that do what you mean?
16
be explicit ii
So, how do you read this?
if (a < b)
if (b < c)
a = c;
else
c = b;
Or, more important, how does the compiler read it?
17
be explicit ii
So, how do you read this?
if (a < b)
if (b < c)
a = c;
else
c = b;
Or, more important, how does the compiler read it?
if (a < b)
if (b < c)
a = c;
else
c = b;
if (a < b)
if (b < c)
a = c;
else
c = b;
17
be explicit ii
Better with curly brackets!
if (a < b) {
if (b < c) {
a = c;
}
}
else {
c = b;
}
if (a < b) {
if (b < c) {
a = c;
}
else {
c = b;
}
}
Even without indentation you can understand it properly!!
And better! You do not need to know how the compiler interprets it.
18
use proper data structures
Implement related data as a data structure.
So, in pacman we have four ghosts. Store their positions.
int g1x, g1y, g2x, g2y, g3x, g3y, g4x, g4y;
19
use proper data structures
Implement related data as a data structure.
So, in pacman we have four ghosts. Store their positions.
int g1x, g1y, g2x, g2y, g3x, g3y, g4x, g4y;
There are only four, right? And it works!
19
use proper data structures
Implement related data as a data structure.
So, in pacman we have four ghosts. Store their positions.
int g1x, g1y, g2x, g2y, g3x, g3y, g4x, g4y;
There are only four, right? And it works!
Probably better:
class Pair { public int x, y; };
Pair[] ghost = new Pair[4];
// now use ghost[0].x, ghost[1].y, etc
19
code documentation
documentation
21
should it exist?
Real programmers don’t comment their code,
if it was hard to write,
it should be hard to understand and harder to modify.
— unknown
22
should it exist?
Real programmers don’t comment their code,
if it was hard to write,
it should be hard to understand and harder to modify.
— unknown
Kidding. It should really exist!
22
is this documentation?
/* Computes the length of the longer string */
int LongestString(string list[])
{
string maxString = list[0];
int maxSize = maxString.length();
for (i=1; i<list.length; i++) {
if (list[i].length() > maxSize) {
maxString = list[i];
maxSize = maxString.length();
}
}
return maxSize;
}
23
is this documentation?
/* Computes the length of the longer string */
int LongestString(string list[])
{
string maxString = list[0];
int maxSize = maxString.length();
for (i=1; i<list.length; i++) {
if (list[i].length() > maxSize) {
maxString = list[i];
maxSize = maxString.length();
}
}
return maxSize;
}
Not really!
23
documentation relevance
Documentation is like sex:
when it is good, it is very, very good;
and when it is bad, it is better than nothing.
— Dick Brandon (?)
24
documentation content
Try to include:
∙ What the code is about;
∙ What are each of the input arguments/parameters;
∙ What is the type and content of the returned value;
∙ If any of the method/function parameters are for output;
∙ What restrictions does the input values have?
∙ What happens when you do not follow that restriction?
∙ What exceptions are thrown directy?
∙ What exceptions are not catched and might be propagated?
∙ What is the algorithm?
25
use standards
Most programming languages have a standard documentation
approach:
∙ Perl has POD;
∙ Java has JavaDoc;
∙ Haskell has Hadock;
∙ C# has “XML Comments”;
∙ Python has Sphinx;
∙ C has Doxygen;
∙ C++ has Doxygen too;
∙ Lots of cross-language tools;
26
example: javadoc
/**
* Given an array of strings, compute the length of the
* longest string.
* <p>
* This method will not work for empty lists.
*
* @param list the list of strings to be processed;
* @return the size of the longest string
* in the array;
*/
int LongestString(string list[])
{
string maxString = list[0];
int maxSize = maxString.length();
for (i=1; i<list.length; i++) {
[...]
27
testing
testing
29
does this work?
int LongestString(string list[])
{
string maxString = list[0];
int maxSize = maxString.length();
for (i=1; i<list.length; i++) {
if (list[i].length() > maxSize) {
maxString = list[i];
maxSize = maxString.length();
}
}
return maxSize;
}
30
does this work?
int LongestString(string list[])
{
string maxString = list[0];
int maxSize = maxString.length();
for (i=1; i<list.length; i++) {
if (list[i].length() > maxSize) {
maxString = list[i];
maxSize = maxString.length();
}
}
return maxSize;
}
Always!?
30
does this work?
int LongestString(string list[])
{
string maxString = list[0];
int maxSize = maxString.length();
for (i=1; i<list.length; i++) {
if (list[i].length() > maxSize) {
maxString = list[i];
maxSize = maxString.length();
}
}
return maxSize;
}
Always!?
What happens on the empty list?
30
unit testing
∙ Different tools have different approaches/tools;
∙ The idea is the same: test!
31
unit testing
∙ Different tools have different approaches/tools;
∙ The idea is the same: test!
∙ What to test?
31
unit testing
∙ Different tools have different approaches/tools;
∙ The idea is the same: test!
∙ What to test?
∙ Everything!
∙ Test a simple case;
∙ Test a large case;
∙ Test weird cases;
∙ Test limit cases!
31
do it yourself testing
static class Test {
static void is(int a, int b) {
System.out.println( a == b ? ”ok” : ”nok” );
}
}
32
do it yourself testing
static class Test {
static void is(int a, int b) {
System.out.println( a == b ? ”ok” : ”nok” );
}
}
Then…
string[] array = { ”banana”, ”apple”, ”strawberry” };
Test.is( 10, LongestString(array) );
string[] array1 = { ”pear” };
Test.is( 4, LongestString(array) );
32
do it yourself testing
You can ever try and test if a method throws an exception!
static class Test {
static void throws(Runnable code, Class<?> class) {
boolean ok = false;
try {
code.run();
} catch (Exception e) {
if (e instanceof class) ok = true;
}
System.out.println( ok ? ”ok” : ”nok” );
}
}
Non Tested Code!
33
testing: why?
∙ To know your code is working;
∙ To know your code is still working;
∙ To know that your latest change does not mess with your
working code;
34
must read
How To Write Unmaintainable Code
by Roedy Green
https://www.thc.org/root/phun/unmaintain.html
Thank you!
35
1 of 61

Recommended

Datatypes by
DatatypesDatatypes
DatatypesZTE Nepal
422 views26 slides
Pycon Korea 2020 by
Pycon Korea 2020 Pycon Korea 2020
Pycon Korea 2020 jihoonkang29
468 views42 slides
A Closer Look at Data Types, Variables and Expressions by
A Closer Look at Data Types, Variables and ExpressionsA Closer Look at Data Types, Variables and Expressions
A Closer Look at Data Types, Variables and ExpressionsInan Mashrur
127 views22 slides
CSMR10c.ppt by
CSMR10c.pptCSMR10c.ppt
CSMR10c.pptPtidej Team
244 views24 slides
Measuring the Code Quality Using Software Metrics by
Measuring the Code Quality Using Software MetricsMeasuring the Code Quality Using Software Metrics
Measuring the Code Quality Using Software MetricsGeetha Anjali
7K views24 slides
Classification Systems by
Classification SystemsClassification Systems
Classification SystemsAlberto Simões
1.7K views65 slides

More Related Content

Similar to Source Code Quality

Perfect Code by
Perfect CodePerfect Code
Perfect CodeArtem Tabalin
7.7K views66 slides
ACM init() Spring 2015 Day 1 by
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1UCLA Association of Computing Machinery
666 views45 slides
Python Presentation by
Python PresentationPython Presentation
Python PresentationNarendra Sisodiya
89.3K views47 slides
Clean Code 2 by
Clean Code 2Clean Code 2
Clean Code 2Fredrik Wendt
2.6K views51 slides
Undefined behavior is closer than you think by
Undefined behavior is closer than you thinkUndefined behavior is closer than you think
Undefined behavior is closer than you thinkAndrey Karpov
335 views4 slides
Presentation 2nd by
Presentation 2ndPresentation 2nd
Presentation 2ndConnex
150 views30 slides

Similar to Source Code Quality(20)

Undefined behavior is closer than you think by Andrey Karpov
Undefined behavior is closer than you thinkUndefined behavior is closer than you think
Undefined behavior is closer than you think
Andrey Karpov335 views
Presentation 2nd by Connex
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex150 views
Keep Code Left - How to write better code in almost any language by Mick Andrew
Keep Code Left - How to write better code in almost any languageKeep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any language
Mick Andrew2.5K views
270 1 c_intro_up_to_functions by ray143eddie
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
ray143eddie52 views
270_1_CIntro_Up_To_Functions.ppt by Alefya1
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
Alefya14 views
Safety of 64-bit code by PVS-Studio
Safety of 64-bit codeSafety of 64-bit code
Safety of 64-bit code
PVS-Studio176 views
Contest Tips and Tricks by mbuzdalov
Contest Tips and TricksContest Tips and Tricks
Contest Tips and Tricks
mbuzdalov263 views
About size_t and ptrdiff_t by PVS-Studio
About size_t and ptrdiff_tAbout size_t and ptrdiff_t
About size_t and ptrdiff_t
PVS-Studio367 views
270_1_CIntro_Up_To_Functions.ppt by JoshCasas1
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
JoshCasas11 view
A 64-bit horse that can count by Andrey Karpov
A 64-bit horse that can countA 64-bit horse that can count
A 64-bit horse that can count
Andrey Karpov353 views

More from Alberto Simões

Language Identification: A neural network approach by
Language Identification: A neural network approachLanguage Identification: A neural network approach
Language Identification: A neural network approachAlberto Simões
2.2K views40 slides
Google Maps JS API by
Google Maps JS APIGoogle Maps JS API
Google Maps JS APIAlberto Simões
2.5K views55 slides
Making the most of a 100-year-old dictionary by
Making the most of a 100-year-old dictionaryMaking the most of a 100-year-old dictionary
Making the most of a 100-year-old dictionaryAlberto Simões
1.5K views42 slides
Dictionary Alignment by Rewrite-based Entry Translation by
Dictionary Alignment by Rewrite-based Entry TranslationDictionary Alignment by Rewrite-based Entry Translation
Dictionary Alignment by Rewrite-based Entry TranslationAlberto Simões
903 views23 slides
EMLex-A5: Specialized Dictionaries by
EMLex-A5: Specialized DictionariesEMLex-A5: Specialized Dictionaries
EMLex-A5: Specialized DictionariesAlberto Simões
2.9K views150 slides
Modelação de Dados by
Modelação de DadosModelação de Dados
Modelação de DadosAlberto Simões
5.8K views61 slides

More from Alberto Simões(20)

Language Identification: A neural network approach by Alberto Simões
Language Identification: A neural network approachLanguage Identification: A neural network approach
Language Identification: A neural network approach
Alberto Simões2.2K views
Making the most of a 100-year-old dictionary by Alberto Simões
Making the most of a 100-year-old dictionaryMaking the most of a 100-year-old dictionary
Making the most of a 100-year-old dictionary
Alberto Simões1.5K views
Dictionary Alignment by Rewrite-based Entry Translation by Alberto Simões
Dictionary Alignment by Rewrite-based Entry TranslationDictionary Alignment by Rewrite-based Entry Translation
Dictionary Alignment by Rewrite-based Entry Translation
Alberto Simões903 views
EMLex-A5: Specialized Dictionaries by Alberto Simões
EMLex-A5: Specialized DictionariesEMLex-A5: Specialized Dictionaries
EMLex-A5: Specialized Dictionaries
Alberto Simões2.9K views
Aula 04 - Introdução aos Diagramas de Sequência by Alberto Simões
Aula 04 - Introdução aos Diagramas de SequênciaAula 04 - Introdução aos Diagramas de Sequência
Aula 04 - Introdução aos Diagramas de Sequência
Alberto Simões1.2K views
Aula 03 - Introdução aos Diagramas de Atividade by Alberto Simões
Aula 03 - Introdução aos Diagramas de AtividadeAula 03 - Introdução aos Diagramas de Atividade
Aula 03 - Introdução aos Diagramas de Atividade
Alberto Simões3.8K views
Aula 02 - Engenharia de Requisitos by Alberto Simões
Aula 02 - Engenharia de RequisitosAula 02 - Engenharia de Requisitos
Aula 02 - Engenharia de Requisitos
Alberto Simões1.6K views
Aula 01 - Planeamento de Sistemas de Informação by Alberto Simões
Aula 01 - Planeamento de Sistemas de InformaçãoAula 01 - Planeamento de Sistemas de Informação
Aula 01 - Planeamento de Sistemas de Informação
Alberto Simões4.4K views
Building C and C++ libraries with Perl by Alberto Simões
Building C and C++ libraries with PerlBuilding C and C++ libraries with Perl
Building C and C++ libraries with Perl
Alberto Simões1.6K views
Processing XML: a rewriting system approach by Alberto Simões
Processing XML: a rewriting system approachProcessing XML: a rewriting system approach
Processing XML: a rewriting system approach
Alberto Simões854 views
Arquitecturas de Tradução Automática by Alberto Simões
Arquitecturas de Tradução AutomáticaArquitecturas de Tradução Automática
Arquitecturas de Tradução Automática
Alberto Simões751 views
Extracção de Recursos para Tradução Automática by Alberto Simões
Extracção de Recursos para Tradução AutomáticaExtracção de Recursos para Tradução Automática
Extracção de Recursos para Tradução Automática
Alberto Simões677 views

Recently uploaded

Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionMárton Kodok
15 views55 slides
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...sparkfabrik
8 views46 slides
Copilot Prompting Toolkit_All Resources.pdf by
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdfRiccardo Zamana
16 views4 slides
Software evolution understanding: Automatic extraction of software identifier... by
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...Ra'Fat Al-Msie'deen
10 views33 slides
Understanding HTML terminology by
Understanding HTML terminologyUnderstanding HTML terminology
Understanding HTML terminologyartembondar5
6 views8 slides
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptxNeo4j
17 views26 slides

Recently uploaded(20)

Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by Márton Kodok
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action
Márton Kodok15 views
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik8 views
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana16 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
Understanding HTML terminology by artembondar5
Understanding HTML terminologyUnderstanding HTML terminology
Understanding HTML terminology
artembondar56 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j17 views
Introduction to Git Source Control by John Valentino
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source Control
John Valentino6 views
Bootstrapping vs Venture Capital.pptx by Zeljko Svedic
Bootstrapping vs Venture Capital.pptxBootstrapping vs Venture Capital.pptx
Bootstrapping vs Venture Capital.pptx
Zeljko Svedic14 views
predicting-m3-devopsconMunich-2023.pptx by Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app7 views
How Workforce Management Software Empowers SMEs | TraQSuite by TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuiteHow Workforce Management Software Empowers SMEs | TraQSuite
How Workforce Management Software Empowers SMEs | TraQSuite
TraQSuite5 views
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports by Ra'Fat Al-Msie'deen
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable12 views
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta7 views
Myths and Facts About Hospice Care: Busting Common Misconceptions by Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
Top-5-production-devconMunich-2023.pptx by Tier1 app
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app8 views
Quality Engineer: A Day in the Life by John Valentino
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the Life
John Valentino7 views

Source Code Quality

  • 1. source code quality Alberto Simões March 10, 2015 – ESEIG-IPP – Vila do Conde Departamento de Informática Universidade do Minho
  • 4. no bad code initiative 3
  • 6. code problems ∙ Legibility Issues; ∙ Code should document itself; 4
  • 7. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; 4
  • 8. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! 4
  • 9. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; 4
  • 10. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; ∙ Documentation should exist; 4
  • 11. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; ∙ Documentation should exist; ∙ Documentation should follow standards; 4
  • 12. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; ∙ Documentation should exist; ∙ Documentation should follow standards; ∙ Documentation should document! 4
  • 13. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; ∙ Documentation should exist; ∙ Documentation should follow standards; ∙ Documentation should document! ∙ Testing Issues; 4
  • 14. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; ∙ Documentation should exist; ∙ Documentation should follow standards; ∙ Documentation should document! ∙ Testing Issues; ∙ Code should work on correct input; 4
  • 15. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; ∙ Documentation should exist; ∙ Documentation should follow standards; ∙ Documentation should document! ∙ Testing Issues; ∙ Code should work on correct input; ∙ Code should work on incorrect input; 4
  • 16. code problems ∙ Legibility Issues; ∙ Code should document itself; ∙ Code should be easy to read; ∙ Code should be elegant! ∙ Documentation Issues; ∙ Documentation should exist; ∙ Documentation should follow standards; ∙ Documentation should document! ∙ Testing Issues; ∙ Code should work on correct input; ∙ Code should work on incorrect input; ∙ Code should be tested on every change! 4
  • 19. use meaningful identifiers What does this code do? int x(string g[]) { string p = g[0]; int o = p.length(); for (z=1;z<g.length;++z) { if (g[z].length()>o) { p=g[z];o=p.length(); } } return o; } 7
  • 20. use meaningful identifiers Is this better? int x(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1;i<list.length;++i) { if (list[i].length()>maxSize) { maxString=list[i]; maxSize=maxString.length(); } } return maxSize; } 8
  • 21. use coherent indentation Do you prefer this… int x(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1;i<list.length;++i) { if (list[i].length()>maxSize) { maxString=list[i]; maxSize=maxString.length(); } } return maxSize; } 9
  • 22. use coherent indentation or this? int x(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1;i<list.length;++i) { if (list[i].length()>maxSize) { maxString=list[i]; maxSize=maxString.length(); } } return maxSize; } 10
  • 23. use coherent identifiers int x(string Lists[]) { string max_String = Lista[0]; int maxSize = max_String.length(); for (i=1;i<Lista.length;++i) { if (Lista[i].length()>maxSize) { max_String=Lista[i]; maxSize=max_String.length(); } } return maxSize; } 11
  • 24. use coherent identifiers Choose: ∙ One language: I prefer English given keywords are English, but any will work! 12
  • 25. use coherent identifiers Choose: ∙ One language: I prefer English given keywords are English, but any will work! ∙ Use one variable style: If you prefer use CamelCaseIdentifiers; Or, why not, underscores_identifiers; but not both! 12
  • 26. use coherent identifiers Choose: ∙ One language: I prefer English given keywords are English, but any will work! ∙ Use one variable style: If you prefer use CamelCaseIdentifiers; Or, why not, underscores_identifiers; but not both! ∙ Note that some languages have conventions: Java libraries use CamelCase; GNU Toolkit (GTK+) use underscores; So, probably a good idea to follow the flow… 12
  • 27. use standard code structure Does this work? int x(string list[]) { ; string maxString = list[0] ; int maxSize = maxString.length() ; for (i=1;i<list.length;++i) if (list[i].length()>maxSize) { ; maxString=list[i] ; maxSize=maxString.length() ; } ; return maxSize ; } Isn’t it cute? 13
  • 28. use standard and coherent code structure Choose one, but stick to it! int x(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1;i<list.length;++i) if (list[i].length()>maxSize) { maxString=list[i]; maxSize=maxString.length(); } return maxSize; } int x(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1;i<list.length;++i) if (list[i].length()>maxSize) { maxString=list[i]; maxSize=maxString.length(); } return maxSize; } 14
  • 29. use vertical alignment Most editors suck and mess with vertical alignment. Nevertheless, it is useful. See the error? Sprite tank=LoadSprite(”path/to/sprites/tank.png”); Sprite chopper=LoadSprite(”path/to/sprtes/chopper.png”); Sprite balloons=LoadSprite(”path/to/sprites/balloons.png”); 15
  • 30. use vertical alignment Most editors suck and mess with vertical alignment. Nevertheless, it is useful. See the error? Sprite tank=LoadSprite(”path/to/sprites/tank.png”); Sprite chopper=LoadSprite(”path/to/sprtes/chopper.png”); Sprite balloons=LoadSprite(”path/to/sprites/balloons.png”); And now? Sprite tank = LoadSprite(”path/to/sprites/tank.png”); Sprite chopper = LoadSprite(”path/to/sprtes/chopper.png”); Sprite balloons = LoadSprite(”path/to/sprites/balloons.png”); 15
  • 31. be explicit C, Java and C# are tolerant, so you can write if (foo < bar) do_something(foo, bar); Look, m’a! No curly brackets! 16
  • 32. be explicit C, Java and C# are tolerant, so you can write if (foo < bar) do_something(foo, bar); Look, m’a! No curly brackets! Problem? Later you might need to add an action and probably you will add it like this: if (foo < bar) do_something(foo, bar); do_something_else(foo, bar); And does that do what you mean? 16
  • 33. be explicit ii So, how do you read this? if (a < b) if (b < c) a = c; else c = b; Or, more important, how does the compiler read it? 17
  • 34. be explicit ii So, how do you read this? if (a < b) if (b < c) a = c; else c = b; Or, more important, how does the compiler read it? if (a < b) if (b < c) a = c; else c = b; if (a < b) if (b < c) a = c; else c = b; 17
  • 35. be explicit ii Better with curly brackets! if (a < b) { if (b < c) { a = c; } } else { c = b; } if (a < b) { if (b < c) { a = c; } else { c = b; } } Even without indentation you can understand it properly!! And better! You do not need to know how the compiler interprets it. 18
  • 36. use proper data structures Implement related data as a data structure. So, in pacman we have four ghosts. Store their positions. int g1x, g1y, g2x, g2y, g3x, g3y, g4x, g4y; 19
  • 37. use proper data structures Implement related data as a data structure. So, in pacman we have four ghosts. Store their positions. int g1x, g1y, g2x, g2y, g3x, g3y, g4x, g4y; There are only four, right? And it works! 19
  • 38. use proper data structures Implement related data as a data structure. So, in pacman we have four ghosts. Store their positions. int g1x, g1y, g2x, g2y, g3x, g3y, g4x, g4y; There are only four, right? And it works! Probably better: class Pair { public int x, y; }; Pair[] ghost = new Pair[4]; // now use ghost[0].x, ghost[1].y, etc 19
  • 41. should it exist? Real programmers don’t comment their code, if it was hard to write, it should be hard to understand and harder to modify. — unknown 22
  • 42. should it exist? Real programmers don’t comment their code, if it was hard to write, it should be hard to understand and harder to modify. — unknown Kidding. It should really exist! 22
  • 43. is this documentation? /* Computes the length of the longer string */ int LongestString(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1; i<list.length; i++) { if (list[i].length() > maxSize) { maxString = list[i]; maxSize = maxString.length(); } } return maxSize; } 23
  • 44. is this documentation? /* Computes the length of the longer string */ int LongestString(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1; i<list.length; i++) { if (list[i].length() > maxSize) { maxString = list[i]; maxSize = maxString.length(); } } return maxSize; } Not really! 23
  • 45. documentation relevance Documentation is like sex: when it is good, it is very, very good; and when it is bad, it is better than nothing. — Dick Brandon (?) 24
  • 46. documentation content Try to include: ∙ What the code is about; ∙ What are each of the input arguments/parameters; ∙ What is the type and content of the returned value; ∙ If any of the method/function parameters are for output; ∙ What restrictions does the input values have? ∙ What happens when you do not follow that restriction? ∙ What exceptions are thrown directy? ∙ What exceptions are not catched and might be propagated? ∙ What is the algorithm? 25
  • 47. use standards Most programming languages have a standard documentation approach: ∙ Perl has POD; ∙ Java has JavaDoc; ∙ Haskell has Hadock; ∙ C# has “XML Comments”; ∙ Python has Sphinx; ∙ C has Doxygen; ∙ C++ has Doxygen too; ∙ Lots of cross-language tools; 26
  • 48. example: javadoc /** * Given an array of strings, compute the length of the * longest string. * <p> * This method will not work for empty lists. * * @param list the list of strings to be processed; * @return the size of the longest string * in the array; */ int LongestString(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1; i<list.length; i++) { [...] 27
  • 51. does this work? int LongestString(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1; i<list.length; i++) { if (list[i].length() > maxSize) { maxString = list[i]; maxSize = maxString.length(); } } return maxSize; } 30
  • 52. does this work? int LongestString(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1; i<list.length; i++) { if (list[i].length() > maxSize) { maxString = list[i]; maxSize = maxString.length(); } } return maxSize; } Always!? 30
  • 53. does this work? int LongestString(string list[]) { string maxString = list[0]; int maxSize = maxString.length(); for (i=1; i<list.length; i++) { if (list[i].length() > maxSize) { maxString = list[i]; maxSize = maxString.length(); } } return maxSize; } Always!? What happens on the empty list? 30
  • 54. unit testing ∙ Different tools have different approaches/tools; ∙ The idea is the same: test! 31
  • 55. unit testing ∙ Different tools have different approaches/tools; ∙ The idea is the same: test! ∙ What to test? 31
  • 56. unit testing ∙ Different tools have different approaches/tools; ∙ The idea is the same: test! ∙ What to test? ∙ Everything! ∙ Test a simple case; ∙ Test a large case; ∙ Test weird cases; ∙ Test limit cases! 31
  • 57. do it yourself testing static class Test { static void is(int a, int b) { System.out.println( a == b ? ”ok” : ”nok” ); } } 32
  • 58. do it yourself testing static class Test { static void is(int a, int b) { System.out.println( a == b ? ”ok” : ”nok” ); } } Then… string[] array = { ”banana”, ”apple”, ”strawberry” }; Test.is( 10, LongestString(array) ); string[] array1 = { ”pear” }; Test.is( 4, LongestString(array) ); 32
  • 59. do it yourself testing You can ever try and test if a method throws an exception! static class Test { static void throws(Runnable code, Class<?> class) { boolean ok = false; try { code.run(); } catch (Exception e) { if (e instanceof class) ok = true; } System.out.println( ok ? ”ok” : ”nok” ); } } Non Tested Code! 33
  • 60. testing: why? ∙ To know your code is working; ∙ To know your code is still working; ∙ To know that your latest change does not mess with your working code; 34
  • 61. must read How To Write Unmaintainable Code by Roedy Green https://www.thc.org/root/phun/unmaintain.html Thank you! 35