SlideShare ist ein Scribd-Unternehmen logo
1 von 66
Downloaden Sie, um offline zu lesen
Perfect Code! 
How to write high-quality code! 
ARTEM TABALIN!
Motivation! 
Why should we always improve our code?! 
Why code that just works is not enough? !
Code Quality Control Law ! 
Improving code quality reduces development costs! 
Why?! 
Developer average productivity is! 
10-50 lines per day! 
Writing code – 10%! 
Reading code, testing, debugging – 90%! 
!
Productivity vs Time! 
Productivity decreases with entropy increasing! 
Time 
Productivity
Software Development Paradox! 
1. Low-quality code slows down development! 
2. Devs reduce code quality to meet a deadline! 
Paradox: “Devs have no time to work rapidly”! 
The clue: #2 is wrong! 
Impossible to successfully meet a deadline messing up the code! 
Continuously maintain high code quality!
The Boy Scout Rule! 
It’s not enough to write code well - prevent “rotting”! 
! 
“Leave the campground cleaner than you found it”! 
!
Software Development Principles! 
KISS, YAGNI, DRY, SOLID!
Keep Code Simple! 
KISS (Keep It Simple, Stupid)! 
Simplicity is a key goal! 
Components should be integrated tightly or weakly (?)! 
Try to reduce influence between components! 
Follow “Divide and Conquer” principle! 
!
Division of Responsibilities! 
• System → packages! 
• Package → classes! 
• Class → methods! 
• Method → control statements! 
Low coupling on each level!
Use Patterns! 
Don’t reinvent the square wheel! 
• Reduce complexity! 
• Less mistakes! 
• Simplify communication! 
! 
Examples: Repository, Factory, Adapter, Strategy, Observer!
No Unnecessary Code! 
YAGNI (You Aren’t Gonna Need It)! 
Implement things only when you really need them! 
!
Avoid Duplication! 
DRY (Don’t Repeat Yourself)! 
! 
“Every piece of knowledge must have a single, unambiguous, 
authoritative representation within a system.”! 
!
Object-Oriented Design! 
SOLID! 
1. Single Responsibility (SRP)! 
2. Open-Closed (OCP)! 
3. Liskov Substitution (LSP)! 
4. Interface Segregation (ISP)! 
5. Dependency Inversion (DIP)!
Single Responsibility Principle! 
“A class should have one and only one reason to change”! 
!
Open-Closed Principle! 
Class should be opened to extension and closed for modification! 
GraphicEditor 
+drawShape 
Shape 
+draw 
Rectangle 
+draw 
Circle 
+draw 
violation 
+drawCircle 
+drawRectangle 
+drawTriangle 
Triangle 
+draw
Liskov Substitution Principle! 
Objects implementing an interface can be used interchangeably! 
! 
GraphicEditor 
+resize(IResizable) 
IResizable 
+bounds 
+resize 
Shape 
+bounds 
+resize 
Image 
+bounds 
+resize 
violation 
resize(IResizable obj) { 
if(obj is TextBlock) 
return; 
obj.resize(); 
} 
TextBlock 
+bounds 
+resize
Interface Segregation Principle! 
Clients should not depend on interfaces they don’t use! 
! 
Shape 
+resize 
+move 
+select 
IResizable 
+resize 
violation 
IGraphic 
+resize 
+move 
+select 
ISelectable 
+select 
IMovable 
+move
Dependency Inversion Principle! 
Abstractions should not depend on details! 
GraphicEditor 
+logger: ILogger 
ILogger 
violation 
GraphicEditor() { 
logger = new FileLogger(); 
} 
EmailLogger FileLogger 
SystemLogger
Meaningful Names! 
Naming principles. Name length. Variable names. ! 
Class names. Method names.!
Naming Principles! 
Name should show your intention! 
int 
d; 
// 
elapsed 
time 
Is it good enough?! 
Which name is better?! 
int 
elapsedTimeInDays; 
int 
daysSinceCreation; 
! 
!
Naming Principles! 
What does the following code do?! 
function 
getItems(items) 
{ 
var 
list1 
= 
[]; 
for(var 
i 
= 
0; 
i 
< 
items.length; 
i++) 
{ 
var 
x 
= 
items[i]; 
if(items[i]["Field"] 
=== 
12) 
{ 
list1.push(x); 
} 
} 
return 
list1; 
} 
!
Naming Principles! 
What is about this one?! 
function 
getMarkedCells(cells) 
{ 
var 
result 
= 
[]; 
for(var 
i 
= 
0; 
i 
< 
cells.length; 
i++) 
{ 
var 
cell 
= 
cells[i]; 
if(cell.Status 
=== 
CellStatus.Marked) 
{ 
result.push(cell); 
} 
} 
return 
result; 
}
Naming Principles! 
No implementation details! 
HashSet<Account> 
accountHashSet; 
Is it good enough? Why?! 
What if we decide to use List?! 
Which name is better?! 
HashSet<Account> 
accounts; 
!
Naming Principles! 
Choose easy-to-pronounce name! 
class 
Cstmr 
{ 
private 
int 
prsnid; 
private 
DateTime 
genTstmp; 
private 
DateTime 
modTstmp; 
} 
class 
Customer 
{ 
private 
int 
personId; 
private 
DateTime 
generationTimestamp; 
private 
DateTime 
modificationTimestamp; 
} 
!
Naming Principles! 
• Single word for concept (avoid synonyms)! 
fetch / retrieve / get controller / manager / driver! 
• Names from patterns and algos! 
RenderStrategy, JobQueue! 
• Names from user stories! 
Credit, Debit, Asset! 
• Antonyms! 
begin / end first / last min / max next / previous! 
old / new opened / closed source / target up / down! 
!
Naming Convention! 
The most important is to follow to the convention! 
Example:! 
• CONSTANT 
• ClassName 
• localVariable 
• _privateMember
Name Length! 
What is the optimal length for a name?! 
x → maximumNumberOfPointsInEachLine 
short / long name pros & cons! 
short names – lacks of information! 
long names – harder to read and write! 
! 
10-16 characters is the optimal length! 
if < 10 ask: is meaningful enough?! 
if > 16 ask: isn’t verbose?!
Loop Variable Names! 
• Simple loop! 
for(int 
i 
= 
0; 
i 
< 
data.length; 
i++) 
{ 
data[i] 
= 
0; 
} 
• Complex loop! 
for(int 
teamIndex 
= 
0; 
teamIndex 
< 
teamCount; 
teamIndex++) 
{ 
for(int 
playerIndex 
= 
0; 
playerIndex 
< 
count; 
playerIndex++) 
{ 
playerStore[teamIndex][playerIndex] 
= 
0; 
} 
}!
Loop Variable Names! 
• Variable used outside of the loop 
int 
recordCount 
= 
0; 
while(moreRecords()) 
{ 
data[recordCount] 
= 
getNextRecord(); 
recordCount++; 
} 
// 
… 
recordCount 
is 
accessed 
here 
!
Temporary Variable Names! 
Avoid pointless names! 
temp 
= 
sqrt(b^2 
-­‐ 
4*a*c); 
root[0] 
= 
(-­‐b 
+ 
temp) 
/ 
(2*a); 
root[1] 
= 
(-­‐b 
-­‐ 
temp) 
/ 
(2*a); 
How to improve?! 
discriminant 
= 
sqrt(b^2 
-­‐ 
4*a*c); 
root[0] 
= 
(-­‐b 
+ 
discriminant) 
/ 
(2*a); 
root[1] 
= 
(-­‐b 
-­‐ 
discriminant) 
/ 
(2*a); 
!
Boolean Variables and Methods! 
Use verbs is, has, can for booleans! 
• isSupported! 
• hasNext! 
• canExecute!
Class Names! 
Use nouns and noun combinations for classes! 
• Client! 
• Window! 
• UserAccount! 
• FileLoader!
Method Names! 
Use verbs and verb phrases for methods! 
• Save! 
• Close! 
• GetAccount! 
• LoadFile!
Variables! 
Declaration. Initialization. Lifetime and scope.!
Declaration! 
• Declare all variables! 
• Turn off implicit variable declaration! 
JavaScript: 
“use 
strict” 
VB: 
Option 
Explicit 
On 
php: 
error_reporting(E_STRICT); 
!
Initialization! 
Initialize variables at declaration! 
var 
total 
= 
0; 
or at first occurrence in code! 
Dim 
total 
As 
Double 
' 
another 
code 
total 
= 
0.0 
' 
code 
using 
total 
!
Lifetime and Scope! 
Variables lifetime and scope should be minimal! 
Why?! 
Does code follow the principle?! 
function 
summarizeData() 
{ 
var 
oldData 
= 
getOldData(); 
var 
totalOldData 
= 
summarize(oldData); 
printData(totalOldData); 
saveData(totalOldData); 
var 
newData 
= 
getNewData(); 
var 
totalNewData 
= 
summarize(newData); 
printData(totalNewData); 
saveData(totalNewData); 
}
Lifetime and Scope! 
Code might look like! 
function 
summarizeData() 
{ 
var 
oldData 
= 
getOldData(); 
var 
newData 
= 
getNewData(); 
var 
totalOldData 
= 
summarize(oldData); 
var 
totalNewData 
= 
summarize(newData); 
printData(totalOldData); 
printData(totalNewData); 
saveData(totalOldData); 
saveData(totalNewData); 
} 
! 
!
Lifetime and Scope! 
• Single purpose principle! 
int 
value 
= 
getValue(); 
int 
result 
= 
calcResult(value); 
// 
some 
code 
value 
= 
val1; 
val1 
= 
val2; 
val2 
= 
value; 
• Avoid global variables! 
• Prefer the most restrictive access level! 
private → public! 
var 
swap 
= 
val1; 
val1 
= 
val2; 
val2 
= 
swap; 
→
Methods (Functions)! 
Purposes. Principles. Order. Parameters.!
Purposes! 
• Simplify code! 
• Improve readability! 
• Documentation defines abstraction! 
• Eliminating duplication most popular! 
• Inheritance support method overriding!
Principles! 
Method should be small! 
How many lines?! 
not more than 20 lines and better even less! 
Example:! 
public 
ReportContainer 
BuildReport(IList<Order> 
orders) 
{ 
var 
report 
= 
new 
ReportContainer(); 
report.Lines 
= 
BuildReportLines(orders); 
report.Total 
= 
BuildReportTotal(report.Lines); 
return 
report; 
} 
!
Principles! 
Method should have! 
• blocks (if, else, for, while) 1-3 lines long! 
• indent level not more than 2! 
private 
IList<ReportLine> 
BuildReportLines(IList<Order> 
orders) 
{ 
IList<ReportLine> 
result 
= 
new 
List<ReportLine>(); 
foreach 
(Order 
order 
in 
orders) 
{ 
ReportLine 
reportLine 
= 
BuildReportLine(order); 
if 
(reportLine.IsVisible) 
result.Add(reportLine); 
} 
return 
result; 
} 
!
Principles! 
Single Thing Rule! 
Function should do one thing, do it only, and do it well! 
Examples:! 
• BuildReport – makes report! 
• BuildReportLines – prepares report lines! 
• BuildReportTotal – summarizes report! 
Criteria: function cannot be divided into sections!
Principles! 
Single Abstraction Level! 
Mixing up abstraction levels increases complexity! 
Does code follow the principle? Why?! 
private 
Report 
BuildReport(Order 
order) 
{ 
var 
result 
= 
new 
Report(); 
result.Header 
= 
BuildReportHeader(order.Title); 
result.Body 
= 
ReportHelper.TextToHtml(order.Description); 
result.Footer 
= 
"<b>" 
+ 
APP_NAME 
+ 
"</b>"; 
result.Footer 
+= 
" 
CopyRight 
© 
" 
+ 
DateTime.Now.Year; 
return 
result; 
} 
!
Principles! 
Better! 
private 
Report 
BuildReport(Order 
order) 
{ 
var 
result 
= 
new 
Report(); 
result.Header 
= 
BuildReportHeader(order.Title); 
result.Body 
= 
ReportHelper.TextToHtml(order.Description); 
result.Footer 
= 
BuildReportFooter(); 
return 
result; 
} 
Much Better! 
private 
Report 
BuildReport(Order 
order) 
{ 
var 
result 
= 
new 
Report(); 
result.Header 
= 
BuildReportHeader(order.Title); 
result.Body 
= 
BuildReportBody(order.Description); 
result.Footer 
= 
BuildReportFooter(); 
return 
result; 
} 
!
Principles! 
Command-Query Separation (CQS)! 
Method performs an action OR returns data! 
Does code follow the principle?! 
if 
(SetAttribute("username", 
"Admin")) 
{ 
// 
code 
} 
How to fix? 
if 
(HasAttribute("username")) 
{ 
SetAttribute("username", 
"Admin"); 
// 
code 
}
Order! 
The Stepdown Rule! 
Read code from top to bottom (by abstraction levels)! 
public 
Report 
BuildReport(IList<Order> 
orders) 
{ 
// 
uses 
BuildReportLines 
and 
BuildReportTotal 
} 
private 
Report 
BuildReportLines(IList<Order> 
orders) 
{ 
// 
uses 
BuildReportLine 
} 
private 
Report 
BuildReportLine(IList<Order> 
orders) 
{ 
// 
code 
} 
private 
Report 
BuildReportTotal(IList<Order> 
orders) 
{ 
// 
code 
}
Arguments! 
How many parameters should a method have?! 
• Ideally 0! 
• Avoid methods with more than 2 arguments! 
Why?! 
• Harder to read (remember passing values)! 
• Increase coupling! 
• Harder to test (combinatorial growth of variants)!
Arguments! 
Avoid boolean arguments! 
Why?! 
• Usually can be divided into two sections! 
• Hard to understand a purpose of an argument! 
BuildReportLine(order, 
true); 
private 
Report 
BuildReportLine(Order 
order, 
bool 
isMarked) 
{ 
if 
(isMarked) 
{ 
// 
build 
marked 
report 
line 
} 
else 
{ 
// 
build 
simple 
report 
line 
} 
}
Classes! 
Purposes. Principles. Interface. Encapsulation. 
Inheritance.!
Purposes! 
• Simplify code 
• Improve readability! 
• Limit the scope of changes! 
• Hide implementation details (encapsulation)! 
• Allow to prepare generic solution (abstraction)! 
• Eliminate duplication (delegation & inheritance)! 
• Provide extensibility (inheritance)! 
• Allow to work with real domain entities!
Principles! 
• Encapsulation! 
Hide as much as possible! 
• Compactness! 
Reduce class responsibilities (SRP)! 
• Abstraction! 
Program to an interface, not an implementation! 
• High Cohesion! 
Fields and methods should belong together!
Interface! 
Methods should be on the same abstraction level! 
Does code follow the principle? Why?! 
class 
Program 
{ 
public 
void 
InitializeCommandStack(); 
public 
void 
PushCommand(Command 
command); 
public 
Command 
PopCommand(); 
public 
void 
ShutdownCommandStack(); 
public 
void 
InitializeReportFormatting(); 
public 
void 
FormatReport(Report 
report); 
public 
void 
PrintReport(Report 
report); 
public 
void 
InitializeGlobalData(); 
public 
void 
ShutdownGlobalData(); 
}
Interface! 
Programming over semantic! 
• Programming – can be checked by compiler! 
Amount of arguments! 
Argument types! 
• Semantic – cannot be checked by compiler! 
Method A should be called after method B! 
Method A throws exception when argument is not initialized! 
!
Encapsulation! 
• Not public should be private ! 
private → public! 
• No direct access to fields! 
private 
decimal 
_x 
= 
0; 
public 
decimal 
X 
{ 
get 
{ 
return 
_x; 
} 
set 
{ 
_x 
= 
value; 
} 
} 
• No assumptions about class clients! 
// 
param2 
should 
be 
> 
0, 
in 
other 
case 
method 
fails 
public 
int 
Method(int 
param1, 
int 
param2) 
!
Inheritance! 
Should be able to say that child ‘is’ parent! 
Circle is Shape HtmlParser is Parser! 
Does code follow the principle?! 
class 
Customer 
{ 
public 
int 
ID 
{ 
get; 
set; 
} 
public 
string 
Name 
{ 
get; 
set; 
} 
} 
class 
Bank: 
Customer 
{ 
public 
string 
CorrespondentAccount 
{ 
get; 
set; 
} 
} 
Depends on whether a bank can be a customer or not! 
!
Inheritance! 
Move common methods to base class! 
abstract 
class 
Stream 
{ 
public 
void 
Write(byte[] 
bytes); 
public 
byte[] 
Read(); 
} 
class 
SecureStream: 
Stream 
{ 
public 
void 
Init(StreamConfig 
config); 
} 
!
Inheritance! 
Avoid following situations:! 
• Parent class has only one child! 
• Child overrides method leaving it empty! 
• Too many hierarchy levels! 
better not more than 3 levels!
Comments! 
Commenting principles. Bad comments. Good 
comments.!
Commenting Principles! 
• Comments do not redress bad code! 
clean code much better than bad code with comments! 
• Do not comment tricky code – rewrite it! 
tricky code = bad code! 
• Try to explain with code! 
// 
is 
employee 
eligible 
for 
bonus 
if 
((employee.Schedule 
== 
HOURLY_SCHEDULE) 
&& 
employee.Age 
> 
65) 
{ 
… 
} 
! 
Better! 
if 
(employee.IsEligibleForBonus()) 
{ 
… 
}
Commenting Principles! 
Comment says “why” not “how”! 
• How! 
// 
if 
flag 
equals 
to 
zero 
if 
(accountFlag 
== 
0) 
• Why! 
// 
if 
new 
account 
created 
if 
(accountFlag 
== 
0) 
• Code instead of comment! 
if 
(accountType 
== 
AccountType.NewAccount)
Bad Comments! 
• Redundant comments! 
obvious and repeating code! 
// 
closing 
connection 
Connection.Close(); 
• Commented code! 
remove unnecessary code, VCS is for the rescue 
InputStream 
response 
= 
new 
InputStream(); 
response.SetBody(formatter.ResultStream, 
formatter.BytesCount); 
//InputStream 
resultStream 
= 
formatter.ResultStream; 
//StreamReader 
reader 
= 
new 
StreamReader(resultStream); 
//response.SetContent(reader.Read(formatter.BytesCount));
Good Comments! 
• Legal comments! 
license, copyright, author! 
• Explanations! 
provide info about inevitable tricks 
// 
NOTE: 
postpone 
execution 
to 
refresh 
UI 
setTimeout(function() 
{ 
// 
code 
}); 
• TODOs! 
notes for future to avoid “broken windows” 
// 
TODO: 
get 
rid 
of 
tricky 
workaround 
function 
badFunction() 
{ 
// 
tricky 
workaround 
here 
});
Thank you!! 
Your questions, please!! 
ARTEM TABALIN!
References! 
• Steve McConnell Code Complete! 
• Robert C. Martin Clean Code! 
• Hunt A., Thomas D. The Pragmatic Programmer ! 
• Craig Larman Applying UML and Patterns! 
• Kent Beck Implementation Patterns! 
• Eric Evans Domain-Driven Design!

Weitere ähnliche Inhalte

Was ist angesagt?

What is-sass-by-lucas-castro
What is-sass-by-lucas-castroWhat is-sass-by-lucas-castro
What is-sass-by-lucas-castroLucas Castro
 
10 Ways To Abuse T-SQL
10 Ways To Abuse T-SQL10 Ways To Abuse T-SQL
10 Ways To Abuse T-SQLTracy McKibben
 
Why are preprocessors divisive
Why are preprocessors divisiveWhy are preprocessors divisive
Why are preprocessors divisiveKianosh Pourian
 
Scala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityScala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityJaime Jorge
 
Active Record PowerPoint
Active Record PowerPointActive Record PowerPoint
Active Record PowerPointElizabeth Cruz
 
Know Before it Goes: Testing Your Email Design
Know Before it Goes: Testing Your Email DesignKnow Before it Goes: Testing Your Email Design
Know Before it Goes: Testing Your Email DesignLitmus
 
Funtional Ruby - Mikhail Bortnyk
Funtional Ruby - Mikhail BortnykFuntional Ruby - Mikhail Bortnyk
Funtional Ruby - Mikhail BortnykRuby Meditation
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonsecassuserfadb24
 
Graduates Gone Mad: Innovations in Software
Graduates Gone Mad: Innovations in SoftwareGraduates Gone Mad: Innovations in Software
Graduates Gone Mad: Innovations in SoftwareAlper Kanat
 
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can UseFive Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can UseSalesforce Developers
 
Spsbe using js-linkanddisplaytemplates
Spsbe   using js-linkanddisplaytemplatesSpsbe   using js-linkanddisplaytemplates
Spsbe using js-linkanddisplaytemplatesPaul Hunt
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassYogendra Rampuria
 
Functional programming
Functional programmingFunctional programming
Functional programmingPrateek Jain
 
Up to speed in domain driven design
Up to speed in domain driven designUp to speed in domain driven design
Up to speed in domain driven designRick van der Arend
 
06 integrating extra features and looking forward
06   integrating extra features and looking forward06   integrating extra features and looking forward
06 integrating extra features and looking forwardМарина Босова
 

Was ist angesagt? (20)

What is-sass-by-lucas-castro
What is-sass-by-lucas-castroWhat is-sass-by-lucas-castro
What is-sass-by-lucas-castro
 
10 Ways To Abuse T-SQL
10 Ways To Abuse T-SQL10 Ways To Abuse T-SQL
10 Ways To Abuse T-SQL
 
Testing gone-right
Testing gone-rightTesting gone-right
Testing gone-right
 
Why are preprocessors divisive
Why are preprocessors divisiveWhy are preprocessors divisive
Why are preprocessors divisive
 
Scala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityScala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and quality
 
Active Record PowerPoint
Active Record PowerPointActive Record PowerPoint
Active Record PowerPoint
 
Know Before it Goes: Testing Your Email Design
Know Before it Goes: Testing Your Email DesignKnow Before it Goes: Testing Your Email Design
Know Before it Goes: Testing Your Email Design
 
Productive development with react js
Productive development with react jsProductive development with react js
Productive development with react js
 
Funtional Ruby - Mikhail Bortnyk
Funtional Ruby - Mikhail BortnykFuntional Ruby - Mikhail Bortnyk
Funtional Ruby - Mikhail Bortnyk
 
Vimperl
VimperlVimperl
Vimperl
 
International SEO
International SEOInternational SEO
International SEO
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca
 
Graduates Gone Mad: Innovations in Software
Graduates Gone Mad: Innovations in SoftwareGraduates Gone Mad: Innovations in Software
Graduates Gone Mad: Innovations in Software
 
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can UseFive Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
 
Spsbe using js-linkanddisplaytemplates
Spsbe   using js-linkanddisplaytemplatesSpsbe   using js-linkanddisplaytemplates
Spsbe using js-linkanddisplaytemplates
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Up to speed in domain driven design
Up to speed in domain driven designUp to speed in domain driven design
Up to speed in domain driven design
 
06 integrating extra features and looking forward
06   integrating extra features and looking forward06   integrating extra features and looking forward
06 integrating extra features and looking forward
 
How To Write Beautiful Code
How To Write Beautiful CodeHow To Write Beautiful Code
How To Write Beautiful Code
 

Andere mochten auch

SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design PrinciplesAndreas Enbohm
 
A Software Architect's View On Diagramming
A Software Architect's View On DiagrammingA Software Architect's View On Diagramming
A Software Architect's View On Diagrammingmeghantaylor
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programmingAngelin R
 
Agile Agile: Adapting Practices to Support Explosive Growth by Ben Foster
Agile Agile: Adapting Practices to Support Explosive Growth by Ben FosterAgile Agile: Adapting Practices to Support Explosive Growth by Ben Foster
Agile Agile: Adapting Practices to Support Explosive Growth by Ben FosterLitheSpeed
 
Interview: a Learning Conversation
Interview: a Learning ConversationInterview: a Learning Conversation
Interview: a Learning ConversationJane Prusakova
 
Lets talk About Good Code (Dallas TechFest 2014)
Lets talk About Good Code (Dallas TechFest 2014)Lets talk About Good Code (Dallas TechFest 2014)
Lets talk About Good Code (Dallas TechFest 2014)Jane Prusakova
 
Smacss e-css-faz-bem
Smacss e-css-faz-bemSmacss e-css-faz-bem
Smacss e-css-faz-bemJust Digital
 
Guide to Human Activity System (HAS) Mapping
Guide to Human Activity System (HAS) MappingGuide to Human Activity System (HAS) Mapping
Guide to Human Activity System (HAS) MappingDavid Alman
 
Ewan developing the agile mindset for organizational agility
Ewan   developing the agile mindset for organizational agilityEwan   developing the agile mindset for organizational agility
Ewan developing the agile mindset for organizational agilityMagneta AI
 
вольфсон построение собственного Agile-фреймворка (шаблон)
вольфсон   построение собственного Agile-фреймворка (шаблон)вольфсон   построение собственного Agile-фреймворка (шаблон)
вольфсон построение собственного Agile-фреймворка (шаблон)Magneta AI
 
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...Theo Jungeblut
 
Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...
Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...
Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...Vu Hung Nguyen
 
Software Programming Principles
Software Programming PrinciplesSoftware Programming Principles
Software Programming PrinciplesSven Peters
 
GRASP Principles
GRASP PrinciplesGRASP Principles
GRASP PrinciplesRaheel Arif
 
The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Designguest446c0
 

Andere mochten auch (20)

Refactoring
RefactoringRefactoring
Refactoring
 
eXtreme Programming
eXtreme ProgrammingeXtreme Programming
eXtreme Programming
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 
A Software Architect's View On Diagramming
A Software Architect's View On DiagrammingA Software Architect's View On Diagramming
A Software Architect's View On Diagramming
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programming
 
Offline Web Apps
Offline Web AppsOffline Web Apps
Offline Web Apps
 
Agile Agile: Adapting Practices to Support Explosive Growth by Ben Foster
Agile Agile: Adapting Practices to Support Explosive Growth by Ben FosterAgile Agile: Adapting Practices to Support Explosive Growth by Ben Foster
Agile Agile: Adapting Practices to Support Explosive Growth by Ben Foster
 
Interview: a Learning Conversation
Interview: a Learning ConversationInterview: a Learning Conversation
Interview: a Learning Conversation
 
Lets talk About Good Code (Dallas TechFest 2014)
Lets talk About Good Code (Dallas TechFest 2014)Lets talk About Good Code (Dallas TechFest 2014)
Lets talk About Good Code (Dallas TechFest 2014)
 
Smacss e-css-faz-bem
Smacss e-css-faz-bemSmacss e-css-faz-bem
Smacss e-css-faz-bem
 
Guide to Human Activity System (HAS) Mapping
Guide to Human Activity System (HAS) MappingGuide to Human Activity System (HAS) Mapping
Guide to Human Activity System (HAS) Mapping
 
Ewan developing the agile mindset for organizational agility
Ewan   developing the agile mindset for organizational agilityEwan   developing the agile mindset for organizational agility
Ewan developing the agile mindset for organizational agility
 
вольфсон построение собственного Agile-фреймворка (шаблон)
вольфсон   построение собственного Agile-фреймворка (шаблон)вольфсон   построение собственного Agile-фреймворка (шаблон)
вольфсон построение собственного Agile-фреймворка (шаблон)
 
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
 
Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...
Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...
Nguyen Vu Hung: Beyond Agile - Practices and Mindset - Agile Tour Vietnam (Ha...
 
Design Smells
Design SmellsDesign Smells
Design Smells
 
Software Programming Principles
Software Programming PrinciplesSoftware Programming Principles
Software Programming Principles
 
GRASP Principles
GRASP PrinciplesGRASP Principles
GRASP Principles
 
The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Design
 

Ähnlich wie Perfect Code

Keep Code Left - How to write better code in almost any language
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 languageMick Andrew
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987乐群 陈
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practiceintive
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....Mike Harris
 
Techtalk design patterns
Techtalk design patternsTechtalk design patterns
Techtalk design patternsJan Berdajs
 
Chapter i c#(console application and programming)
Chapter i c#(console application and programming)Chapter i c#(console application and programming)
Chapter i c#(console application and programming)Chhom Karath
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!Gautam Rege
 
Test Driven Development - Workshop
Test Driven Development - WorkshopTest Driven Development - Workshop
Test Driven Development - WorkshopAnjana Somathilake
 
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureCoder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureThomas Pierrain
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patternsJeremy Duvall
 
Java Review
Java ReviewJava Review
Java Reviewpdgeorge
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersMohammed Mushtaq Ahmed
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Insidejeffz
 
Functional solid
Functional solidFunctional solid
Functional solidMatt Stine
 

Ähnlich wie Perfect Code (20)

Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Keep Code Left - How to write better code in almost any language
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
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practice
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
Techtalk design patterns
Techtalk design patternsTechtalk design patterns
Techtalk design patterns
 
Chapter i c#(console application and programming)
Chapter i c#(console application and programming)Chapter i c#(console application and programming)
Chapter i c#(console application and programming)
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!
 
Test Driven Development - Workshop
Test Driven Development - WorkshopTest Driven Development - Workshop
Test Driven Development - Workshop
 
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureCoder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architecture
 
Source Code Quality
Source Code QualitySource Code Quality
Source Code Quality
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
 
Java Review
Java ReviewJava Review
Java Review
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Inside
 
Python: The Dynamic!
Python: The Dynamic!Python: The Dynamic!
Python: The Dynamic!
 
Functional solid
Functional solidFunctional solid
Functional solid
 

Kürzlich hochgeladen

Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Kürzlich hochgeladen (20)

Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 

Perfect Code

  • 1. Perfect Code! How to write high-quality code! ARTEM TABALIN!
  • 2. Motivation! Why should we always improve our code?! Why code that just works is not enough? !
  • 3. Code Quality Control Law ! Improving code quality reduces development costs! Why?! Developer average productivity is! 10-50 lines per day! Writing code – 10%! Reading code, testing, debugging – 90%! !
  • 4. Productivity vs Time! Productivity decreases with entropy increasing! Time Productivity
  • 5. Software Development Paradox! 1. Low-quality code slows down development! 2. Devs reduce code quality to meet a deadline! Paradox: “Devs have no time to work rapidly”! The clue: #2 is wrong! Impossible to successfully meet a deadline messing up the code! Continuously maintain high code quality!
  • 6. The Boy Scout Rule! It’s not enough to write code well - prevent “rotting”! ! “Leave the campground cleaner than you found it”! !
  • 7. Software Development Principles! KISS, YAGNI, DRY, SOLID!
  • 8. Keep Code Simple! KISS (Keep It Simple, Stupid)! Simplicity is a key goal! Components should be integrated tightly or weakly (?)! Try to reduce influence between components! Follow “Divide and Conquer” principle! !
  • 9. Division of Responsibilities! • System → packages! • Package → classes! • Class → methods! • Method → control statements! Low coupling on each level!
  • 10. Use Patterns! Don’t reinvent the square wheel! • Reduce complexity! • Less mistakes! • Simplify communication! ! Examples: Repository, Factory, Adapter, Strategy, Observer!
  • 11. No Unnecessary Code! YAGNI (You Aren’t Gonna Need It)! Implement things only when you really need them! !
  • 12. Avoid Duplication! DRY (Don’t Repeat Yourself)! ! “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”! !
  • 13. Object-Oriented Design! SOLID! 1. Single Responsibility (SRP)! 2. Open-Closed (OCP)! 3. Liskov Substitution (LSP)! 4. Interface Segregation (ISP)! 5. Dependency Inversion (DIP)!
  • 14. Single Responsibility Principle! “A class should have one and only one reason to change”! !
  • 15. Open-Closed Principle! Class should be opened to extension and closed for modification! GraphicEditor +drawShape Shape +draw Rectangle +draw Circle +draw violation +drawCircle +drawRectangle +drawTriangle Triangle +draw
  • 16. Liskov Substitution Principle! Objects implementing an interface can be used interchangeably! ! GraphicEditor +resize(IResizable) IResizable +bounds +resize Shape +bounds +resize Image +bounds +resize violation resize(IResizable obj) { if(obj is TextBlock) return; obj.resize(); } TextBlock +bounds +resize
  • 17. Interface Segregation Principle! Clients should not depend on interfaces they don’t use! ! Shape +resize +move +select IResizable +resize violation IGraphic +resize +move +select ISelectable +select IMovable +move
  • 18. Dependency Inversion Principle! Abstractions should not depend on details! GraphicEditor +logger: ILogger ILogger violation GraphicEditor() { logger = new FileLogger(); } EmailLogger FileLogger SystemLogger
  • 19. Meaningful Names! Naming principles. Name length. Variable names. ! Class names. Method names.!
  • 20. Naming Principles! Name should show your intention! int d; // elapsed time Is it good enough?! Which name is better?! int elapsedTimeInDays; int daysSinceCreation; ! !
  • 21. Naming Principles! What does the following code do?! function getItems(items) { var list1 = []; for(var i = 0; i < items.length; i++) { var x = items[i]; if(items[i]["Field"] === 12) { list1.push(x); } } return list1; } !
  • 22. Naming Principles! What is about this one?! function getMarkedCells(cells) { var result = []; for(var i = 0; i < cells.length; i++) { var cell = cells[i]; if(cell.Status === CellStatus.Marked) { result.push(cell); } } return result; }
  • 23. Naming Principles! No implementation details! HashSet<Account> accountHashSet; Is it good enough? Why?! What if we decide to use List?! Which name is better?! HashSet<Account> accounts; !
  • 24. Naming Principles! Choose easy-to-pronounce name! class Cstmr { private int prsnid; private DateTime genTstmp; private DateTime modTstmp; } class Customer { private int personId; private DateTime generationTimestamp; private DateTime modificationTimestamp; } !
  • 25. Naming Principles! • Single word for concept (avoid synonyms)! fetch / retrieve / get controller / manager / driver! • Names from patterns and algos! RenderStrategy, JobQueue! • Names from user stories! Credit, Debit, Asset! • Antonyms! begin / end first / last min / max next / previous! old / new opened / closed source / target up / down! !
  • 26. Naming Convention! The most important is to follow to the convention! Example:! • CONSTANT • ClassName • localVariable • _privateMember
  • 27. Name Length! What is the optimal length for a name?! x → maximumNumberOfPointsInEachLine short / long name pros & cons! short names – lacks of information! long names – harder to read and write! ! 10-16 characters is the optimal length! if < 10 ask: is meaningful enough?! if > 16 ask: isn’t verbose?!
  • 28. Loop Variable Names! • Simple loop! for(int i = 0; i < data.length; i++) { data[i] = 0; } • Complex loop! for(int teamIndex = 0; teamIndex < teamCount; teamIndex++) { for(int playerIndex = 0; playerIndex < count; playerIndex++) { playerStore[teamIndex][playerIndex] = 0; } }!
  • 29. Loop Variable Names! • Variable used outside of the loop int recordCount = 0; while(moreRecords()) { data[recordCount] = getNextRecord(); recordCount++; } // … recordCount is accessed here !
  • 30. Temporary Variable Names! Avoid pointless names! temp = sqrt(b^2 -­‐ 4*a*c); root[0] = (-­‐b + temp) / (2*a); root[1] = (-­‐b -­‐ temp) / (2*a); How to improve?! discriminant = sqrt(b^2 -­‐ 4*a*c); root[0] = (-­‐b + discriminant) / (2*a); root[1] = (-­‐b -­‐ discriminant) / (2*a); !
  • 31. Boolean Variables and Methods! Use verbs is, has, can for booleans! • isSupported! • hasNext! • canExecute!
  • 32. Class Names! Use nouns and noun combinations for classes! • Client! • Window! • UserAccount! • FileLoader!
  • 33. Method Names! Use verbs and verb phrases for methods! • Save! • Close! • GetAccount! • LoadFile!
  • 35. Declaration! • Declare all variables! • Turn off implicit variable declaration! JavaScript: “use strict” VB: Option Explicit On php: error_reporting(E_STRICT); !
  • 36. Initialization! Initialize variables at declaration! var total = 0; or at first occurrence in code! Dim total As Double ' another code total = 0.0 ' code using total !
  • 37. Lifetime and Scope! Variables lifetime and scope should be minimal! Why?! Does code follow the principle?! function summarizeData() { var oldData = getOldData(); var totalOldData = summarize(oldData); printData(totalOldData); saveData(totalOldData); var newData = getNewData(); var totalNewData = summarize(newData); printData(totalNewData); saveData(totalNewData); }
  • 38. Lifetime and Scope! Code might look like! function summarizeData() { var oldData = getOldData(); var newData = getNewData(); var totalOldData = summarize(oldData); var totalNewData = summarize(newData); printData(totalOldData); printData(totalNewData); saveData(totalOldData); saveData(totalNewData); } ! !
  • 39. Lifetime and Scope! • Single purpose principle! int value = getValue(); int result = calcResult(value); // some code value = val1; val1 = val2; val2 = value; • Avoid global variables! • Prefer the most restrictive access level! private → public! var swap = val1; val1 = val2; val2 = swap; →
  • 40. Methods (Functions)! Purposes. Principles. Order. Parameters.!
  • 41. Purposes! • Simplify code! • Improve readability! • Documentation defines abstraction! • Eliminating duplication most popular! • Inheritance support method overriding!
  • 42. Principles! Method should be small! How many lines?! not more than 20 lines and better even less! Example:! public ReportContainer BuildReport(IList<Order> orders) { var report = new ReportContainer(); report.Lines = BuildReportLines(orders); report.Total = BuildReportTotal(report.Lines); return report; } !
  • 43. Principles! Method should have! • blocks (if, else, for, while) 1-3 lines long! • indent level not more than 2! private IList<ReportLine> BuildReportLines(IList<Order> orders) { IList<ReportLine> result = new List<ReportLine>(); foreach (Order order in orders) { ReportLine reportLine = BuildReportLine(order); if (reportLine.IsVisible) result.Add(reportLine); } return result; } !
  • 44. Principles! Single Thing Rule! Function should do one thing, do it only, and do it well! Examples:! • BuildReport – makes report! • BuildReportLines – prepares report lines! • BuildReportTotal – summarizes report! Criteria: function cannot be divided into sections!
  • 45. Principles! Single Abstraction Level! Mixing up abstraction levels increases complexity! Does code follow the principle? Why?! private Report BuildReport(Order order) { var result = new Report(); result.Header = BuildReportHeader(order.Title); result.Body = ReportHelper.TextToHtml(order.Description); result.Footer = "<b>" + APP_NAME + "</b>"; result.Footer += " CopyRight © " + DateTime.Now.Year; return result; } !
  • 46. Principles! Better! private Report BuildReport(Order order) { var result = new Report(); result.Header = BuildReportHeader(order.Title); result.Body = ReportHelper.TextToHtml(order.Description); result.Footer = BuildReportFooter(); return result; } Much Better! private Report BuildReport(Order order) { var result = new Report(); result.Header = BuildReportHeader(order.Title); result.Body = BuildReportBody(order.Description); result.Footer = BuildReportFooter(); return result; } !
  • 47. Principles! Command-Query Separation (CQS)! Method performs an action OR returns data! Does code follow the principle?! if (SetAttribute("username", "Admin")) { // code } How to fix? if (HasAttribute("username")) { SetAttribute("username", "Admin"); // code }
  • 48. Order! The Stepdown Rule! Read code from top to bottom (by abstraction levels)! public Report BuildReport(IList<Order> orders) { // uses BuildReportLines and BuildReportTotal } private Report BuildReportLines(IList<Order> orders) { // uses BuildReportLine } private Report BuildReportLine(IList<Order> orders) { // code } private Report BuildReportTotal(IList<Order> orders) { // code }
  • 49. Arguments! How many parameters should a method have?! • Ideally 0! • Avoid methods with more than 2 arguments! Why?! • Harder to read (remember passing values)! • Increase coupling! • Harder to test (combinatorial growth of variants)!
  • 50. Arguments! Avoid boolean arguments! Why?! • Usually can be divided into two sections! • Hard to understand a purpose of an argument! BuildReportLine(order, true); private Report BuildReportLine(Order order, bool isMarked) { if (isMarked) { // build marked report line } else { // build simple report line } }
  • 51. Classes! Purposes. Principles. Interface. Encapsulation. Inheritance.!
  • 52. Purposes! • Simplify code • Improve readability! • Limit the scope of changes! • Hide implementation details (encapsulation)! • Allow to prepare generic solution (abstraction)! • Eliminate duplication (delegation & inheritance)! • Provide extensibility (inheritance)! • Allow to work with real domain entities!
  • 53. Principles! • Encapsulation! Hide as much as possible! • Compactness! Reduce class responsibilities (SRP)! • Abstraction! Program to an interface, not an implementation! • High Cohesion! Fields and methods should belong together!
  • 54. Interface! Methods should be on the same abstraction level! Does code follow the principle? Why?! class Program { public void InitializeCommandStack(); public void PushCommand(Command command); public Command PopCommand(); public void ShutdownCommandStack(); public void InitializeReportFormatting(); public void FormatReport(Report report); public void PrintReport(Report report); public void InitializeGlobalData(); public void ShutdownGlobalData(); }
  • 55. Interface! Programming over semantic! • Programming – can be checked by compiler! Amount of arguments! Argument types! • Semantic – cannot be checked by compiler! Method A should be called after method B! Method A throws exception when argument is not initialized! !
  • 56. Encapsulation! • Not public should be private ! private → public! • No direct access to fields! private decimal _x = 0; public decimal X { get { return _x; } set { _x = value; } } • No assumptions about class clients! // param2 should be > 0, in other case method fails public int Method(int param1, int param2) !
  • 57. Inheritance! Should be able to say that child ‘is’ parent! Circle is Shape HtmlParser is Parser! Does code follow the principle?! class Customer { public int ID { get; set; } public string Name { get; set; } } class Bank: Customer { public string CorrespondentAccount { get; set; } } Depends on whether a bank can be a customer or not! !
  • 58. Inheritance! Move common methods to base class! abstract class Stream { public void Write(byte[] bytes); public byte[] Read(); } class SecureStream: Stream { public void Init(StreamConfig config); } !
  • 59. Inheritance! Avoid following situations:! • Parent class has only one child! • Child overrides method leaving it empty! • Too many hierarchy levels! better not more than 3 levels!
  • 60. Comments! Commenting principles. Bad comments. Good comments.!
  • 61. Commenting Principles! • Comments do not redress bad code! clean code much better than bad code with comments! • Do not comment tricky code – rewrite it! tricky code = bad code! • Try to explain with code! // is employee eligible for bonus if ((employee.Schedule == HOURLY_SCHEDULE) && employee.Age > 65) { … } ! Better! if (employee.IsEligibleForBonus()) { … }
  • 62. Commenting Principles! Comment says “why” not “how”! • How! // if flag equals to zero if (accountFlag == 0) • Why! // if new account created if (accountFlag == 0) • Code instead of comment! if (accountType == AccountType.NewAccount)
  • 63. Bad Comments! • Redundant comments! obvious and repeating code! // closing connection Connection.Close(); • Commented code! remove unnecessary code, VCS is for the rescue InputStream response = new InputStream(); response.SetBody(formatter.ResultStream, formatter.BytesCount); //InputStream resultStream = formatter.ResultStream; //StreamReader reader = new StreamReader(resultStream); //response.SetContent(reader.Read(formatter.BytesCount));
  • 64. Good Comments! • Legal comments! license, copyright, author! • Explanations! provide info about inevitable tricks // NOTE: postpone execution to refresh UI setTimeout(function() { // code }); • TODOs! notes for future to avoid “broken windows” // TODO: get rid of tricky workaround function badFunction() { // tricky workaround here });
  • 65. Thank you!! Your questions, please!! ARTEM TABALIN!
  • 66. References! • Steve McConnell Code Complete! • Robert C. Martin Clean Code! • Hunt A., Thomas D. The Pragmatic Programmer ! • Craig Larman Applying UML and Patterns! • Kent Beck Implementation Patterns! • Eric Evans Domain-Driven Design!