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.
Enterprise Java Training
© Copyright Victor Rentea P.F.A. 2015
www.VictorRentea.ro
The Art of
Clean Code
Victor Rentea
Mar...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
About Me
 Victor Rentea, P...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Funct...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Clean Code …
…does one thi...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
The true cost of software ...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Funct...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Packages, namespaces
Clas...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Packages – 1 word
Classes...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Functions are verbs
getNam...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Why it exists? What it doe...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Pronounceable
int getinvcd...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Provide Meaningful Context...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Variables: big scope  lon...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Funct...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
"A function should do one t...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
How small ?
- 4 lines is b...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
The layout of a long funct...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Instead of a familiar land...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
This is why we want to lea...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Same Goal: the code should...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
No nullable parameters
- I...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
By continuous refactoring ...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
You Extract Till You Drop: ...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Reduces the number of inde...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
= how to refactor God Metho...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
= when a function changes t...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
1.A Query doesn't have side...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
A consequence of side effe...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Funct...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
The member order: [Standar...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Define a constant in the c...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
=classes that expose all th...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
=hide implementation detail...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
=classes that hide their st...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
void m(P p) {
memberF();
fi...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
=code that works with too m...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Conditionals over Polymorph...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Runtime dependency usually...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Make A depend on an interf...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Introduction
Names
Funct...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
It's all about communicati...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
< 100-120 chars/line
 < 1...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
=they compensate for our in...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
public List<int[]> getFlagg...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Mumbling
- Unclear
- Rush/...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Intent: WHY?(what?)
- When...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
48
Names
 Choose descripti...
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
49
Special Thanks to
Ionuţ ...
50
Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015
Bucharest Java User Group
Clean Code
Robert C. Marti...
Nächste SlideShare
Wird geladen in …5
×

Clean Code

2.613 Aufrufe

Veröffentlicht am

How should a professional software developer behave in code? What guidelines should one follow? How should we name our constructs? What about OOP principles? What's their real use?
This classic training module in my training curricula is the cornerstone of my professionalism. These are my conduit guidelines at work. I've held this training > 10 times, including at Voxxed Days Bucharest 2016 and at a Bucharest Java User Group meetup.

Veröffentlicht in: Software

Clean Code

  1. 1. Enterprise Java Training © Copyright Victor Rentea P.F.A. 2015 www.VictorRentea.ro The Art of Clean Code Victor Rentea March 23, 2016 @ Bucharest Java User Group Voxxed Days Bucharest 2016
  2. 2. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group About Me  Victor Rentea, PhD(CS) - Technical Team Lead, Senior Java Engineer at IBM Romania - Independent Trainer PFA: - victorrentea@gmail.com - www.VictorRentea.ro - - @victorrentea 2 Who am I ?
  3. 3. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 3
  4. 4. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Clean Code … …does one thing well …reads like well written prose ...looks like it was written by someone who cares ...is when each method you read turns out to be pretty much what you expected [The Principle of Least Astonishment] anyone can write code that a computer understands, but few programmers know how to write code that a human can understand Introduction What is Clean Code ? 4 Bjarne Stroustrup inventor of C++ Grady Booch inventor of UML Michael Feathers author of Working Effectively with Legacy Code Martin Fowler author of Refactoring Ward Cunningham inventor of Wiki, coinventor of eXtreme Programming
  5. 5. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group The true cost of software = its maintenance - 80% of the total cost+effort of software is in maintenance. Why ? - Because we get slower and slower, as the code gets dirtier and begins to ROT We READ 10x more time than we WRITE Do your best to increase readability, even if it makes writing harder  Always check in cleaner code than you found (Boy scout rule) Introduction Why Clean Code ? 5
  6. 6. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 6
  7. 7. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Packages, namespaces Classes, interfaces Functions Variables, parameters Class fields Constants, enums, ...  We do a lot of naming, so we must be good at it Names We name everything 7
  8. 8. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Packages – 1 word Classes, interfaces Functions Variables, parameters Class fields Constants enum values ≈constants customer.service Customer, OrderService placeOrder() customerName age, phoneNumber CUSTOMER_PAGE_SIZE {SINGLE, MULTIPLE} Names The JavaCaseConventions 8
  9. 9. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Functions are verbs getName(), sendEmail(), execute(), placeOrder() - Boolean functions should answer yes/no isGoldClient(), hostsAreValid() Classes are nouns Customer, OrderLine, SpecialSalesOffer, OrderFacade - Iron out as much domain concepts ASAP - Avoid meaningless prefixes or suffixes: ICustomerService, OrderInfo, OrderData, OrderServiceImpl Names “Well Written Prose” 9
  10. 10. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Why it exists? What it does? How it's used? You should NOT need: 1. an /* explanatory comment */ 2. to descifer its implementation, or 3. to hunt down the code using it Make the name speak for itself !! Just go back and rename it whenever you feel so - Your team will be grateful! And even you will, in 3 months! - With an IDE, it's a matter of seconds with almost no risk Names should… Names Explain Intent 10
  11. 11. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Pronounceable int getinvcdtlmt() vs. int getInvoiceableCreditLimit() - Avoid abbreviations ! (except a fundamental business concept) Consistent DAO.findXyz() .fetchXyz() or .getXyz() – pick one but stick to it - When you add code, choose names that preserve consistency (read some code to understand the de facto naming conventions) Unique: Synonyms are bad, they confuse When referring to a customer, don't also use buyer or client in code - Use ubiquitous language: customer if that’s the prevalent business term Names: Several Guidelines Names Should be … 11
  12. 12. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Provide Meaningful Context Order.customerFirstName - But don't repeat yourself: Order.orderCreationDate Sort nicely at CTRL-SPACE - Related classes should begin similarly CustomerService, CustomerDAO, Customer, CustomerExporter Think positive about booleans isActive() instead of isInactive() or isNotActive() - Read this: !isInactive() :-S Names: Several Guidelines Names Should… 12
  13. 13. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Variables: big scope  long descriptive name - For loop variables can be 1 letter - Method variables: 1+ word - Method parameters: 1++ word  Documentation: are shown by the IDE - Fields: a bit longer - Constants: self-explanatory names Functions & Classes: big scope  short name - public names should be convenient: short and easy to remember - private functions should have long descriptive names Names Name Length 13 public class AClass { public final static int CONST_WITH_EXPLANATORY_NAME; private String instanceField; public void myMethod(String parameter) { String variable; for (int i = 0; i < 100; i++) { ... } } }
  14. 14. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 14
  15. 15. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group "A function should do one thing, it should do it well and it should do it ONLY"[UBob] They should be Small in order not to surprise us - Principle of Least Astonishment Functions Functions 15
  16. 16. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group How small ? - 4 lines is best; 5 is ok; 6 is already too much - By any means, keep your functions smaller than a page of your IDE ! Why so small ?! To be sure that they do only 1 THING In a few lines, you can’t do much Its name can then tell you everything Functions Functions Should be Small !! 16
  17. 17. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group The layout of a long function is like a landscape - Humans, are good at memorizing landscape This landscape is familiar to the author But for the rest of the team, this function is completely unknown, it's like wilderness Functions Why do small functions scare us? Function Landscape 17 if for if if if for else if for if if for
  18. 18. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Instead of a familiar landscape - in which only you (the author) orient very well You're now swimming in a sea of small functions - You're not so comfortable anymore, - But it's to the end good of the entire team ! Choose long descriptive names - They will act as signposts guiding you and your team - The reader will now be able to quickly understand your code Functions Why do small functions scare us? A Sea of Small Functions 18 (the author) else for if
  19. 19. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group This is why we want to leave landmarks behind; we split long functions into many small functions with carefully chosen long names that guide the reader Functions Act Professional 19 sendActivation EmailToCustomer() removeAllPast CancelledOrders OfConsumer()
  20. 20. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Same Goal: the code should speak for itself - The reader shouldn't have to look at the function definition nor to its usages Max 2 parameters - For ≥ 3 parameters, it's hard to read: their order becomes a problem  group them in a Parameter Object/DTO Avoid output parameters - The caller may be surprised that an argument changed No flag parameters (boolean, enum) = laziness/fear - It shouts that the function does more than one thing !  Split it into smaller functions customer.setLoggedIn(true); Functions Function Signature (1) 20 myBadMethod("John","Michael", "Paris","St. Albergue"); checkCustomer(customer, order); removeOrders(customer, false, true); params.setStreet("Paris");… myBadMethod(params); ?!
  21. 21. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group No nullable parameters - It's like a boolean  split that function in 2: one for null, one for not-null - Thoroughly check parameters at boundaries (=defensive programming) Don’t return null - Null is the worst mistake in IT [dzone]  Consider Optional<> / throw exception / Null Object Pattern Unchecked Exceptions won ! - No more try/throws/empty catch(); no return status codes - Runtime Exceptions don’t annoy the caller  Can be handled uniformly in a transparent layer at the entry points  Can hold enum error codes for (i18n) user messages  Define custom exception sub-types for recoverable errors (selective catch) Functions Function Signature (2) 21
  22. 22. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group By continuous refactoring to clean up the code You are not done when the code starts working! It is then when you should clean up your code !! - IDEs help you a lot - But only rigorous unit tests can guarantee that you don't break anything  Test-Driven Development Functions - Techniques How to write such Functions ? 22
  23. 23. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group You Extract Till You Drop: [UBob] Try to extract as many functions as possible Into methods that tell what they do - by their long nice name - (you document your code this way making it easier to understand) … until you simply cannot extract any more [opt] - (when extracting again would basically duplicate a method) = Extreme Functions - Techniques Split Your Functions ! 23
  24. 24. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Reduces the number of indentations - Max number of TABs can be restricted: Readability ++ Functions - Techniques Function body : Early returns 24 public List<Integer> stringsToInts( List<String> strings) { if (strings != null) { List<Integer> integers = new ArrayList<>(); for (String s : strings) { integers.add(Integer.parseInt(s)); } return integers; } else { return null; } } public List<Integer> stringsToInts2( List<String> strings) { if (strings == null) { return null; } List<Integer> integers = new ArrayList<>(); for (String s : strings) { integers.add(Integer.parseInt(s)); } return integers; }
  25. 25. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group = how to refactor God Methods into shiny new classes ? Functions - Techniques Extract Method Object refactor 25 public String aLongMethod(String text) { Set<String> words = new HashSet<String>(); int totalWords = 0; int totalPhrases = 0; StringTokenizer tokenizer = … while (tokenizer.hasMoreTokens()) { String nextToken = tokenizer.nextToken(); … if (…) { for (…) {…} … } else { … } } } public class ExtractedMethodCommand { private final String text; private Set<String> words = new HashSet<>(); private int totalWords = 0; private int totalPhrases = 0; private StringTokenizer tokenizer; public ExtractedMethodCommand(String text) { this.text = text; tokenizer = new StringTokenizer(text, " "); } public String execute() {…} } Extracting this block as a method require lots of parameters, output parameters or may even be impossible These methods use instance fields, and take no/fewer arguments String result = aLongMethod(”bla”); String result = new ExtractedMethodCommand(”bla”).execute();
  26. 26. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group = when a function changes the state of the system - e.g. loginUser(), openConnection(), persistCustomer(), checkUser() A necessary evil: they can surprise us - and break the Least Astonishment Principle Explain them - checkUserAndInitializeHisSession(User) Functions – Advanced Topics Side Effects 26
  27. 27. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group 1.A Query doesn't have side effects and returns a result getState():State, isLoggedIn():boolean, findCustomer():Customer 2.A Command changes the system state and returns void processOrder(Order), consumeMessage(Message), setName(String) Avoid doing both in the same method processOrder(Order):boolean (that returns false if it failed) (It forces the caller to check the result right away. Prefer exceptions instead!) Functions – Advanced Topics Command / Query Separation 27 ? !
  28. 28. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group A consequence of side effects Open the DB connection  do stuff  close DB connection Leads to mysterious code - “Hack!! No one told me that I should have called .initialize() first !!" Can be partially avoided by passing a block - Execute on connection ( set_of_instructions ) Spring’s JdbcTemplate, RestTemplate, … - Java8 lambdas make it a lot easier ()->{stuff;} Functions – Advanced Topics Temporal Coupling 28
  29. 29. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 29
  30. 30. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group The member order: [Standard Java Conventions] 1. Fields 2. Constructors 3. Methods - Start with the public methods - That call private methods  That call private methods down... etc The reader should search down Classes Basic Shape 30 public class ExtractedMethodCommand { private static final String MY_CONST=“val”; private Set<String> words = new HashSet<String>(); private int totalWords = 0; private int totalPhrases = 0; private StringTokenizer tokenizer; public ExtractedMethodCommand(String text) {… } public String execute() {…} private void doInternalVeryUsefulStuff() {…} }
  31. 31. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Define a constant in the class that uses it the most - Even in a domain entity class - DO NOT create a dreadful 4000-lines Constants class ! The same for enums - Next to that class or even nested inside Classes Constants 32
  32. 32. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group =classes that expose all their internal state - to external procedures that manipulate them - These classes don't usually hold much functionality Objects vs. Data Structures Data Structures (≈ C struct) 33 Getters/setters exposing all private fields is NOT encapsulation ! public class PhoneBookEntryDTO { private String firstName; private String lastName; private String phoneNumber; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { … } public void setLastName(…) { … } public String getPhoneNumber() { … } public void setPhoneNumber(…) { … } } public class SimpleImmutableStruct { private final String firstName; private final String lastName; public SimpleImmutableStruct( String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } Why we Immutable Objects: - Preserve their consistency after creation - Thread safe - Safe for sort-/hash-based collections public class PhoneBookEntryDTO { public String firstName; public String lastName; public String phoneNumber; } ≈
  33. 33. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group =hide implementation details from your client Expose operations rather than data car.startEngine() instead of car.setEngineStarted(true) or car.engineStarted=true - Data is concrete, it's an implementation detail Try to minimize the object's observable state Expose data as abstract as possible car.getPercentageFuelLeft() instead of getGasolineInLiters() Objects vs. Data Structures True Encapsulation 34 car.getEstimatedRemainingKm()
  34. 34. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group =classes that hide their state behind abstractions - and expose functionality as public methods, so that - their caller works with them without knowing their implementation Objects vs. Data Structures True Objects (as in OOP) 35 public class Car { private double remainingGasoline; private double reservoirCapacity; public double getRemainingGasolineInLiters() { return remainingGasoline; } public double getReservoirCapacityInLiters() { return reservoirCapacity; } public double getRemainingFuelRatio() { return remainingGasoline/reservoirCapacity; } } structs OOP
  35. 35. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group void m(P p) { memberF(); field.fieldF(); p.parameterF(); new Obj().f(); Math.sqrt(4); Don’t ask the state of other objects, instead, tell them what to do 1. Encapsulation - Keep behavior next to state 2. Low coupling - Less knowledge about other objects Avoid Train Wrecks: - getRoot().getManager().getMessageWidget().showMessage("blah") Classes Tell, Don’t Ask Principle 36 The Law of Demeter A function m() of ClassX should call only methods of: • ClassX • a field of ClassX • m()'s parameters • objects created within m() • globals (in short: "use only one dot")
  36. 36. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group =code that works with too much data of another class …probably belongs inside that other class - This refactoring usually simplifies the code - Did you thought about the Law of Demeter ?  - Is the envy gone from our example ? Classes Feature Envy 37 public class Rental { private MovieCopy movieCopy; … public String getStatement() { return "t" + movieCopy.getMovie().getTitle() + "t" + movieCopy.getMovie().getPrice() + "n"; } } public class MovieCopy { private Movie movie; public String getStatement() { return "t" + movie.getTitle() + "t" + movie.getPrice() + "n"; } } return movieCopy.getStatement();
  37. 37. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Conditionals over Polymorphic Data Structures Objects  Easy to add functions +1 type-specific functionality = a new switch e.g. getMaxLoanDays()  Dangerous to add types +1 type = a new case in all the existing switches abstract methods need to be defined by each concrete type  Safe to add types - Java forces us to implement all the necessary methods  More artifacts: + 3 classes 38 Objects vs. Data Structures: Replace Conditionals with Polymorphism VS switch (movie.getType()) { case NEW_RELEASE: … break; case REGULAR: … break; case CHILDRENS: … break; } public class NewReleaseMovie extends Movie { @Override public double func(…) { … } } Movie #func() RegularMovie ChildrensMovie
  38. 38. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Runtime dependency usually goes the same way as source code dependency - Class A imports the class B (source code dependency) - …so that A can then invoke a method in B (runtime dependency) With OO, we can inverse the source code dep. Classes Best of OOP:[UBob] The Plugin Model 39 Module 2Module 1 A B import B; b.method()
  39. 39. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Make A depend on an interface I - That contains the method(s) that need to be invoked in B Make B implement I - It thus must have code source dependency on I A needs an instance of type I  give it a B instance - Easily done using an dependency injection framework (EJB, Spring, Guice) - At runtime, A still invokes B (), but Module 1 does not depend on Module 2 anymore Classes The Plugin Model: Dependency Inversion 40 Module 2Module 1 A B import I .method() import = abstractions should not depend on details, details should depend on abstractions
  40. 40. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Introduction Names Functions Classes Formatting & Comments Contents Agenda 41
  41. 41. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group It's all about communication - Communication is the most important activity of a professional developer Don't ignore the formatting rules, Nor follow them blindly - The purpose is to express your intent in code as clearly as possible Have the IDE help you Formatting Code Formatting 42
  42. 42. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group < 100-120 chars/line  < 100-200 lines/file, never > 500  < 5-10 lines/method, never > 1 screen Indentation: Team 2-3-4 chars or TAB ? Egyptian-style or not ? ... - Establish a team style and follow it [+stylesheet?] - Never reformat the entire file using your IDE – only several selected lines  Manual formatting can be more expressive:  We just merge conflicts at commit, don’t we  Don't collapse: { return 0; } or if (cond) doStuff(); Formatting Several Suggestions 43 Customer customer = new Customer.Builder() .withName("John Doe") .withAddress(new Address.Builder() .withStreetName("Viorele") .build()) .build(); { }
  43. 43. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group =they compensate for our inability to express in code Always before dropping a comment And see whether you can express it in code Why should we hate comments ? Because they usually LIE ! - As they immediately fall out of sync with the code Comments Comments are Failures 44
  44. 44. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group public List<int[]> getFlaggedCells(){ List<int[]> flaggedCells = new A…L…<…>(); for (int[] cell : gameBoard) { boolean isFlagged = cell[STATUS_VALUE] == FLAGGED; if (isFlagged) flaggedCells.add(x); } return flaggedCells; } public List<Cell> getFlaggedCells(){ List<Cell> flaggedCells = new A…L…<Cell>(); for (Cell cell : gameBoard) { if (cell.isFlagged()) flaggedCells.add(cell); } return flaggedCells; } Constants - Instead of magic numbers Explanatory variables - Locals that store intermediary results Explanatory methods - To name a given computation - "Encapsulate Conditionals" Split the code - into many small private functions with long descriptive names, remember? This is how to document your code ! Comments Code Expressiveness ++ 45 public List<int[]> getCells(){ List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) { if (x[0] == 4) list1.add(x); } return list1; }
  45. 45. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Mumbling - Unclear - Rush/lazy Redundant Mandated or Noise /** Default constructor. */ Position Markers //////// Accessors ////// Commented-out Code - Don't read it. Just DELETE IT! - (You SCM rocks !) HTML JavaDocs Non-local Information - Comment code on that line (±1) Comments Bad Comments 46 /** * Returns the day of the month. * * @return the day of the month. */ public int getDayOfMonth() { return dayOfMonth; } DUH !! stream.close(); } catch (IOException e) { // Oh! Give me a break! }
  46. 46. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Intent: WHY?(what?) - When the code just can't say it specific algorithms/calculus bug workarounds - An URL link can explain it all Clarifications To explain calls to an external API (if its usage is strange) Warning of consequences - that might not be obvious TODOs // TODO vrentea Fetch the order - Assume ownership Public API JavaDocs - for libraries/frameworks you write Legal // Copyright (C) 2013, … Comments Good Comments 47 SimpleDateFormat sdf = new SimpleDateFormat(…); // Not thread-safe. Keep it local!
  47. 47. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group 48 Names  Choose descriptive names  Unambiguous names, no synonyms  Use an ubiquitous language if possible  Use long variable names for long scopes  Make side-effects clear  Avoid encodings (e.g. m_...) Functions  Too many arguments  Output arguments  Flag arguments  Dead function (no callers)  Functions should do one thing  Function names should say what they do Comments  Redundant Comment  Obsolete Comment  Commented-out code General  Duplication: DRY  Multiple languages in one source file  Incorrect behavior at the boundaries  Clutter: default constructor, unused code, …  Feature Envy  Avoid transitive navigation(Law of Demeter)  Hidden temporal couplings  Follow standard conventions  Use explanatory variables and functions  Extract magic numbers as constants  Encapsulate conditionals  Avoid negative conditions Tests  Insufficient tests: use a test coverage tool  Don't skip trivial tests  Test boundary conditions  Exhaustively test near bugs  Tests should be fast ! Summary – Code Smells and Heuristics & Part2Part1
  48. 48. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group 49 Special Thanks to Ionuţ Chereji Laurenţiu Carată Victor Bucuţea Florin Diaconu Ionuţ Scutaru Leonard Giura
  49. 49. 50
  50. 50. Clean Code | Enterprise Java Training © Copyright Victor Rentea 2015 Bucharest Java User Group Clean Code Robert C. Martin (aka Uncle Bob), 2008 Clean Coders videos http://www.cleancoders.com/ : Uncle Bob Refactoring Martin Fowler, 1999  NULL – the worst mistake in IT - https://dzone.com/articles/the-worst-mistake-of-computer-science-1  The Clean Architecture: - http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html  Some  Programming Jargon - http://blog.codinghorror.com/new-programming-jargon/ Want to dig more ? References 51

×