SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
>< nextprevious
C#6A cleaner code
Clean up your code!
>< nextprevious
Philosophy design
No New Big features
… but many small ones to
to improve your code
Clean up your code!
>< nextprevious
Put C#6 In context
Let’s see how to improve our code with less
boiler plate and more meanings
>< nextprevious
The language
C#1
async/await
?
var, anonymous,
Lambdas, auto-
properties, line
Generics, partials,
iterators, nullables
C#2
C#4 C#3
C#5 C#6
History
dynamic, optional
parameters
2002 2005
2007
20152012
2010
>< nextprevious
Developers should write
their code to fit in a slide
News
01
Using Static classes
why bother with static class names?
02
03
04
>< nextprevious
String Interpolation
because string.format sucks
Getter only properties
because un-meaningful boiler plate
auto-properties initializers
because creating a backing field for
properties only don’t make sense
>< nextprevious
Using Static 01
using System;
public class Code
{
public void LogTime(string message)
{
Console.Write(DateTime.Now);
Console.WriteLine(message);
}
}
>< nextprevious
Using Static 01
using static System.Console;
using static System.DateTime;
public class Code
{
public void Print(string message)
{
Write(Now);
WriteLine(message);
}
}
>< nextprevious
Using Static 01
Console.Write(DateTime.Now);
Write(Now);
From a very technical line
You moved to a natural
language reading friendly
sentence
using static allows
removal of technical
boilerplate
>< nextprevious
String Interpolation 02
public void UserMessagesLog(
string message, User user)
{
var messageToLog =
string.Format("[{0}] {1} - {2}",
DateTime.Now,
user.Name,
message);
Console.WriteLine(messageToLog);
}
}
>< nextprevious
String Interpolation 02
public void UserMessagesLog(
string message, User user)
{
var messageToLog =
$"[{DateTime.Now}] {User.Name} - {message}"
Console.WriteLine(messageToLog);
}
}
>< nextprevious
String Interpolation 02
string.Format("[{0}] {1} - {2}",
DateTime.Now,
user.Name,
message);
$"[{DateTime.Now}] {User.Name} - {message}"
sounds good enough
for small strings, But…
we’re stupid, when you read the code,
there will be a context switch to
interpret the result of your string if the
value is not in the place you write it!
>< nextprevious
String Interpolation 02
public void UserMessagesLog(
string message, User user)
{
var messageToLog =
$"[{DateTime.Now}] {User.Name} - {message}"
Console.WriteLine(messageToLog);
}
}
Why waiting 15
years for that?
>< nextprevious
Getter only properties 03
public class Post
{
private string title;
public string Title
{
get{return title;}
}
public Post(string title)
{
this.title=title
}
}
C#2
>< nextprevious
Getter only properties 03
public class Post
{
public string Title { get;private set;}
public Post(string title)
{
Title=title
}
}
C#3
>< nextprevious
Getter only properties 03
public class Post
{
public string Title { get;}
public Post(string title)
{
Title=title
}
}
C#6
>< nextprevious
AutoProperties initializers 04
public class Post
{
private string id="new-post";
public string Id
{
get{return id;}
}
public Post()
{
}
} C#2
>< nextprevious
AutoProperties initializers 04
public class Post
{
public string Id {get;private set;}
public Post()
{
Id="new-post";
}
}
C#3
>< nextprevious
AutoProperties initializers 04
public class Post
{
public string Id {get;} = "new-post";
}
C#6
News
05
Expression bodied properties
because one expression is enough
06
07
08
>< nextprevious
Expression bodied methods
too much braces for a one expression
function
Index initializers
because initializer shortcuts are great
Null conditional operators
if null then null else arg…
>< nextprevious
Expression bodied props 05
public class Post
{
private DateTime created = DateTime.Now;
public DateTime Created
{
get{return created;}
}
public TimeSpan Elapsed
{
get {
return (DateTime.Now-Created);
}
}
}
C#3
>< nextprevious
Expression bodied props 05
public class Post
{
public DateTime Created {get;}
= DateTime.Now;
public TimeSpan Elapsed
=> (DateTime.Now-Created);
}
C#6
>< nextprevious
Expression bodied props 05
public class Post
{
public DateTime Created {get;}
= DateTime.Now;
public DateTime Updated
=> DateTime;
}
C#6
Spot the
difference
{get;} =
value is affected once for all, stored in an
hidden backing field
=>
represents an expression, newly evaluated on
each call
>< nextprevious
Expression Bodied Methods 06
public class Post
{
public string Title {get;set;}
public string BuildSlug()
{
return Title.ToLower().Replace(" ", "-"); 
}
}
C#3
>< nextprevious
Expression Bodied Methods 06
public class Post
{
public string Title {get;set;}
public string BuildSlug()
{
return Title.ToLower().Replace(" ", "-"); 
}
}
C#3
never been frustrated to have to write this {return}
boilerplate since you use the => construct with lambdas?
>< nextprevious
Expression Bodied Methods 06
public class Post
{
public string Title {get;set;}
public string BuildSlug()
=> Title
.ToLower()
.Replace(" ", "-");
}
C#6
>< nextprevious
Index initializers 07
public class Author
{
public Dictionary<string,string> Contacts
{get;private set;};
public Author()
{
Contacts = new Dictionary<string,string>();
Contacts.Add("mail", "demo@rui.fr");
Contacts.Add("twitter", "@rhwy");
Contacts.Add("github", "@rhwy");
}
}
C#2
>< nextprevious
Index initializers 07
public class Author
{
public Dictionary<string,string> Contacts
{get;}
= new Dictionary<string,string>() {
["mail"]="demo@rui.fr",
["twitter"]="@rhwy",
["github"]="@rhwy"
};
}
C#6
>< nextprevious
Index initializers 07
public class Author
{
public Dictionary<string,string> Contacts
{get;}
= new Dictionary<string,string>() {
{"mail","demo@rui.fr"},
{"twitter","@rhwy"},
{"github","@rhwy"}
};
}
C#3
>< nextprevious
Null Conditional Operators 08
public class Post
{
//"rui carvalho"
public string Author {get;private set;};
//=>"Rui Carvalho"
public string GetPrettyName()
{
if(Author!=null)
{
if(Author.Contains(" "))
{
string result;
var items=Author.Split(" ");
forEach(var word in items)
{
result+=word.SubString(0,1).ToUpper()
+word.SubString(1).ToLower()
+ " ";
}
return result.Trim();
}
}
return Author;
}
}
C#3
>< nextprevious
Null Conditional Operators 08
public class Post
{
//"rui carvalho"
public string Author {get;private set;};
//=>"Rui Carvalho"
public string GetPrettyName()
=> (string.Join("",
Author?.Split(' ')
.ToList()
.Select( word=>
word.Substring(0,1).ToUpper()
+word.Substring(1).ToLower()
+ " ")
)).Trim();
C#6
>< nextprevious
Null Conditional Operators 08
public class Post
{
//"rui carvalho"
public string Author {get;private set;};
//=>"Rui Carvalho"
public string GetPrettyName()
=> (string.Join("",
Author?.Split(' ')
.ToList()
.Select( word=>
word.Substring(0,1).ToUpper()
+word.Substring(1).ToLower()
+ " ")
)).Trim();
C#6
We have now one
expression only but
maybe not that clear or
testable ?
>< nextprevious
Null Conditional Operators 08
public string PrettifyWord (string word)
=>
word.Substring(0,1).ToUpper()
+word.Substring(1).ToLower()
+ " ";
public IEnumerable<string>
PrettifyTextIfExists(string phrase)
=> phrase?
.Split(' ')
.Select( PrettifyWord);
public string GetPrettyName()
=> string
.Join("",PrettifyTextIfExists(Author))
.Trim();
C#6
Refactoring !
We have now 3 small
independent functions with
Names and meanings
News
09
Exception filters
not new in .Net
10
11
12
>< nextprevious
nameof Operator
consistent refactorings
await in catch
who never complained about that?
and in finally
the last step
News
09
Exception filters
not new in .Net
10
11
12
>< nextprevious
nameof Operator
consistent refactorings
await in catch
who never complained about that?
and in finally
the last step
these ones are just goodimprovements but not thatimportant for our code
readability
>< nextprevious
Exception Filters 09
try {
//production code
}
catch (HttpException ex)
{
if(ex.StatusCode==500)
//do some specific crash scenario
if(ex.StatusCode==400)
//tell client that he’s stupid
}
catch (Exception otherErrors)
{
// ...
}
C#2
>< nextprevious
Exception Filters 09
try {
//production code
}
catch (HttpException ex) when (ex.StatusCode == 500)
{
//do some specific crash scenario
}
catch (HttpException ex) when (ex.StatusCode == 400)
{
//tell the client he’s stupid
}
catch (Exception otherException)
{
// ...
}
C#6
>< nextprevious
nameof Operator 10
public string SomeMethod (string word)
{
if(word == null)
throw new Exception("word is null");
return word;
}
C#3
>< nextprevious
nameof Operator 10
public string SomeMethod (string text)
{
if(word == null)
throw new Exception("word is null");
return word;
}
C#3
Refactoring
arg, information
lost!
>< nextprevious
nameof Operator 10
public string SomeMethod (string word)
{
if(word == null)
throw new Exception(
$"{nameof(word)} is null");
return word;
}
C#6
parameter name is now pure
code & support refactoring
>< nextprevious
await in catch 11
try {
return await something();
}
catch (HttpException ex)
{
error = ex;
}
return await CrashLogger.ServerError(error);
C#5
>< nextprevious
await in catch 11
try {
await something();
}
catch (HttpException ex)
{
await CrashLogger.ServerError(ex);
}
C#6
>< nextprevious
await in finally 12
try {
return await Persistence.Query(query);
}
catch (PersistenceException ex)
{
await CrashLogger.ServerError(ex);
}
finally
{
await Persistence.Close();
} C#6
>< nextprevious
To Finish
C#6 helps to be more functional & write cleaner code by
removing lots of boilerplate!
refactoring to small
functions, add new words to
your app vocabulary
>< nextprevious
Thanks
@rhwy
ncrafts.io
altnet.fr
rui.io

Contenu connexe

Tendances

Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
Dmitry Buzdin
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
Antoine Sabot-Durand
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
RORLAB
 

Tendances (20)

Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
Why you should be using the shiny new C# 6.0 features now!
Why you should be using the shiny new C# 6.0 features now!Why you should be using the shiny new C# 6.0 features now!
Why you should be using the shiny new C# 6.0 features now!
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
IronSmalltalk
IronSmalltalkIronSmalltalk
IronSmalltalk
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
Anatomy of a Gradle plugin
Anatomy of a Gradle pluginAnatomy of a Gradle plugin
Anatomy of a Gradle plugin
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in Apex
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Group
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 

En vedette

1165 hong kong's unique protestors
1165 hong kong's unique protestors1165 hong kong's unique protestors
1165 hong kong's unique protestors
Next2ndOpinions
 
Workshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEOWorkshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEO
Yogh
 
ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)
veronica nascimento
 
O real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. ivO real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. iv
Artemosfera Cia de Artes
 
Utilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidadeUtilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidade
Beth Cordeiro
 
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia RegressivaSignificado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
GSArt Web Solutions
 
O signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev eO signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev e
Unternbaumen
 
Figuras de linguagem slide
Figuras de linguagem slideFiguras de linguagem slide
Figuras de linguagem slide
Ivana Bastos
 
Semiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símboloSemiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símbolo
Bruno Santos
 

En vedette (19)

1165 hong kong's unique protestors
1165 hong kong's unique protestors1165 hong kong's unique protestors
1165 hong kong's unique protestors
 
Pérolas das avaliações de conhecimento
Pérolas das avaliações de conhecimentoPérolas das avaliações de conhecimento
Pérolas das avaliações de conhecimento
 
Workshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEOWorkshop - Links Patrocinados e SEO
Workshop - Links Patrocinados e SEO
 
ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)ApresentaçãO Em PúBlico (Veronica)
ApresentaçãO Em PúBlico (Veronica)
 
O real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. ivO real e o supra real. seminário de teologia da saúde. iv
O real e o supra real. seminário de teologia da saúde. iv
 
Carmof oa
Carmof oaCarmof oa
Carmof oa
 
Utilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidadeUtilização dos recursos linguísticos na publicidade
Utilização dos recursos linguísticos na publicidade
 
Dino preti
Dino pretiDino preti
Dino preti
 
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia RegressivaSignificado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
Significado e Significante e a Dinâmica do Inconsciente na Terapia Regressiva
 
Semiótica é Experiência
Semiótica é ExperiênciaSemiótica é Experiência
Semiótica é Experiência
 
O signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev eO signo linguístico em saussure, hjelmslev e
O signo linguístico em saussure, hjelmslev e
 
Signo linguìstico
Signo linguìsticoSigno linguìstico
Signo linguìstico
 
Signos Visuais
Signos VisuaisSignos Visuais
Signos Visuais
 
Figuras de linguagem: 25 propagandas. Exercício 2.
Figuras de linguagem: 25 propagandas. Exercício 2.Figuras de linguagem: 25 propagandas. Exercício 2.
Figuras de linguagem: 25 propagandas. Exercício 2.
 
Figuras de linguagem em propagandas
Figuras de linguagem em propagandasFiguras de linguagem em propagandas
Figuras de linguagem em propagandas
 
Figuras de linguagem slide
Figuras de linguagem   slideFiguras de linguagem   slide
Figuras de linguagem slide
 
Figuras de linguagem slide
Figuras de linguagem slideFiguras de linguagem slide
Figuras de linguagem slide
 
Semiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símboloSemiótica - ícone, índice e símbolo
Semiótica - ícone, índice e símbolo
 
Signos | Semiótica: símbolo, índice e ícone
Signos | Semiótica: símbolo, índice e íconeSignos | Semiótica: símbolo, índice e ícone
Signos | Semiótica: símbolo, índice e ícone
 

Similaire à Clean up your code with C#6

Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
jeffz
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
ARORACOCKERY2111
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
Luis Enrique
 

Similaire à Clean up your code with C#6 (20)

C#.net evolution part 2
C#.net evolution part 2C#.net evolution part 2
C#.net evolution part 2
 
C# 6.0 Introduction
C# 6.0 IntroductionC# 6.0 Introduction
C# 6.0 Introduction
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
Linq intro
Linq introLinq intro
Linq intro
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기
 
Annotation processor and compiler plugin
Annotation processor and compiler pluginAnnotation processor and compiler plugin
Annotation processor and compiler plugin
 
C#6 - The New Stuff
C#6 - The New StuffC#6 - The New Stuff
C#6 - The New Stuff
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
 
C# 6.0
C# 6.0C# 6.0
C# 6.0
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
 

Plus de Rui Carvalho

Plus de Rui Carvalho (15)

Agile Feedback Loops
Agile Feedback LoopsAgile Feedback Loops
Agile Feedback Loops
 
NewCrafts 2017 Conference Opening
NewCrafts 2017 Conference OpeningNewCrafts 2017 Conference Opening
NewCrafts 2017 Conference Opening
 
Cqrs Ignite
Cqrs IgniteCqrs Ignite
Cqrs Ignite
 
AltNet fr talks #2016.11 - news
AltNet fr talks #2016.11 - newsAltNet fr talks #2016.11 - news
AltNet fr talks #2016.11 - news
 
Patience, the art of taking his time
Patience, the art of taking his timePatience, the art of taking his time
Patience, the art of taking his time
 
Ncrafts 2016 opening notes
Ncrafts 2016 opening notesNcrafts 2016 opening notes
Ncrafts 2016 opening notes
 
Code Cooking
Code Cooking Code Cooking
Code Cooking
 
Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening
 
Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!
 
Simple Code
Simple CodeSimple Code
Simple Code
 
Simplicity 2.0 - Get the power back
Simplicity 2.0 - Get the power backSimplicity 2.0 - Get the power back
Simplicity 2.0 - Get the power back
 
SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)SPA avec Angular et SignalR (FR)
SPA avec Angular et SignalR (FR)
 
My Git workflow
My Git workflowMy Git workflow
My Git workflow
 
Simplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and toolsSimplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and tools
 
.Net pour le développeur Java - une source d'inspiration?
.Net pour le développeur Java - une source d'inspiration?.Net pour le développeur Java - une source d'inspiration?
.Net pour le développeur Java - une source d'inspiration?
 

Dernier

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Dernier (20)

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Clean up your code with C#6

  • 2. Clean up your code! >< nextprevious Philosophy design No New Big features … but many small ones to to improve your code
  • 3. Clean up your code! >< nextprevious Put C#6 In context Let’s see how to improve our code with less boiler plate and more meanings
  • 4. >< nextprevious The language C#1 async/await ? var, anonymous, Lambdas, auto- properties, line Generics, partials, iterators, nullables C#2 C#4 C#3 C#5 C#6 History dynamic, optional parameters 2002 2005 2007 20152012 2010
  • 5. >< nextprevious Developers should write their code to fit in a slide
  • 6. News 01 Using Static classes why bother with static class names? 02 03 04 >< nextprevious String Interpolation because string.format sucks Getter only properties because un-meaningful boiler plate auto-properties initializers because creating a backing field for properties only don’t make sense
  • 7. >< nextprevious Using Static 01 using System; public class Code { public void LogTime(string message) { Console.Write(DateTime.Now); Console.WriteLine(message); } }
  • 8. >< nextprevious Using Static 01 using static System.Console; using static System.DateTime; public class Code { public void Print(string message) { Write(Now); WriteLine(message); } }
  • 9. >< nextprevious Using Static 01 Console.Write(DateTime.Now); Write(Now); From a very technical line You moved to a natural language reading friendly sentence using static allows removal of technical boilerplate
  • 10. >< nextprevious String Interpolation 02 public void UserMessagesLog( string message, User user) { var messageToLog = string.Format("[{0}] {1} - {2}", DateTime.Now, user.Name, message); Console.WriteLine(messageToLog); } }
  • 11. >< nextprevious String Interpolation 02 public void UserMessagesLog( string message, User user) { var messageToLog = $"[{DateTime.Now}] {User.Name} - {message}" Console.WriteLine(messageToLog); } }
  • 12. >< nextprevious String Interpolation 02 string.Format("[{0}] {1} - {2}", DateTime.Now, user.Name, message); $"[{DateTime.Now}] {User.Name} - {message}" sounds good enough for small strings, But… we’re stupid, when you read the code, there will be a context switch to interpret the result of your string if the value is not in the place you write it!
  • 13. >< nextprevious String Interpolation 02 public void UserMessagesLog( string message, User user) { var messageToLog = $"[{DateTime.Now}] {User.Name} - {message}" Console.WriteLine(messageToLog); } } Why waiting 15 years for that?
  • 14. >< nextprevious Getter only properties 03 public class Post { private string title; public string Title { get{return title;} } public Post(string title) { this.title=title } } C#2
  • 15. >< nextprevious Getter only properties 03 public class Post { public string Title { get;private set;} public Post(string title) { Title=title } } C#3
  • 16. >< nextprevious Getter only properties 03 public class Post { public string Title { get;} public Post(string title) { Title=title } } C#6
  • 17. >< nextprevious AutoProperties initializers 04 public class Post { private string id="new-post"; public string Id { get{return id;} } public Post() { } } C#2
  • 18. >< nextprevious AutoProperties initializers 04 public class Post { public string Id {get;private set;} public Post() { Id="new-post"; } } C#3
  • 19. >< nextprevious AutoProperties initializers 04 public class Post { public string Id {get;} = "new-post"; } C#6
  • 20. News 05 Expression bodied properties because one expression is enough 06 07 08 >< nextprevious Expression bodied methods too much braces for a one expression function Index initializers because initializer shortcuts are great Null conditional operators if null then null else arg…
  • 21. >< nextprevious Expression bodied props 05 public class Post { private DateTime created = DateTime.Now; public DateTime Created { get{return created;} } public TimeSpan Elapsed { get { return (DateTime.Now-Created); } } } C#3
  • 22. >< nextprevious Expression bodied props 05 public class Post { public DateTime Created {get;} = DateTime.Now; public TimeSpan Elapsed => (DateTime.Now-Created); } C#6
  • 23. >< nextprevious Expression bodied props 05 public class Post { public DateTime Created {get;} = DateTime.Now; public DateTime Updated => DateTime; } C#6 Spot the difference {get;} = value is affected once for all, stored in an hidden backing field => represents an expression, newly evaluated on each call
  • 24. >< nextprevious Expression Bodied Methods 06 public class Post { public string Title {get;set;} public string BuildSlug() { return Title.ToLower().Replace(" ", "-");  } } C#3
  • 25. >< nextprevious Expression Bodied Methods 06 public class Post { public string Title {get;set;} public string BuildSlug() { return Title.ToLower().Replace(" ", "-");  } } C#3 never been frustrated to have to write this {return} boilerplate since you use the => construct with lambdas?
  • 26. >< nextprevious Expression Bodied Methods 06 public class Post { public string Title {get;set;} public string BuildSlug() => Title .ToLower() .Replace(" ", "-"); } C#6
  • 27. >< nextprevious Index initializers 07 public class Author { public Dictionary<string,string> Contacts {get;private set;}; public Author() { Contacts = new Dictionary<string,string>(); Contacts.Add("mail", "demo@rui.fr"); Contacts.Add("twitter", "@rhwy"); Contacts.Add("github", "@rhwy"); } } C#2
  • 28. >< nextprevious Index initializers 07 public class Author { public Dictionary<string,string> Contacts {get;} = new Dictionary<string,string>() { ["mail"]="demo@rui.fr", ["twitter"]="@rhwy", ["github"]="@rhwy" }; } C#6
  • 29. >< nextprevious Index initializers 07 public class Author { public Dictionary<string,string> Contacts {get;} = new Dictionary<string,string>() { {"mail","demo@rui.fr"}, {"twitter","@rhwy"}, {"github","@rhwy"} }; } C#3
  • 30. >< nextprevious Null Conditional Operators 08 public class Post { //"rui carvalho" public string Author {get;private set;}; //=>"Rui Carvalho" public string GetPrettyName() { if(Author!=null) { if(Author.Contains(" ")) { string result; var items=Author.Split(" "); forEach(var word in items) { result+=word.SubString(0,1).ToUpper() +word.SubString(1).ToLower() + " "; } return result.Trim(); } } return Author; } } C#3
  • 31. >< nextprevious Null Conditional Operators 08 public class Post { //"rui carvalho" public string Author {get;private set;}; //=>"Rui Carvalho" public string GetPrettyName() => (string.Join("", Author?.Split(' ') .ToList() .Select( word=> word.Substring(0,1).ToUpper() +word.Substring(1).ToLower() + " ") )).Trim(); C#6
  • 32. >< nextprevious Null Conditional Operators 08 public class Post { //"rui carvalho" public string Author {get;private set;}; //=>"Rui Carvalho" public string GetPrettyName() => (string.Join("", Author?.Split(' ') .ToList() .Select( word=> word.Substring(0,1).ToUpper() +word.Substring(1).ToLower() + " ") )).Trim(); C#6 We have now one expression only but maybe not that clear or testable ?
  • 33. >< nextprevious Null Conditional Operators 08 public string PrettifyWord (string word) => word.Substring(0,1).ToUpper() +word.Substring(1).ToLower() + " "; public IEnumerable<string> PrettifyTextIfExists(string phrase) => phrase? .Split(' ') .Select( PrettifyWord); public string GetPrettyName() => string .Join("",PrettifyTextIfExists(Author)) .Trim(); C#6 Refactoring ! We have now 3 small independent functions with Names and meanings
  • 34. News 09 Exception filters not new in .Net 10 11 12 >< nextprevious nameof Operator consistent refactorings await in catch who never complained about that? and in finally the last step
  • 35. News 09 Exception filters not new in .Net 10 11 12 >< nextprevious nameof Operator consistent refactorings await in catch who never complained about that? and in finally the last step these ones are just goodimprovements but not thatimportant for our code readability
  • 36. >< nextprevious Exception Filters 09 try { //production code } catch (HttpException ex) { if(ex.StatusCode==500) //do some specific crash scenario if(ex.StatusCode==400) //tell client that he’s stupid } catch (Exception otherErrors) { // ... } C#2
  • 37. >< nextprevious Exception Filters 09 try { //production code } catch (HttpException ex) when (ex.StatusCode == 500) { //do some specific crash scenario } catch (HttpException ex) when (ex.StatusCode == 400) { //tell the client he’s stupid } catch (Exception otherException) { // ... } C#6
  • 38. >< nextprevious nameof Operator 10 public string SomeMethod (string word) { if(word == null) throw new Exception("word is null"); return word; } C#3
  • 39. >< nextprevious nameof Operator 10 public string SomeMethod (string text) { if(word == null) throw new Exception("word is null"); return word; } C#3 Refactoring arg, information lost!
  • 40. >< nextprevious nameof Operator 10 public string SomeMethod (string word) { if(word == null) throw new Exception( $"{nameof(word)} is null"); return word; } C#6 parameter name is now pure code & support refactoring
  • 41. >< nextprevious await in catch 11 try { return await something(); } catch (HttpException ex) { error = ex; } return await CrashLogger.ServerError(error); C#5
  • 42. >< nextprevious await in catch 11 try { await something(); } catch (HttpException ex) { await CrashLogger.ServerError(ex); } C#6
  • 43. >< nextprevious await in finally 12 try { return await Persistence.Query(query); } catch (PersistenceException ex) { await CrashLogger.ServerError(ex); } finally { await Persistence.Close(); } C#6
  • 44. >< nextprevious To Finish C#6 helps to be more functional & write cleaner code by removing lots of boilerplate! refactoring to small functions, add new words to your app vocabulary