Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
Clean Code
Maciej Grabek
Software Engineer | Holte Software Poland
Bio
• Maciej Grabek
• Software Engineer w Holte Software
• Editor in Chief CodeGuru.pl
• MVP Windows Phone Development
• S...
Agenda
• Meaningful names
• Read your code
• Small steps
• Responsibilities
• Magic numbers
• Exceptions
• Communication b...
Why?
Why?
• Smart developer
• Difficult code
• Has great developing skills
• r = lowercase url
• Professional developer
• Reada...
Why?
• Bad code?
• Need to be done fast
• Tired of project / work
• Works now, I will clean up later
• All of us does this
Why?
• Bad code?
• Requirements changed
• Deadline to close
• Managers
• Sales
• WE - DEVELOPERS
Why?
• DEVELOPERS, DEVELOPERS, DEVELOPERS
Explanation
Explanation
Meaningful names
Meaningful names
int elapsedTimeInMinutes
int maximumPossibleValue
int daysSinceLastLogin
return result
int x
int y
int te...
Meaningful names
public List<Cell> getFlaggedCells()
{
List<Cell> flaggedCells = new
ArrayList<Cell>();
for (Cell cell : g...
Meaningful names
public static void copyChars(char a1[], char a2[])
{
for (int i = 0; i < a1.length; i++)
{
a2[i] = a1[i];...
Meaningful names
Array[Item] GetItemsArray()
List<Item> GetItemsList()
XYZControllerForEfficientHandlingOfStrings
XYZContr...
Not too much
string strProductTitle = „some product title”;
double dbProductPrice = 12.34;
string productTitle = „some pro...
Try to pronouce this
class DtaRcrd102
{
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "10...
One word per concept
• Get / receive / fetch
• Controller / manager / driver
Read your code
Read your code
• Max 150 chars per line
• Max 20 lines per method
• Blocks ( { } )
Read your code
• Method parameters
• Search(int minValue, int maxValue, int pageNumber, int pageSize)
• Search(Conditions ...
Read your code
if(account.Id > 0 && account.Name != null)
{
// do something
}
if(AccountIsValid(account))
{
// do somethin...
Read your code
BadWay()
{
CodeToCallDB
CodeToConvertItemsToModel
CodeToConvertItemsToModel
CodeToConvertItemsToModel
CodeT...
Don’t repeat your self
GetItems(){
Account account = accountsService.GetAccount();
if(account.IsValid)
{
return itemsServi...
Small steps
Small steps
• Scout rule
• Always leave it better than you found it
• Check your code after some time
Conditions – leave when is not ok
if(checkCondition1)
{
some logic here
if(checkCondition2)
{
long logic here
long logic h...
Responsibilities
SOLID
• S – Single responsibility principle
• O – Open / closed principle
• L – Liskov substitution principle
• I – Interf...
Single responsibility principle
class Person
{
string Name;
string Surname;
int Age;
}
class World
{
CalculateDistance(Per...
Magic Numbers
MNDD – Magic Numbers Driven Development
Magic number
if(report.Type == ReportType.Cool)
{
}
enum ReportType
{
Normal = 1,
Cool = 2,
Basic = 3
}
if(report.Type == ...
Magic string
if(report.CategoryName == StringResources.SpecialCategoryName)
{
}
if(report.CategoryName == „special”)
{
}
Exceptions
Exception hierarchy
OutOfRangeException
InvalidOperationException
InvalidUserException
InsufficientPrivilegesException
try...
„Empty” object
Var account = GetAccount(id);
if(account == null || account.Id <= 0)
{
throw new InvalidAccountException();...
Communication between
projects
External / internal
• WebAPI
• Always use DTO (ex Model.Person)
• PersonController
• PersonDto Get(id)
• Contract is resis...
Bonus
Clean codefull
Clean codefull
Nächste SlideShare
Wird geladen in …5
×
Nächste SlideShare
What to Upload to SlideShare
Weiter
Herunterladen, um offline zu lesen und im Vollbildmodus anzuzeigen.

0

Teilen

Herunterladen, um offline zu lesen

Clean codefull

Herunterladen, um offline zu lesen

clean code book pdf download

Ähnliche Bücher

Kostenlos mit einer 30-tägigen Testversion von Scribd

Alle anzeigen

Ähnliche Hörbücher

Kostenlos mit einer 30-tägigen Testversion von Scribd

Alle anzeigen
  • Gehören Sie zu den Ersten, denen das gefällt!

Clean codefull

  1. 1. Clean Code Maciej Grabek Software Engineer | Holte Software Poland
  2. 2. Bio • Maciej Grabek • Software Engineer w Holte Software • Editor in Chief CodeGuru.pl • MVP Windows Phone Development • Speaker, author of books, articles, webcasts... • Contact • kontakt@maciejgrabek.com • http://maciejgrabek.com • @maciejgrabek
  3. 3. Agenda • Meaningful names • Read your code • Small steps • Responsibilities • Magic numbers • Exceptions • Communication between projects
  4. 4. Why?
  5. 5. Why? • Smart developer • Difficult code • Has great developing skills • r = lowercase url • Professional developer • Readable code • Maintanable code • Clarity! • lowercaseUrlOfPage = lowercase url
  6. 6. Why? • Bad code? • Need to be done fast • Tired of project / work • Works now, I will clean up later • All of us does this
  7. 7. Why? • Bad code? • Requirements changed • Deadline to close • Managers • Sales • WE - DEVELOPERS
  8. 8. Why? • DEVELOPERS, DEVELOPERS, DEVELOPERS
  9. 9. Explanation
  10. 10. Explanation
  11. 11. Meaningful names
  12. 12. Meaningful names int elapsedTimeInMinutes int maximumPossibleValue int daysSinceLastLogin return result int x int y int temp return x
  13. 13. Meaningful names public List<Cell> getFlaggedCells() { List<Cell> flaggedCells = new ArrayList<Cell>(); for (Cell cell : gameBoard) if (cell.isFlagged()) flaggedCells.add(cell); return flaggedCells; } public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if (x[0] == 4) list1.add(x); return list1; }
  14. 14. Meaningful names public static void copyChars(char a1[], char a2[]) { for (int i = 0; i < a1.length; i++) { a2[i] = a1[i]; } } public static void copyChars(char source[], char destination[]) { for (int i = 0; i < source.length; i++) { destination[i] = source[i]; } }
  15. 15. Meaningful names Array[Item] GetItemsArray() List<Item> GetItemsList() XYZControllerForEfficientHandlingOfStrings XYZControllerForEfficientStorageOfStrings IEnumerable<Item> GetItems()
  16. 16. Not too much string strProductTitle = „some product title”; double dbProductPrice = 12.34; string productTitle = „some product title”; double productPrice = 12.34;
  17. 17. Try to pronouce this class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /* ... */ }; class Customer { private Date generationTimestamp; private Date modificationTimestamp;; private final String recordId = "102"; /* ... */ };
  18. 18. One word per concept • Get / receive / fetch • Controller / manager / driver
  19. 19. Read your code
  20. 20. Read your code • Max 150 chars per line • Max 20 lines per method • Blocks ( { } )
  21. 21. Read your code • Method parameters • Search(int minValue, int maxValue, int pageNumber, int pageSize) • Search(Conditions conditions) • Conditions {int minValue, int maxValue, int pageNumber, int pageSize }
  22. 22. Read your code if(account.Id > 0 && account.Name != null) { // do something } if(AccountIsValid(account)) { // do something } //where account is bussinnes class if(account.IsValid) { // do something }
  23. 23. Read your code BadWay() { CodeToCallDB CodeToConvertItemsToModel CodeToConvertItemsToModel CodeToConvertItemsToModel CodeToCalculate CodeToCalculate CodeToCalculate CodeToCalculate CodeToSaveCalculations CodeToSaveCalculations CodeToSaveCalculations return } BetterWay() { var items = GetItems(); var results = ProcessItems(items); SaveResults(results); return results; } GetItems() { } ProcessItems(itemsToProcess){ } SaveResults(resultsToSave){ }
  24. 24. Don’t repeat your self GetItems(){ Account account = accountsService.GetAccount(); if(account.IsValid) { return itemsService.GetItems(account); } } GetItem(int itemId){ Account account = accountsService.GetAccount(); if(account.IsValid) { return itemsService.GetItem(itemId); } } GetItems(){ if(ValidateAccount()) { return itemsService.GetItems(account); } } GetItem(int itemId){ if(ValidateAccount()) { return itemsService.GetItem(itemId); } } ValidateAccount(){ Account account = accountsService.GetAccount(); return account.IsValid; }
  25. 25. Small steps
  26. 26. Small steps • Scout rule • Always leave it better than you found it • Check your code after some time
  27. 27. Conditions – leave when is not ok if(checkCondition1) { some logic here if(checkCondition2) { long logic here long logic here long logic here } else { return / throw } } else { return / throw } if(!checkCondition1) { return / throw } some logic here if(!checkCondition2) { return / throw } long logic here long logic here long logic here
  28. 28. Responsibilities
  29. 29. SOLID • S – Single responsibility principle • O – Open / closed principle • L – Liskov substitution principle • I – Interface segregation principle • D – Dependency inversion principle
  30. 30. Single responsibility principle class Person { string Name; string Surname; int Age; } class World { CalculateDistance(Person, Place) } class PersonRepository { Save(Person); } class Person { string Name; string Surname; int Age; ... int CalculateDistance(Place); void SaveInDB() ... and so on ... ... for next couple k lines }
  31. 31. Magic Numbers MNDD – Magic Numbers Driven Development
  32. 32. Magic number if(report.Type == ReportType.Cool) { } enum ReportType { Normal = 1, Cool = 2, Basic = 3 } if(report.Type == 2) { } // guess what is 2 
  33. 33. Magic string if(report.CategoryName == StringResources.SpecialCategoryName) { } if(report.CategoryName == „special”) { }
  34. 34. Exceptions
  35. 35. Exception hierarchy OutOfRangeException InvalidOperationException InvalidUserException InsufficientPrivilegesException try { var result = DoSomething(); } catch(OutOfRangeException){} catch(InvalidUserException){} catch(InsufficientPrivilegesException){} catch(Exception) { // something went really bad // as I was not expecting that  } try { var result = DoSomething(); } catch(Exception ex) { if(ex.Message.Equals(„range”)) { } else if(ex.Message.StartsWith(„_”)) { } }
  36. 36. „Empty” object Var account = GetAccount(id); if(account == null || account.Id <= 0) { throw new InvalidAccountException(); } rest of logic GetAccountReturns Empty instead of null if(account == Account.Empty) { throw new InvalidAccountException(); } rest of logic class Account { public int Id { get; set; } public Account Empty { return new Account { Id = 0}; } }
  37. 37. Communication between projects
  38. 38. External / internal • WebAPI • Always use DTO (ex Model.Person) • PersonController • PersonDto Get(id) • Contract is resistant to internal changes of model • IPersonRepository • Person Get(id) • Model • Person • DBPersonRepository : IPersonRepository • DBPerson • DBPerson To Person Mapper • Easy to change repository ex. from EF to Azure Tables
  39. 39. Bonus

clean code book pdf download

Aufrufe

Aufrufe insgesamt

45

Auf Slideshare

0

Aus Einbettungen

0

Anzahl der Einbettungen

0

Befehle

Downloads

0

Geteilt

0

Kommentare

0

Likes

0

×