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
2
Uncle Bob
Robert Cecil Martin
@unclebobmartin
http://blog.cleancoder.com/
Agile Manifesto, Extreme
Programming, UML for ...
3 Warnings
▸ What we’re going to see are
recommendations. They’re not the
Bible. Each case is different and
common sense i...
4 Warnings
▸ Whoever is free from sin...
5
Clean Code
A Handbook of Agile Software Craftsmanship
❑ Published in 2008
❑ Summary of known and perceived good practice...
6
Clean Code
❑ We have the book on paper and in Spanish
❑ On eBook in English
Yeray Darias, Codemotion 2016:
«There are tw...
7
❑ A series of guides and good practices are proposed
when writing code
❑ Examples in Java, but applicable to any high-le...
"The responsibility of doing
good
code belongs to the
programmers. You have to
refuse to do bad code.
9
Clean Code
The clean code is elegant, effective,
readable. With unit tests that explain
what it does and serve as an exa...
10 The theory of broken windows
11 The theory of broken windows
12
Clean Code
is very easy
If the code is
If it’s clean, who dares to put it first?
Boy Scout rule: leave the code cleaner...
13
Meaningful names
14
Meaningful names
▸ All names have to be descriptive, searchable and
pronunciable. Spend a couple of minutes thinking up...
15
Meaningful names
▸ Better to use "added" in the implementation (which will
be private and less used) than in the Interf...
16
Meaningful names
▸ Use the same words for the same thing. At least
per project (get? fetch? . retrieve?.
▸ Do not use t...
17
Meaningful names
new MiObject("22") new
MiObject(22)
new MiObject( Hashtable )
...
MiObject.FromString("22")
MiObject.F...
18
Meaningful names
▸ Use technical names when the intention is
technical: Factory, List...
▸ If you can’t use a technical...
19
Meaningful names
▸ Do not add unnecessary prefixes or contexts:
neg* , GDB* ... Let the IDE help you find
▸ Class Caser...
20
Functions
▸ Two basic rules:
▹ First rule: Reduced: ~ 20 lines
▹ Second rule: Smaller still
▸ Fit on a screen (24 * 80)...
21
Functions
A single level of abstraction in each function: do
not mix high level things with low level.
For example, in ...
22
Functions - Level of abstraction
public void doerBackgroundsCaseros(){
passerPerro(); sacBasura();
Washing machines (ta...
23
Functions
▸ They must do only one thing, and do it well. They
should have no side effects: they do what they
are expect...
24
boolean?. How do we know
What kind of mistake happened?
public boolean ,String password) {User verifieYPassword( String...
25
Functions
The code should be read as if it were prose, top to
bottom, from greater to lesser abstraction:
public void l...
26
Functions
switch: (or if-else multiples)
▸ Are long
▸ Surely they do more than one
thing
▸ More difficult to maintain
27
Functions
Integer calculatePaymentEmployed( Employee employee )
{ if( employee.type == Employee.MERCHANT_TYPE 1) {
calc...
28
Functions
// or Interfaceabstract class Employee{
getSalario()
getDiaDePago()
...
}
class
EmployeesFactory {static Empl...
29
Functions - Method Arguments
▸ There should be no more than 2 parameters. 1 better than 2
▸ 3 are many, and yet must he...
30
Functions - Method Arguments
▸ Functions/methods with 2 parameters ok if
related
Point point = makePoint( float x, floa...
31
Functions - Method Arguments
▸ If there are exceptions... throw an exception!. (It doesn’t
have to be processed immedia...
32
Code commentary
▸ There should only be comments when the code is not able to
express what it does.
▸ Acceptable comment...
33
Code commentary
/** * Always returns true.
*/
public boolean isAvailable()
{
return false;
}
return 1; // returns 1
// ...
34
Format
35
Vertical Format
▸ A class (or procedures file) should not have +200 average lines,
never +500
▸ Metaphor of the newspap...
36
Format
▸ Variables should be declared near their use. Exception: class
variables at the beginning of the class
▸ Width ...
37
Format
▸ Avoid excessive nesting. If you even have to put comments
to know closures... is that there is a serious probl...
38
Objects and data
structures
39
Objects and data structures
▸ The classes, facing the outside, must hide their internal structure
with abstractions tha...
40
Objects and data structures
➢ Shapes are data structures, without
behavior. All behavior is in the Geometry
class
➢ If ...
41
Objects and data structures
➢ Method polymorphic area.
➢ We don’t need a Geometry class, each
class knows for itself ho...
42
Objects and data structures
▸ So the opposite is also true:
▸ Procedure-oriented code makes it difficult to include
new...
43
Objects and data structures
▸ Demeter law
▹ A module should not know the interiors of the objects it
manipulates: these...
44
Functions - Method Arguments
File cvsTempFile = new File(getConfig().getTempDir().getAbsolutePath() + "/" + System.curr...
45
Objects and data structures
▸ Data Transfer Objects (or, actually, beans)
▹ Data structure (get/sets). With or without ...
46
Error
processing
47
Mistakes
▸ Use exceptions instead of error
codes
if( conditionError) {
return -1
} else if (otherCondition )
{ return -...
48
Mistakes
▸ (Own crop)
▹ Handle only the exceptions you know how to handle. How are
you going to handle a BD connectivit...
49
Mistakes
▸ Not all exceptions have to be checked. If we do so, we force
everyone who calls to change their class signat...
50
Mistakes
▸ If a third-party bookshop returns us many exceptions it may be
convenient to do a wrapping
▸ Do not return n...
51
Limits
52
Limits
▸ Sometimes the system or generic classes are too "big" for what we need
▸ Use them as little as possible as ret...
53
Limits
Class MapaDeLibros {
private Map books = new HashMap<Book>()
public Book addBook( String key, Book book ){...} p...
54
Unit
tests
55
TDD
▸ The concept of TDD did not exist until 1997.
▸ The tests were mini-programs that we then threw away
▸ Laws of TDD...
56
TDD
▸ Tests are indispensable in modern software development.
▸ Ensure that changes can be made in the future without b...
57
TDD
▸ The tests must be F.I.R.S.T
▹ Fast
▹ Independent
▹ Repeat
▹ Self-Validating
▹ Timely
▸ Not having proof is very b...
versions)
▸
58
Classes
59
Classes
▸ Order within the class:
▹ Static constants
▹ Static variables
▹ Instance variables
▹ Methods/Functions.
Of al...
60
Classes
S.O.L.I.D
▸ Single Responsability
▹ A single (and simple) class liability. Just a reason to change class.
▹ Avo...
61
Sistemas
62
Sistemas
▸ Para dedicar una charla entera (o leerse el capítulo 11 del
libro):
▹ Factorias abstractas
▹ Inyeccion de de...
63
Diseño sencillo
64
Diseño sencillo
▸ Reglas de Kent Beck para diseño sencillo
▹ Que pase todas las pruebas
▹ No hay codigo duplicado
▹ Exp...
65
Eliminar duplicados
▸ DRY!
▸ No solo por comodidad: nos ayudan a reducir la complejidad
▸ Ayudan a pensar como mejorar ...
66
Expresividad
▸ Cualquier idiota puede hacer código que compila
▸ Solo un buen programador puede hacer código que otros
...
67
Concurrencia
68
Concurrencia
▸ Capítulo (13) tambien para dedicarle un tiempo aparte.
▸ Notitas:
▹ Multiproceso no siempre mejora rendi...
69
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
70
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
71
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
72
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
73
-
-
-
Let’s start with the first set of slides
THIS IS YOUR
PRESENTATION
TITLE
75
Instructions for use
Open this document in Google Slides (if you are at slidescarnival.com use the button below this pr...
76
HELLO!
I am Jayden Smith
I am here because I love
to
give presentations. You
can find me at
@username
77
1.
Transition headline
Let’s start with the first set of slides
“
Quotations are commonly
printed as a means of inspiration
and to
invoke philosophical thoughts
from the reader.
79
This is a slide title
▸Here you have a list of items
▸And some text
▸But remember not to overload
your slides with cont...
80
BIG CONCEPT
Bring the attention of your audience over
a key concept using icons or illustrations
81
You can also split your content
White
Is the color of milk and
fresh snow, the color
produced by the
combination of all...
82
In two or three columns
Yellow
Is the color of gold,
butter and ripe
lemons. In the
spectrum of visible
light, yellow i...
83
A picture is worth a thousand words
A complex idea can be
conveyed with just a single
still image, namely making it
pos...
84
Want big impact? USE BIG IMAGE
85
Use charts to explain your ideas
White Gray Black
86
And tables to compare data
TO B C
Yellow 10 20 7
Blue 30 15 10
Orange 5 24 16
87 Maps
our office
88
89,526,124
Whoa! That’s a big number,
aren’t you proud?
89
89,526,124$
That’s a lot of money
185,244 users
And a lot of users
100%
Total success!
90
Our process is easy
first second last
91
Let’s review some concepts
Yellow
Is the color of gold, butter and
ripe lemons. In the spectrum of
visible light, yello...
92
You can insert graphs from Google
Sheets
93
Place your screenshot here
ANDROID
PROJECT
Show and explain
your web, app or
software projects
using these gadget
templ...
94
Place your screenshot here
iPHONE
PROJECT
Show and explain
your web, app or
software projects
using these gadget
templa...
95
Place your screenshot here
TABLET
PROJECT
Show and explain
your web, app or
software projects
using these gadget
templa...
96
Place your screenshot here
DESKTOP
PROJECT
Show and explain
your web, app or
software projects
using these gadget
templ...
97
THANKS!
Any questions?
You can find me at @username & user@mail.me
98
Credits
Special thanks to all the people who made
and released these awesome resources for
free:
▸ Presentation templat...
99
Presentation design
This presentation uses the following typographies and colors:
▸ Titles: Dosis
▸ Body copy: Roboto
Y...
100
SlidesCarnival icons are editable
shapes.
This means that you can:
● Resize them without losing quality.
● Change line...
101
Now you can use any emoji as an icon!
And of course it resizes without losing quality and you can change the color.
Ho...
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
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.

1

Teilen

Herunterladen, um offline zu lesen

clean code book summary - uncle bob - English version

Herunterladen, um offline zu lesen

clean code book summary - uncle bob - English version

Ä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

clean code book summary - uncle bob - English version

  1. 1. Clean Code
  2. 2. 2 Uncle Bob Robert Cecil Martin @unclebobmartin http://blog.cleancoder.com/ Agile Manifesto, Extreme Programming, UML for Java... Clean Coders
  3. 3. 3 Warnings ▸ What we’re going to see are recommendations. They’re not the Bible. Each case is different and common sense is above the rules. ▸ There are hundreds (thousands?) of videos and slides on the topic https://goo.gl/r25If ▸ It’s the summary of a book
  4. 4. 4 Warnings ▸ Whoever is free from sin...
  5. 5. 5 Clean Code A Handbook of Agile Software Craftsmanship ❑ Published in 2008 ❑ Summary of known and perceived good practices but not always implemented ❑ Clean code isn’t just desirable. It is vital for companies and programmers. ❑ Whoever writes dirty code wastes everyone’s time and money trying to understand it. Even to his own self.
  6. 6. 6 Clean Code ❑ We have the book on paper and in Spanish ❑ On eBook in English Yeray Darias, Codemotion 2016: «There are two things that humanity should not have done: The H-bomb and the translation of Clean Code»
  7. 7. 7 ❑ A series of guides and good practices are proposed when writing code ❑ Examples in Java, but applicable to any high-level language. ❑ Divided into 2 parts + 1 summary chapter ❑ Caps. 1-13. Good practice ❑ Chaps. 14-16. Examples of real situations ❑ Cap. 17. Odors and symptoms.
  8. 8. "The responsibility of doing good code belongs to the programmers. You have to refuse to do bad code.
  9. 9. 9 Clean Code The clean code is elegant, effective, readable. With unit tests that explain what it does and serve as an example We read more code than we wrote. We can’t write good code if the one around is a disaster.
  10. 10. 10 The theory of broken windows
  11. 11. 11 The theory of broken windows
  12. 12. 12 Clean Code is very easy If the code is If it’s clean, who dares to put it first? Boy Scout rule: leave the code cleaner than you found it.
  13. 13. 13 Meaningful names
  14. 14. 14 Meaningful names ▸ All names have to be descriptive, searchable and pronunciable. Spend a couple of minutes thinking up a good name. If you don’t like it, change it later. ▸ Avoid abbreviations, prefixes (Hungarian notation), redundant words (the- , a- , -object, -data). Use names you can look for. Avoid single-letter variables (except i, j, k) ▸ Class names start with Shift. The objects with lowercase.
  15. 15. 15 Meaningful names ▸ Better to use "added" in the implementation (which will be private and less used) than in the Interface (IFactory) ▸ Class names: try to avoid Manager or Processor suffixes. Class names should not be verbs, but nouns ▸ Methods: whether they should be verbs ▸ Use get-set and is to access variables ▸ Don’t use puns (which others, perhaps in gitHub and other cultures) won’t understand or joke.
  16. 16. 16 Meaningful names ▸ Use the same words for the same thing. At least per project (get? fetch? . retrieve?. ▸ Do not use the same word for different things (is add used to add or to insert? ▸ Use static methods with the name of the expected argument type instead of multiple constructors:
  17. 17. 17 Meaningful names new MiObject("22") new MiObject(22) new MiObject( Hashtable ) ... MiObject.FromString("22") MiObject.FromInteger( 22 )
  18. 18. 18 Meaningful names ▸ Use technical names when the intention is technical: Factory, List... ▸ If you can’t use a technical name that the next programmer understands, use one from the domain (business): at least you can ask someone from business what it means. ▸ Names, the shorter (although clear and explicit), the better.
  19. 19. 19 Meaningful names ▸ Do not add unnecessary prefixes or contexts: neg* , GDB* ... Let the IDE help you find ▸ Class CaserEmailAddress. If you need email elsewhere, will you use that class with that name?
  20. 20. 20 Functions ▸ Two basic rules: ▹ First rule: Reduced: ~ 20 lines ▹ Second rule: Smaller still ▸ Fit on a screen (24 * 80) ▸ That we can describe it in one sentence
  21. 21. 21 Functions A single level of abstraction in each function: do not mix high level things with low level. For example, in an html parser: ▸ A getHtml() call that returns the String ▸ A parseHtml that mixes data sources ▸ A call . append(" n") ▸ Open and close Streams or disk files
  22. 22. 22 Functions - Level of abstraction public void doerBackgroundsCaseros(){ passerPerro(); sacBasura(); Washing machines (tableware and tableware); } public void doerBackgroundsCaseros(){ passerPerro(); sacBasura(); for( Tableware piece piece ){ rinsingVajilla( piece ) ; meteInLavaplatos( piece ) ; } } private void washing machine Dishes( ArrayList<Piece> pieces) { for( Tableware piece piece ){ rinsingVajilla( piece ) ; meteInLavaplatos( piece ) ; } }
  23. 23. 23 Functions ▸ They must do only one thing, and do it well. They should have no side effects: they do what they are expected to do, and nothing else.
  24. 24. 24 boolean?. How do we know What kind of mistake happened? public boolean ,String password) {User verifieYPassword( String user Incorrect level of abstraction: Low-level access to BD with verification of correct data. enters boolean = false; Not to mention we’reif (OracleExecute( "SELECT COUNT(*) FROM USERS WHERE USER='user' AND PASS= 'password'")) {sendin g th e pass wor d... in initializeUser Session() ; // We initialize the user’s session clear? in = true ; } return enters;} Oracle?. What if tomorrow is another BD? Control of errors? This side effect... Alone we wanted to verify user and password!. What if we have to go to another site to validate the IP or what sea? Pointless comment. More on this later. Functions
  25. 25. 25 Functions The code should be read as if it were prose, top to bottom, from greater to lesser abstraction: public void leemosConfigurationYDetailsUser() { we read User Representation() & we read User Details(); } private void leemosDetailsUser() { read DeLdap() details; } private void leemosUser() settings{ read ConfigDeBaseDeDatos(); } private void readDeLdap() { }
  26. 26. 26 Functions switch: (or if-else multiples) ▸ Are long ▸ Surely they do more than one thing ▸ More difficult to maintain
  27. 27. 27 Functions Integer calculatePaymentEmployed( Employee employee ) { if( employee.type == Employee.MERCHANT_TYPE 1) { calculateCommercial payment( int percentage Commission ) ; } else if ( employee.type == Employee.TRADE_TYPE2 ) { calculatePayment() + getCommissionFix() ; } else if ( employee.type == employee.DIRECTIVO_SHAREHOLDER ) { calculatePaymentADirective( int percentageDeBonus , int numberDeActions ) ; } else if ( employee.type == employee.MANAGER ) { calculatePayment( int of the Commission’s share ) ; } else if ( employee.type == employee.SENORA_LIMIPEZA) { calculaPagoAGerente( int metrosDeOficina ) ; } else if (...) { } else { throw exception("Type of invalid employee") } } Problems: ● Does more than one thing ● The list of types could be unlimited ● Breaches the principle of sole responsibility: there is more than one reason to change it ● Breach in principle of Open/Closed ("O" SOLID) ● Hypothetically, there could be many other modules that have this same if/switch structure
  28. 28. 28 Functions // or Interfaceabstract class Employee{ getSalario() getDiaDePago() ... } class EmployeesFactory {static Employee created EmployedPorTipo(String type) { switch(type) { COMMERCIAL CASE: return new Commercial Employment(); case DIRECTOR: return new EmployedDirective(); case GERENT: return new EmployeedGerente(); } } Class EmployedCommercial implements/extends Employee { Public int getSalario() // real implementation for this type of user. Only this changes if you have to change the form }
  29. 29. 29 Functions - Method Arguments ▸ There should be no more than 2 parameters. 1 better than 2 ▸ 3 are many, and yet must he be justified ▸ Try to avoid (unless just what is expected) changing parameters within a function. Use the return values. ▸ A parameter should never be boolean. If we have a boolean we have an if and that means that the function will do at least two things: do two functions!
  30. 30. 30 Functions - Method Arguments ▸ Functions/methods with 2 parameters ok if related Point point = makePoint( float x, float y) { } } ▸ Can you improve by creating a new class? Circle circle = makeCircle( float x, float y, float radio) Circle circle = makeCircle( Point point, float radio)
  31. 31. 31 Functions - Method Arguments ▸ If there are exceptions... throw an exception!. (It doesn’t have to be processed immediately) ▸ Do not return error codes ( -1, -2 .. ), return an exception or class containing information
  32. 32. 32 Code commentary ▸ There should only be comments when the code is not able to express what it does. ▸ Acceptable comments ▹ and other legal ▹ Warnings of why a decision has been made ▹ JavaDoc for public APIs ▸ Unacceptable: ▹ Those who tease (contradict the code) ▹ Commented obsolete code just in case one day... Use git! ▹ Reviews of Version History ▹ Those who bring nothing
  33. 33. 33 Code commentary /** * Always returns true. */ public boolean isAvailable() { return false; } return 1; // returns 1 // The day of the month private int diaDelMes = 0 // somedev1 - // somedev2 - 6/7/02 Adding temporary tracking of Login screen 5/22/07 Temporary my ass try { .... } catch (Exception e ) { // something bad has h }
  34. 34. 34 Format
  35. 35. 35 Vertical Format ▸ A class (or procedures file) should not have +200 average lines, never +500 ▸ Metaphor of the newspaper: ▹ A class starts with a descriptive title and no details ▹ Then high-level details ▹ Below low level details ▹ A class is a mixture of more and less long articles ▹ "Headlines" should be understood without having to go into detail
  36. 36. 36 Format ▸ Variables should be declared near their use. Exception: class variables at the beginning of the class ▸ Width of screen size, better not to scroll ▸ Do not break bleeding even if there is only one line on a block ▸ If one function invokes another, they should be as close as possible and the caller should be above. ▸ Agree between the team which rules will apply to the entire code. The team rules.
  37. 37. 37 Format ▸ Avoid excessive nesting. If you even have to put comments to know closures... is that there is a serious problem. while ... { if { for { if { [...] } } // for } } // while
  38. 38. 38 Objects and data structures
  39. 39. 39 Objects and data structures ▸ The classes, facing the outside, must hide their internal structure with abstractions that operate on data. ▸ Structures must hide operations and display data ▸ Procedure-oriented code (which uses data structures) facilitates the inclusion of new functions without modifying existing data structures. ▸ Object-oriented code facilitates inclusion of new classes without changing existing functions
  40. 40. 40 Objects and data structures ➢ Shapes are data structures, without behavior. All behavior is in the Geometry class ➢ If we add a perimeter method the classes of shapes (and their descendants) would not be affected ➢ If we add a new form, we have to change all the methods of the Geometry class
  41. 41. 41 Objects and data structures ➢ Method polymorphic area. ➢ We don’t need a Geometry class, each class knows for itself how to behave. ➢ If we add a new form, don’t touch anything from the existing code ➢ But on the other hand, if we add a new operation (perimeter), we must touch all the existing forms
  42. 42. 42 Objects and data structures ▸ So the opposite is also true: ▸ Procedure-oriented code makes it difficult to include new data structures (all functions need to be changed) ▸ Object-oriented code makes it difficult to include new functions because all classes need to be changed.
  43. 43. 43 Objects and data structures ▸ Demeter law ▹ A module should not know the interiors of the objects it manipulates: these must hide their implementation through operations. ▹A method m of a class C must only invoke: ▹ C ▹ Objects created by m ▹ Objects passed as arguments to m ▹ Instance variable objects of C
  44. 44. 44 Functions - Method Arguments File cvsTempFile = new File(getConfig().getTempDir().getAbsolutePath() + "/" + System.currentTimemillis() + ".cvs") File xlsTempFile = new File(getConfig().getTempDir().getAbsolutePath() + "/" + System.currentTimemillis() + ".xls") File tempFile = getConfig(). getCvsTempFile() File tempFile = getConfig(). getXlsTempFile() File tempFile = getConfig(). getTempFileWithExtension( "xls")
  45. 45. 45 Objects and data structures ▸ Data Transfer Objects (or, actually, beans) ▹ Data structure (get/sets). With or without representation in BD ▹ They shouldn’t be behaving. ▸ Special Type: Active Records ▹ More like Grails domain classes ▹ They have save, find... ▹ We may be tempted to add methods with business rules to them. Error!
  46. 46. 46 Error processing
  47. 47. 47 Mistakes ▸ Use exceptions instead of error codes if( conditionError) { return -1 } else if (otherCondition ) { return -2 } else { return 0 } ▸ This forces the caller to immediately verify the condition
  48. 48. 48 Mistakes ▸ (Own crop) ▹ Handle only the exceptions you know how to handle. How are you going to handle a BD connectivity error. Launch it! ▹ Do not gili- catchs try{ } catch { // nothing for here }
  49. 49. 49 Mistakes ▸ Not all exceptions have to be checked. If we do so, we force everyone who calls to change their class signature to verify. ▸ Sometimes it may be necessary but for example in Groovy the majority are Unchecked (or runtimeException), as well as only the catcheas when you need it ▸ Include the context where the exception occurred: let the error message be informative (we already have the stackTrace)
  50. 50. 50 Mistakes ▸ If a third-party bookshop returns us many exceptions it may be convenient to do a wrapping ▸ Do not return null. It requires constant checks and can easily cause NPE (running!) ▸ Do not pass null. I’m sure we have an if first. If we want to verify parameters, it may be good to check that any problem will skip an InvalidArgumentException, or asserts
  51. 51. 51 Limits
  52. 52. 52 Limits ▸ Sometimes the system or generic classes are too "big" for what we need ▸ Use them as little as possible as return values in our APIs (what if they change and ruin something for us? Map books = new HashMap() Book book = new Book(...) books.put( id , book) … Book book2 = (Book)books.get(id) Map<Book> book = new HashMap<Book>()
  53. 53. 53 Limits Class MapaDeLibros { private Map books = new HashMap<Book>() public Book addBook( String key, Book book ){...} public Book getLibro( String key ){ return books.get(key) } // or even old style but at least in a single public site getLibro book( String key ){ return (Book)books.get(key) } }
  54. 54. 54 Unit tests
  55. 55. 55 TDD ▸ The concept of TDD did not exist until 1997. ▸ The tests were mini-programs that we then threw away ▸ Laws of TDD ▹ Do not create code until there is a test that fails ▹ The test code has to be the minimum for the production code to fail ▹ The production code has to be the minimum for the test not to fail ▸ These rules ensure that the code and tests are created in
  56. 56. 56 TDD ▸ Tests are indispensable in modern software development. ▸ Ensure that changes can be made in the future without breaking anything ▸ These are examples of code usage. Do not ignore seemingly trivial tests because they are useful as examples ▸ In tests, readability is even more important. Don’t miss the opportunity to create many variables if it increases readability or penalizes performance ▸ Avoid very long methods with many implementation details
  57. 57. 57 TDD ▸ The tests must be F.I.R.S.T ▹ Fast ▹ Independent ▹ Repeat ▹ Self-Validating ▹ Timely ▸ Not having proof is very bad. But having bad evidence is worse ▸ The test code is not thrown away: it is as important as the "real" one.
  58. 58. versions) ▸
  59. 59. 58 Classes
  60. 60. 59 Classes ▸ Order within the class: ▹ Static constants ▹ Static variables ▹ Instance variables ▹ Methods/Functions. Of all this, first the public and then the private. ▸ Reduced size ▸ Even smaller size
  61. 61. 60 Classes S.O.L.I.D ▸ Single Responsability ▹ A single (and simple) class liability. Just a reason to change class. ▹ Avoid the "while I’m here, I put this too" ▹ If conceptually what you’re going to do is something else, take it out to another class ▸ Open / Closed ▹ A class must be open to extension but closed to modifications ▹ The most common extension is inheritance, but also the composition can be useful. ▸ Liskov Substitution ▹ A daughter class should be able to use instead of a parent: do not reimplement methods that break up superior functioning ▸ Interface Segregation ▹ Los interfaces deben tener un sentido concreto y finito: mejor muchos interfaces pequeños a pocos grandes
  62. 62. 61 Sistemas
  63. 63. 62 Sistemas ▸ Para dedicar una charla entera (o leerse el capítulo 11 del libro): ▹ Factorias abstractas ▹ Inyeccion de dependencias ▹ AOP ▹ Proxies ▹ DSL
  64. 64. 63 Diseño sencillo
  65. 65. 64 Diseño sencillo ▸ Reglas de Kent Beck para diseño sencillo ▹ Que pase todas las pruebas ▹ No hay codigo duplicado ▹ Expresa la intención del programador ▹ Minimiza el número de clases y métodos Refactorizar Hacemos un cambio, pasa los tests, paramos un segundo y pensamos: ¿es mejor que antes?
  66. 66. 65 Eliminar duplicados ▸ DRY! ▸ No solo por comodidad: nos ayudan a reducir la complejidad ▸ Ayudan a pensar como mejorar el código ▸ Si tienes buenos test no tienes que tener miedo a romper nada
  67. 67. 66 Expresividad ▸ Cualquier idiota puede hacer código que compila ▸ Solo un buen programador puede hacer código que otros entiendan ▸ El mayor coste del software es el mantenimiento a largo plazo ▸ Elegir nombres adecuados para metodos, funciones y variables.
  68. 68. 67 Concurrencia
  69. 69. 68 Concurrencia ▸ Capítulo (13) tambien para dedicarle un tiempo aparte. ▸ Notitas: ▹ Multiproceso no siempre mejora rendimiento: solo si tenemos varios procesadores o máquinas ▹ El diseño del programa cambia si tenemos concurrencia ▹ Muchas veces es mas que conveniente usar objetos inmutables. ▹ Es necesario conocer la infraestructura subyacente (contenedor web, ejbs..) ▹ Saber que clases admiten sincronizacion y cuales no (Hashtable, Hashmap…) ▹ Puede ser conveniente separar el código concurrente del resto. Y que sea lo más pequeño posible. ▹ Usar colas: Product-Consumer o Publish-Subscribe para desacoplar ▹ Bloqueos: controlar, provocar y prevenir ▹ Si usamos synchronized que sean bloques lo mas pequeños posibles para prevenir deadlocks
  70. 70. 69 Suficiente por hoy! Esto ha sido una introducción. Recomendación: leeros el libro!. Ved mas videos y slides Preguntas?
  71. 71. 70 Suficiente por hoy! Esto ha sido una introducción. Recomendación: leeros el libro!. Ved mas videos y slides Preguntas?
  72. 72. 71 Suficiente por hoy! Esto ha sido una introducción. Recomendación: leeros el libro!. Ved mas videos y slides Preguntas?
  73. 73. 72 Suficiente por hoy! Esto ha sido una introducción. Recomendación: leeros el libro!. Ved mas videos y slides Preguntas?
  74. 74. 73 - - - Let’s start with the first set of slides
  75. 75. THIS IS YOUR PRESENTATION TITLE
  76. 76. 75 Instructions for use Open this document in Google Slides (if you are at slidescarnival.com use the button below this presentation) You have to be signed in to your Google account EDIT IN GOOGLE SLIDESGo to the File menu and select Make a copy. You will get a copy of this document on your Google Drive and will be able to edit, add or delete slides. EDIT IN POWERPOINT® Go to the File menu and select Download as Microsoft PowerPoint. You will get a .pptx file that you can edit in PowerPoint. Remember to download and install the fonts used in this presentation (you’ll find the links to the font files needed in the Presentation design slide) More info on how to use this template at www.slidescarnival.com/help-use-presentation-template This template is free to use under Creative Commons Attribution license. You can keep the Credits slide or mention SlidesCarnival and other resources used in a slide footer.
  77. 77. 76 HELLO! I am Jayden Smith I am here because I love to give presentations. You can find me at @username
  78. 78. 77 1. Transition headline Let’s start with the first set of slides
  79. 79. “ Quotations are commonly printed as a means of inspiration and to invoke philosophical thoughts from the reader.
  80. 80. 79 This is a slide title ▸Here you have a list of items ▸And some text ▸But remember not to overload your slides with content You audience will listen to you or read the content, but won’t do both.
  81. 81. 80 BIG CONCEPT Bring the attention of your audience over a key concept using icons or illustrations
  82. 82. 81 You can also split your content White Is the color of milk and fresh snow, the color produced by the combination of all the colors of the visible spectrum. Black Is the color of coal, ebony, and of outer space. It is the darkest color, the result of the absence of or complete absorption of light.
  83. 83. 82 In two or three columns Yellow Is the color of gold, butter and ripe lemons. In the spectrum of visible light, yellow is found between green and orange. Blue Is the colour of the clear sky and the deep sea. It is located between violet and green on the optical spectrum. Red Is the color of blood, and because of this it has historically been associated with sacrifice, danger and courage.
  84. 84. 83 A picture is worth a thousand words A complex idea can be conveyed with just a single still image, namely making it possible to absorb large amounts of data quickly.
  85. 85. 84 Want big impact? USE BIG IMAGE
  86. 86. 85 Use charts to explain your ideas White Gray Black
  87. 87. 86 And tables to compare data TO B C Yellow 10 20 7 Blue 30 15 10 Orange 5 24 16
  88. 88. 87 Maps our office
  89. 89. 88 89,526,124 Whoa! That’s a big number, aren’t you proud?
  90. 90. 89 89,526,124$ That’s a lot of money 185,244 users And a lot of users 100% Total success!
  91. 91. 90 Our process is easy first second last
  92. 92. 91 Let’s review some concepts Yellow Is the color of gold, butter and ripe lemons. In the spectrum of visible light, yellow is found between green and orange. Blue Is the colour of the clear sky and the deep sea. It is located between violet and green on the optical spectrum. Red Is the color of blood, and because of this it has historically been associated with sacrifice, danger and courage. Yellow Blue Red Is the color of gold, butter and Is the colour of the clear sky and Is the color of blood, and ripe lemons. In the spectrum of the deep sea. It is located because of this it has historically visible light, yellow is found between violet and green on the been associated with sacrifice, between green and orange. optical spectrum. danger and courage.
  93. 93. 92 You can insert graphs from Google Sheets
  94. 94. 93 Place your screenshot here ANDROID PROJECT Show and explain your web, app or software projects using these gadget templates.
  95. 95. 94 Place your screenshot here iPHONE PROJECT Show and explain your web, app or software projects using these gadget templates.
  96. 96. 95 Place your screenshot here TABLET PROJECT Show and explain your web, app or software projects using these gadget templates.
  97. 97. 96 Place your screenshot here DESKTOP PROJECT Show and explain your web, app or software projects using these gadget templates.
  98. 98. 97 THANKS! Any questions? You can find me at @username & user@mail.me
  99. 99. 98 Credits Special thanks to all the people who made and released these awesome resources for free: ▸ Presentation template by SlidesCarnival ▸ Photographs by Startupstockphotos
  100. 100. 99 Presentation design This presentation uses the following typographies and colors: ▸ Titles: Dosis ▸ Body copy: Roboto You can download the fonts on these pages: https://www.fontsquirrel.com/fonts/dosis https://material.google.com/resources/roboto-noto-fonts.html ▸ Orange #ff8700 You don’t need to keep this slide in your presentation. It’s only here to serve you as a design guide if you need to create new slides or download the fonts to edit the presentation in PowerPoint®
  101. 101. 100 SlidesCarnival icons are editable shapes. This means that you can: ● Resize them without losing quality. ● Change line color, width and style. Isn’t that nice? :) Examples:
  102. 102. 101 Now you can use any emoji as an icon! And of course it resizes without losing quality and you can change the color. How? Follow Google instructions https://twitter.com/googledocs/status/730087240156643328 ✋ ❤ and many more...
  • RixVii

    Dec. 27, 2020

clean code book summary - uncle bob - English version

Aufrufe

Aufrufe insgesamt

40

Auf Slideshare

0

Aus Einbettungen

0

Anzahl der Einbettungen

0

Befehle

Downloads

1

Geteilt

0

Kommentare

0

Likes

1

×