SlideShare a Scribd company logo
From Clever code to Better code
Dror Helper (@dhelper)
About.ME
Consultant & software architect @ Practical Software
Developing software since 2002
Clean Coder & Test-Driven Developer
Pluralsight author
Blogger: http://helpercode.com
Twitter: @dhelper
A long time ago,
in an office not that far from here . . . .
#define GET_VAL(val, type) 
{ 
ASSERT(( pIP + sizeof(type)) <= pMethodEnd); 
val = ( *((type *&)(pIP))++); 
}
What this code does now I understand, clever it is!
Why do we write clever code?
Because we
can
Because we
must
We don’t know
any better
Performance
void send(short* from, short* to, size_t count) {
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while (--n > 0);
}
}
n = 2
12
<-- 4
--->
--->
--->
--->
n = 1
--->
--->
--->
--->
REALITY CHECK:
We write Clever Code because it makes us feel
good
/* Most programmers love to be clever */
There is more than one
way to write
Clever Code
public void int GetNextSize(int i)
{
return i > 0 ? i << 2 : ~(i << 2) + 1;
}
public void int GetNextSize(int i)
{
return Math.Abs(i * 4);
}
if((i & (i - 1) == 0)
{
...
}
if(IsPowerOfTwo(i))
{
...
}
public bool IsPowerOfTwo(int i)
{
return ((i & (i - 1) == 0;
}
1000 & 0111 --> 0
Low level programming
Avoid if you can
Refactor to show intent
Compressed code
a = y[0]>y[1] ? (b=1,0) : (b=0,1);
a = (y[0] > y[1] ?
(Func<int>)(() => { b = 1; return 0; }) :
() => { b = 0; return 1; })
.Invoke();
Compressed code
a = y[0]>y[1] ? (b=1,0) : (b=0,1);
if(y[0] > y[1]){
a = 0;
b = 1;
} else {
a = 1;
b = 0;
}
Abusing the trinary operator
var name = ((GetAllNamesAsDelimitedString().contains(name) ?
name:
(GetEntityOperationMap().Count() == 0) ?
null :
GetEntityOperationMap.get(name))));
Tricky loops
for (Dog dog = animal as Dog; dog != null; dog = null) {
dog.bark();
}
http://www.mikece.com/2015/08/clean-code-vs-really-clever-code/
Dog dog = animal as Dog;
if(dog != null)
{
dog.Bark();
}
Tricky loops
int i;
for(i = 0 ; callMe() != null ; i++);
http://www.mikece.com/2015/08/clean-code-vs-really-clever-code/
for(n = 0 ; n != 0;) {
n = ReadNewValue();
// do something
}
do
{
n = ReadNewValue();
// do something
} while(n != 0);
do{
// code goes here
if(some condition)
break;
// ...
if(other condition)
break;
// ...
} while(false)
// cleanup here
try{
// code goes here
if(some condition)
break;
// ...
if(other condition)
break;
// ...
} finally {
// cleanup here
public class Tree<T> {
public T Value { get; }
public Tree<T> Left { get; }
public Tree<T> Right { get; }
public void Find(T value)
{
if(Value.Equals(value))
throw new FoundElementException<T>(this);
Left?.Find(value);
Right?.Find(value);
}
}
Creative (ab)use
Don’t surprise the reader!
Think of a better way to express yourself
public Task<Client> GetClientAsync(string clientId) {
var client = _clientDal.FindClientById(clientId);
if(client == null) {
var client = CreateNewClient();
await _clientDal.SaveClient(client);
_notificationQueue.Push(NewClientCreatedNotification);
...
var company = new Company(clientId, "temp");
var account = CreateAccount(clientId, company);
_accountDao.Save(account);
_operationEvents.Send(new Notification(company, account));
}
return client;
}
Complex != Clever
Follow best practices/design patterns
Use clean code guidelines
And your common sense
/* Otherwise: you’ll regret it.
Maybe not today. Maybe not tomorrow,
but soon and for the rest of your life. */
class O1
{
private string myPrivateField;
}
class O2
{
public string publicField;
}
[StructLayout(LayoutKind.Explicit)]
struct FastReflectionAdapter
{
[FieldOffset(0)]
internal object o1;
[FieldOffset(0)]
internal O2 o2;
}
var adapter = new FastReflectionAdapter { o1 = new O1("Foo") };
var privateValue = adapter.o2.publicField;
https://twitter.com/korifey_ad/status/1169210959426183168
What’s so wrong with a little “cleverness”?
Writing < Reading < Debugging
“A clever person solves a problem.
A wise person avoids it.”
Albert Einstein
void calculate(struct salesinfo* sales)
{
jmp_buf buffer;
int i=setjmp(buffer);
if (!(i<sales->count))
RETURN_NOTHING;
addToSubtotal(sales->values[i]);
if (i<sales->count)
{
longjmp(buffer,i+1);
}
}
void calculate(struct salesinfo*sales)
{
for(int i = 0; i < sales->count; i++)
{
addToSubtotal(sales->values[i]);
}
}
Real optimizations
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = *(int*)&x;
i = 0x5f375a86 - (i >> 1);
x = *(float*)&i;
x = x * (1.5f - xhalf * x * x);
return x;
}
http://www.lomont.org/papers/2003/InvSqrt.pdf
Is clever code
Good or Evil?
public string GetPropertyName<T>(Expression<Func<T, object>> property)
{
LambdaExpression lambda = (LambdaExpression)property;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
UnaryExpression unaryExpression = (UnaryExpression)(lambda.Body);
memberExpression = (MemberExpression)(unaryExpression.Operand);
}
else
{
memberExpression = (MemberExpression)(lambda.Body);
}
return ((PropertyInfo)memberExpression.Member).Name;
}
OnPropertyChanged(GetPropertyName<User>(u => u.Address))
#define GET_VAL( val, type ) 
{ 
ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); 
val = ( *((type *&)(pIP))++ ); 
}
void parseCode(BYTE* pIp, BYTE* pMethodEnd)
{
int valueType = getValueType(pIp)
while(pIp < pMethodEnd)
{
switch(valueType){
case ValueType::INT:
int value;
GET_VAL(value, int)
// do something with value
break;
case ValueType::BYTE:
...
}
}
}
Dror Helper | @ dhelper | http://helpercode.com
Thank you!
From clever code to better code

More Related Content

What's hot

Program for hamming code using c
Program for hamming code using cProgram for hamming code using c
Program for hamming code using c
snsanth
 

What's hot (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Lecture20
Lecture20Lecture20
Lecture20
 
C++ TUTORIAL 2
C++ TUTORIAL 2C++ TUTORIAL 2
C++ TUTORIAL 2
 
What\'s New in C# 4.0
What\'s New in C# 4.0What\'s New in C# 4.0
What\'s New in C# 4.0
 
Qno 1 (d)
Qno 1 (d)Qno 1 (d)
Qno 1 (d)
 
informatics practices practical file
informatics practices practical fileinformatics practices practical file
informatics practices practical file
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTs
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Static and const members
Static and const membersStatic and const members
Static and const members
 
C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
901131 examples
901131 examples901131 examples
901131 examples
 
Program for hamming code using c
Program for hamming code using cProgram for hamming code using c
Program for hamming code using c
 
Useful c programs
Useful c programsUseful c programs
Useful c programs
 
PHPSpec BDD Framework
PHPSpec BDD FrameworkPHPSpec BDD Framework
PHPSpec BDD Framework
 
Pointer
PointerPointer
Pointer
 
Qno 1 (e)
Qno 1 (e)Qno 1 (e)
Qno 1 (e)
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 

Similar to From clever code to better code

OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...
Paris Open Source Summit
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
Baidu, Inc.
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Victor Rentea
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon Berlin
 

Similar to From clever code to better code (20)

Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Refactoring
RefactoringRefactoring
Refactoring
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Priming Java for Speed at Market Open
Priming Java for Speed at Market OpenPriming Java for Speed at Market Open
Priming Java for Speed at Market Open
 
Refactoring
RefactoringRefactoring
Refactoring
 
OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
Building Hierarchy
Building HierarchyBuilding Hierarchy
Building Hierarchy
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDKEric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
 
Clean Code
Clean CodeClean Code
Clean Code
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
MySQL Stored Procedures: Building High Performance Web Applications
MySQL Stored Procedures: Building High Performance Web ApplicationsMySQL Stored Procedures: Building High Performance Web Applications
MySQL Stored Procedures: Building High Performance Web Applications
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 

More from Dror Helper

More from Dror Helper (20)

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'
 
A software developer guide to working with aws
A software developer guide to working with awsA software developer guide to working with aws
A software developer guide to working with aws
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you about
 
The role of the architect in agile
The role of the architect in agileThe role of the architect in agile
The role of the architect in agile
 
Harnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreHarnessing the power of aws using dot net core
Harnessing the power of aws using dot net core
 
Developing multi-platform microservices using .NET core
 Developing multi-platform microservices using .NET core Developing multi-platform microservices using .NET core
Developing multi-platform microservices using .NET core
 
Harnessing the power of aws using dot net
Harnessing the power of aws using dot netHarnessing the power of aws using dot net
Harnessing the power of aws using dot net
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
C++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyC++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the ugly
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy code
 
Visual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowVisual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should know
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing tools
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developers
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbg
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Designing with tests
Designing with testsDesigning with tests
Designing with tests
 

Recently uploaded

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 

From clever code to better code

  • 1. From Clever code to Better code Dror Helper (@dhelper)
  • 2. About.ME Consultant & software architect @ Practical Software Developing software since 2002 Clean Coder & Test-Driven Developer Pluralsight author Blogger: http://helpercode.com Twitter: @dhelper
  • 3. A long time ago, in an office not that far from here . . . .
  • 4. #define GET_VAL(val, type) { ASSERT(( pIP + sizeof(type)) <= pMethodEnd); val = ( *((type *&)(pIP))++); }
  • 5. What this code does now I understand, clever it is!
  • 6.
  • 7. Why do we write clever code? Because we can Because we must We don’t know any better Performance
  • 8. void send(short* from, short* to, size_t count) { int n = (count + 7) / 8; switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n > 0); } } n = 2 12 <-- 4 ---> ---> ---> ---> n = 1 ---> ---> ---> --->
  • 9. REALITY CHECK: We write Clever Code because it makes us feel good /* Most programmers love to be clever */
  • 10. There is more than one way to write Clever Code
  • 11. public void int GetNextSize(int i) { return i > 0 ? i << 2 : ~(i << 2) + 1; } public void int GetNextSize(int i) { return Math.Abs(i * 4); }
  • 12. if((i & (i - 1) == 0) { ... } if(IsPowerOfTwo(i)) { ... } public bool IsPowerOfTwo(int i) { return ((i & (i - 1) == 0; } 1000 & 0111 --> 0
  • 13. Low level programming Avoid if you can Refactor to show intent
  • 14.
  • 15. Compressed code a = y[0]>y[1] ? (b=1,0) : (b=0,1); a = (y[0] > y[1] ? (Func<int>)(() => { b = 1; return 0; }) : () => { b = 0; return 1; }) .Invoke();
  • 16. Compressed code a = y[0]>y[1] ? (b=1,0) : (b=0,1); if(y[0] > y[1]){ a = 0; b = 1; } else { a = 1; b = 0; }
  • 17. Abusing the trinary operator var name = ((GetAllNamesAsDelimitedString().contains(name) ? name: (GetEntityOperationMap().Count() == 0) ? null : GetEntityOperationMap.get(name))));
  • 18.
  • 19. Tricky loops for (Dog dog = animal as Dog; dog != null; dog = null) { dog.bark(); } http://www.mikece.com/2015/08/clean-code-vs-really-clever-code/ Dog dog = animal as Dog; if(dog != null) { dog.Bark(); }
  • 20. Tricky loops int i; for(i = 0 ; callMe() != null ; i++); http://www.mikece.com/2015/08/clean-code-vs-really-clever-code/
  • 21. for(n = 0 ; n != 0;) { n = ReadNewValue(); // do something } do { n = ReadNewValue(); // do something } while(n != 0);
  • 22. do{ // code goes here if(some condition) break; // ... if(other condition) break; // ... } while(false) // cleanup here
  • 23. try{ // code goes here if(some condition) break; // ... if(other condition) break; // ... } finally { // cleanup here
  • 24. public class Tree<T> { public T Value { get; } public Tree<T> Left { get; } public Tree<T> Right { get; } public void Find(T value) { if(Value.Equals(value)) throw new FoundElementException<T>(this); Left?.Find(value); Right?.Find(value); } }
  • 25. Creative (ab)use Don’t surprise the reader! Think of a better way to express yourself
  • 26. public Task<Client> GetClientAsync(string clientId) { var client = _clientDal.FindClientById(clientId); if(client == null) { var client = CreateNewClient(); await _clientDal.SaveClient(client); _notificationQueue.Push(NewClientCreatedNotification); ... var company = new Company(clientId, "temp"); var account = CreateAccount(clientId, company); _accountDao.Save(account); _operationEvents.Send(new Notification(company, account)); } return client; }
  • 27. Complex != Clever Follow best practices/design patterns Use clean code guidelines And your common sense /* Otherwise: you’ll regret it. Maybe not today. Maybe not tomorrow, but soon and for the rest of your life. */
  • 28. class O1 { private string myPrivateField; } class O2 { public string publicField; } [StructLayout(LayoutKind.Explicit)] struct FastReflectionAdapter { [FieldOffset(0)] internal object o1; [FieldOffset(0)] internal O2 o2; } var adapter = new FastReflectionAdapter { o1 = new O1("Foo") }; var privateValue = adapter.o2.publicField; https://twitter.com/korifey_ad/status/1169210959426183168
  • 29. What’s so wrong with a little “cleverness”? Writing < Reading < Debugging
  • 30. “A clever person solves a problem. A wise person avoids it.” Albert Einstein
  • 31.
  • 32. void calculate(struct salesinfo* sales) { jmp_buf buffer; int i=setjmp(buffer); if (!(i<sales->count)) RETURN_NOTHING; addToSubtotal(sales->values[i]); if (i<sales->count) { longjmp(buffer,i+1); } } void calculate(struct salesinfo*sales) { for(int i = 0; i < sales->count; i++) { addToSubtotal(sales->values[i]); } }
  • 33. Real optimizations float InvSqrt(float x) { float xhalf = 0.5f * x; int i = *(int*)&x; i = 0x5f375a86 - (i >> 1); x = *(float*)&i; x = x * (1.5f - xhalf * x * x); return x; } http://www.lomont.org/papers/2003/InvSqrt.pdf
  • 35. public string GetPropertyName<T>(Expression<Func<T, object>> property) { LambdaExpression lambda = (LambdaExpression)property; MemberExpression memberExpression; if (lambda.Body is UnaryExpression) { UnaryExpression unaryExpression = (UnaryExpression)(lambda.Body); memberExpression = (MemberExpression)(unaryExpression.Operand); } else { memberExpression = (MemberExpression)(lambda.Body); } return ((PropertyInfo)memberExpression.Member).Name; } OnPropertyChanged(GetPropertyName<User>(u => u.Address))
  • 36. #define GET_VAL( val, type ) { ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); val = ( *((type *&)(pIP))++ ); } void parseCode(BYTE* pIp, BYTE* pMethodEnd) { int valueType = getValueType(pIp) while(pIp < pMethodEnd) { switch(valueType){ case ValueType::INT: int value; GET_VAL(value, int) // do something with value break; case ValueType::BYTE: ... } } }
  • 37. Dror Helper | @ dhelper | http://helpercode.com Thank you!

Editor's Notes

  1. Duff's device is a way of manually implementing loop unrolling by interleaving two syntactic constructs of C
  2. Clever code is not dumb code or bad code in itself, It’s a unique and cool implementation done in a way that you haven’t thought of before. But there are instances where the author of the clever code has gone too far – and I like to show you some of those cases
  3. Not bad code in itself But sometime over complex or trickery Hard to read Difficult to maintain Impossible to extend
  4. Clever code could be a must, but there’s a price to pay – it is impossible to maintain When you need to extend or update you have no choice but to completely re-write it
  5. If I had to write the code I’ve used I would have to write a lot of boilerplate code My conclusion is that Clever code is not always good or bad, but it does have a cost, Maintenance would be harder, extending you code will be difficult or even impossible so you need to make sure you’ve got a good reason to pay that price. In other words - don’t write write clever cod just for the sake of being clever write it only when you have to because there is no better way to solve a complex problem, create a user friendly API or Because real clever code is not about finding a dark corner of your programming language to show how smart you are but rather on making life simpler for whoever is going to us it – including your future self.