SlideShare a Scribd company logo
Practices for becoming  a better programmer Srikanth P Shreenivas [email_address]   http://www.srikanthps.com
Joys of the craft The Mythical Man-Month, Frederick P. Brooks. Jr Slide    Why is programming fun? What delights may its practitioner expect as reward? First is the sheer joy of making things. Second is pleasure of making things that are useful to other people. Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts and watching them work in subtle cycles, playing out the consequences of principles built in the beginning. The programmed computer has all the effects of a pinball machine or jukebox mechanism, carried to the ultimate. Fourth is the joy of always learning, which springs from non-repeating nature of the task. Finally, there is the delight of working in such a tractable medium.  The programmer, like the poet, works only slightly removed from pure thought-stuff.  He builds his castles in the air, from the air, creating by exertion of imagination. Programming gratifies creative longings built deep within us
Values of Programming Implementation Patterns, Kent Beck Communication Simplicity Flexibility Slide
Communicating through code
Use Meaningful Names int d; //elapsed time in days int elapsedTimeInDays; int fileAgeInDays; int daysSinceLastModification; Intention-revealing names
Use Meaningful Names Set  hobbyList; Set  hobbies; Avoid   Disinformation
Use Meaningful Names Slide    Public void copy (String s1, String s2) Make meaningful distinctions Public void copy(String destination, String source)
Meaningful names Slide    class DtaRcrd102 Use pronounceable names class Customer
Meaningful names Slide    int r = 0; for (int j = 0; j < 5; j++) { r = r + j * 8; } Use searchable names int workingDaysInWeek = 5; int workingHoursPerDay = 8; int hoursInWeek = 0; for (int dayIndex = 0; dayIndex < workingDaysInWeek ; dayIndex ++) { hoursInWeek = hoursInWeek + dayIndex * workingHoursPerDay; }
Meaningful names Slide    Class names Should be nouns or noun phrases. Examples: Car,  Account,  DataRetrievalService, AddressParser
Meaningful names Slide    Method names Should be verb or verbPhrases Examples:  parseData ,  deletePage ,  save Methods that return boolean values should sound like question. Example:  isAuthenticated ,  hasNoErrors ,  isEmpty if (user.isAuthenticated()) { String data = parseData(input); if (hasErrors(data)) { throw ErrorInDataException(); } }
Meaningful names Slide    Pick one word per concept Don’t mix words like “fetch”, “get”, “retrieve”. Be consistent.
Meaningful names Slide    Don’t use same word for two different concepts Example: Don’t use “add”, where “insert” makes sense.
Meaningful names Slide    Use names from problem/solution domain Prefer “InvoiceGenerator” to “DataExtractor”
You don’t need comments to communicate
Turning Comments into Code Slide    class InchToPointConvertor { //convert the quantity in inches to points. static float parseInch(float inch) { return inch * 72; //one inch contains 72 points. } } class InchToPointConvertor { final static int POINTS_PER_INCH=72; static float  convertToPoints (float inch) { return inch *  POINTS_PER_INCH ; } }
Turning Comments into Code Slide    class Account { ... //check if the password is complex enough, i.e., //contains letter and digit/symbol. boolean isComplexPassword(String password) { //found a digit or symbol? boolean dg_sym_found=false; //found a letter? boolean letter_found=false; for(int i=0; i<password.length(); i++){ char c=password.charAt(i); if(Character.isLowerCase(c)||Character.isUpperCase(c)) letter_found=true; else dg_sym_found=true; } return (letter_found) && (dg_sym_found); } } class Account { ... boolean isComplexPassword(String password){ return containsLetter(password) && (containsDigit(password) || containsSymbol(password)); } boolean containsLetter(String password) { ... } boolean containsDigit(String password) { ... } boolean containsSymbol(String password) { ... } }
Turning comments into code Slide    Are we writing comments because our code is unclear? Will you keep the comments up-to-date whenever code is updated? What’s wrong with Comments? Nothing wrong with comments.  They are not bad. Why avoid comments? Unclear code with outdated comments. You don’t want: Try to convert comments into code that bring out the intent of the code, and use comments sparingly.
Aiming for Simplicity
Functions Slide    Write small functions … .and try to write even smaller functions. Aim for functions that are not longer than 4 to 5 lines. Split the big methods in smaller methods (Extract method) Use intention-revealing names for methods. Public List<Person> filterList(List<Person> input) { List filteredList = new ArrayList(); for (Person p : input) { if (p.getDateOfBirth().getYear() > 1997) { filteredList.add(p); } if (p.getAddress().getCity().equals(“Bangalore”))  { filteredList.add(p); } } return filterdList; } Public List<Person> selectTeenAgersFromBangalore (List<Person> input)  { List filteredList = new ArrayList(); for (Person p : input) { if (isTeenAger(p) || isFromBangalore(p)) { filteredList.add(p); } } return filterdList; }
Functions Slide    Do one thing in a function (Single responsibility) Public List<Person> filterList(List<Person> input) { List filteredList = new ArrayList(); for (Person p : input) { if (p.getDateOfBirth().getYear() > 1997) { filteredList.add(p); } if (p.getAddress().getCity().equals(“Bangalore”))  { filteredList.add(p); } } return filterdList; } Public List<Person> selectTeenAgersFromBangalore (List<Person> input)  { List filteredList = new ArrayList(); for (Person p : input) { if (isTeenAger(p) && isFromBangalore(p)) { filteredList.add(p); } } return filterdList; } Filtering logic moved out
Functions Slide    All statements should be at same level of abstraction. Employee  employee = employeeRepository.get(“m100XXXX”); employee.getSalaryDetails().setBasic( employee.getSalaryDetails().getBasic () * 1.10); employeeRepository.save(employee); Employee  employee = employeeRepository.get(“m100XXXX”); raiseSalary(empoyee, “10%”); employeeRepository.save(employee); Functions should be read like top-down narrative. Every function should be followed by functions of next level of abstraction.
Functions Slide    Have no side effects. Public boolean checkPassword(String userName, String password) { User user = userService.getUser(userName); if (user.password.equals(password)) { Session.initalize(); return true;   } return false; }
Functions Slide    Command query separation. Public boolean set(String attribute, String value) { … . } if (set(“color”, “red”)) { … . } if (attributeExists(“color”)) { }
Functions Slide    Prefer exceptions to return codes. if (deletePage(“myPage”) == E_OK) { … . } else  { logger.log (“delete failed”); } try { deletePage(“myPage”); } catch (PageCannotBeDeletedException p) { … } catch (PageDoesNotExistException e) { … }
Functions Slide    Format your code. Use IDE supported code formatting tools. Configure IDE to support team-specific alignment rules. opening brace “{“ should be on the same line as the statement. use space after keywords if (someCondtion) use space to separate method arguments doSomething( param1, param2, param3 ); indent each scope by 4 spaces Ctrl+Shift+F in Eclipse
DRY – Don’t repeat yourself
Code which started well… Slide    public class BookRental { String id; String customerName; ... } public class BookRentals { private Vector rentals; public String getCustomerName(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { return rental.getCustomerName(); } } throw new RentalNotFoundException(); } } public class RentalNotFoundException extends Exception { ... } Book Rentals Applications: Maintains a list of books rented to customers. New requirement: Add a method to delete rental given its id.
Code updated for new requirement… Slide    public class BookRental { String id; String customerName; ... } public class BookRentals { private Vector rentals; public String getCustomerName(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { return rental.getCustomerName(); } } throw new RentalNotFoundException(); } public void deleteRental(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { rentals.remove(i); return; } } throw new RentalNotFoundException(); } } public class RentalNotFoundException extends Exception { ... } Duplicate Code
Duplicate code should be avoided Slide    What’s wrong with duplicate code? If there is a bug in the code or code requires changes, then, one has to change it at multiple places.  This is error-prone. public class BookRentals { private Vector rentals; public String getCustomerName(String rentalId) { int rentalIdx = getRentalIdxById(rentalId); return ((BookRental) rentals.elementAt(rentalIdx)).getCustomerName(); } public void deleteRental(String rentalId) { rentals.remove(getRentalIdxById(rentalId)); } private int getRentalIdxById(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { return i; } } throw new RentalNotFoundException(); } }
Removing duplicate code Slide    Point out and remove duplicate code class Organization { String id; String eName; //English name String cName; //Chinese name String telCountryCode; String telAreaCode; String telLocalNumber; String faxCountryCode; String faxAreaCode; String faxLocalNumber; String contactPersonEFirstName; //First name and last name in English String contactPersonELastName; String contactPersonCFirstName; //First name and last name in Chinese String contactPersonCLastName; String contactPersonTelCountryCode; String contactPersonTelAreaCode; String contactPersonTelNumber; String contactPersonFaxCountryCode; String contactPersonFaxAreaCode; String contactPersonFaxLocalNumber; String contactPersonMobileCountryCode; String contactPersonMobileAreaCode; String contactPersonMobileLocalNumber; ... } Organization’s and Person’s Telephone number format is same Organization’s and Person’s names are stored in English and Chinese.
Removing duplicate code Slide    Duplicate code removed class Organization { String id; String eName; String cName; TelNo telNo; TelNo faxNo; ContactPerson contactPerson; ... } class ContactPerson{ String eFirstName; String eLastName; String cFirstName; String cLastName; TelNo tel; TelNo fax; TelNo mobile; } class TelNo { String countryCode; String areaCode; String localNumber; } class ContactPerson { FullName eFullName; FullName cFullName; TelNo tel; TelNo fax; TelNo mobile; } class FullName  { String firstName; String lastName; }
Removing code smells
Code Smells Duplicate code Switch statements Long method Large class Long parameter list Temporary field Etc. Slide    “ If it stinks, change it.”
How to remove a long if-then-else-if Slide    class Shape { } class Line extends Shape { Point startPoint; Point endPoint; }  class Rectangle extends Shape { Point lowerLeftCorner; Point upperRightCorner; }  class Circle extends Shape { Point center; int radius; } class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { if (shapes[i] instanceof Line) { Line line = (Line)shapes[i]; graphics.drawLine(line.getStartPoint(),line.getEndPoint()); } else if (shapes[i] instanceof Rectangle) { Rectangle rect = (Rectangle)shapes[i]; graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); } else if (shapes[i] instanceof Circle) { Circle circle = (Circle)shapes[i]; graphics.drawCircle(circle.getCenter(), circle.getRadius()); } } } }
How to remove a long if-then-else-if Slide    class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { if (shapes[i] instanceof Line) { draw the line } else if (shapes[i] instanceof Rectangle) { draw the rectangle } else if (shapes[i] instanceof Circle) { draw the circle } } } } To remove long if-else conditions, try to make the code identical in each of the if else blocks class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { if (shapes[i] instanceof Line) { draw the shape } else if (shapes[i] instanceof Rectangle) { draw the shape } else if (shapes[i] instanceof Circle) { draw the shape } } } } class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { draw the shape } } } class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { shapes[i].draw(graphics); } } }
How to remove a long if-then-else-if Slide    abstract  class Shape { abstract void draw(Graphics graphics); } class Line extends Shape { Point startPoint; Point endPoint; void draw(Graphics graphics) { graphics.drawLine(getStartPoint(), getEndPoint()); } } class Rectangle extends Shape { Point lowerLeftCorner; Point upperRightCorner; void draw(Graphics graphics) { graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); } }  class Circle extends Shape {  Point center; int radius; void draw(Graphics graphics) { graphics.drawCircle(getCenter(), getRadius()); } } interface  Shape { abstract void draw(Graphics graphics); } class Line  implements  Shape { … } class Rectangle  implements   Shape { … }  class Circle  implements   Shape { … }
Improved Code Slide    interface  Shape { void  draw(Graphics graphics); } class  Line  implements  Shape { Point startPoint; Point endPoint; void  draw(Graphics graphics) { graphics.drawLine(getStartPoint(), getEndPoint()); } } class  Rectangle  implements  Shape { Point lowerLeftCorner; Point upperRightCorner; void  draw(Graphics graphics) { graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); } } class  Circle  implements  Shape { Point center; int  radius; void  draw(Graphics graphics) { graphics.drawCircle(getCenter(), getRadius()); } } class  CADApp { void  drawShapes(Graphics graphics, Shape shapes[]) { for  ( int  i = 0; i < shapes.length; i++) { shapes[i].draw(graphics); } } } If we need to support one more shape (e.g., triangle), none of classes needs to change. All it takes is to create a new Triangle class.
Another Example  There are three types of users: regular users,administrators and guests.  Regular users must change their password once every 90 days (or sooner).  Administrators must change their password once every 30 days.  Guests don't need to change passwords. Only regular users and administrators can print reports. Slide
Original code Slide    class UserAccount { final static int USERTYPE_NORMAL = 0; final static int USERTYPE_ADMIN = 1; final static int USERTYPE_GUEST = 2; int userType; String id; String name; String password; Date dateOfLastPasswdChange; public boolean checkPassword(String password) { ... } } class InventoryApp { int getPasswordMaxAgeInDays(UserAccount account) { switch (account.getType()) { case UserAccount.USERTYPE_NORMAL: return 90; case UserAccount.USERTYPE_ADMIN: return 30; case UserAccount.USERTYPE_GUEST: return Integer.MAX_VALUE; } } void printReport(UserAccount currentUser) { boolean canPrint; switch (currentUser.getType()) { case UserAccount.USERTYPE_NORMAL: canPrint = true; break; case UserAccount.USERTYPE_ADMIN: canPrint = true; break; case UserAccount.USERTYPE_GUEST: canPrint = false; } if (!canPrint) { throw new SecurityException(&quot;You have no right&quot;); } //print the report. } } Issue is same as long if-then-else!
Use subclass to represent type code value Slide    abstract  class UserAccount { String id; String name; String password; Date dateOfLastPasswdChange; abstract int getPasswordMaxAgeInDays(); abstract boolean canPrintReport(); }  class NormalUserAccount extends UserAccount { int getPasswordMaxAgeInDays() { return 90; } boolean canPrintReport() { return true; } }  class AdminUserAccount extends UserAccount { int getPasswordMaxAgeInDays() { return 30; } boolean canPrintReport() { return true; } } class GuestUserAccount extends UserAccount { int getPasswordMaxAgeInDays() { return Integer.MAX_VALUE; } boolean canPrintReport() { return false; } } Subclasses differ in values they return.
Use an object to represent a type code value Slide    class UserAccount { UserType userType; String id; String name; String password; Date dateOfLastPasswdChange; UserType getType() { return userType; } } class UserType { int passwordMaxAgeInDays; boolean allowedToPrintReport; UserType(int passwordMaxAgeInDays, boolean allowedToPrintReport) { this.passwordMaxAgeInDays = passwordMaxAgeInDays; this.allowedToPrintReport = allowedToPrintReport; }  int getPasswordMaxAgeInDays() { return passwordMaxAgeInDays; } boolean canPrintReport() { return allowedToPrintReport; } static UserType normalUserType =  new UserType(90, true); static UserType adminUserType = new UserType(30, true); static UserType guestUserType = new UserType(Integer.MAX_VALUE, false); } int getPasswordMaxAgeInDays(UserAccount account) { return account.getType().getPasswordMaxAgeInDays(); } void printReport(UserAccount currentUser) { boolean canPrint; canPrint = currentUser.getType().canPrintReport(); if (!canPrint) { throw new SecurityException(&quot;You have no right&quot;); } //print the report. }
Better object orientation Additional Reference:  http://www.objectmentor.com/resources/publishedArticles.html
Apply the basic concepts Slide    Goal of OOAD: Identify the classes and relations between them for a given problem. Read the problem statement carefully and identify: Nouns (Classes) Verbs (Behavior) Actors (Users)  Identify relationships between classes Is-A  (Generalization / Inheritance) Has-A (Composition)  Uses (Dependency)
Example Slide    A basket contains oranges and apples. Basket Apple Orange Fruits have cost Basket Apple Orange Fruit 1 * * int Price; 1 * Generalize to accommodate new requirements.
Example continued… Slide    A user has password.  Password can be encrypted and decrypted. User Password public String encrypt(); public String decrypt(); 1 1 String userid; Password is encrypted using a encryption service. User Password public String encrypt(); public String decrypt(); 1 1 String userid; EncryptionService public String encrypt(String); public String decrypt(String);
Single responsibility principle Slide    Class should have one and only one reason to change. Rectangle public draw() public area() Two responsibilities: Mathematical model of the geometry of rectangle Render rectangle to a graphical user interface. Rectangle Point topLeftCorner Point bottomRightCorner G eometric Rectangle public  area()
Law of demeter Principle of least knowledge Slide    Module should not know internal details of objects it manipulates. A method  M  of an object  O  may only invoke the methods of the following kinds of objects: O  itself  M' s parameters  any objects created/instantiated within  M   O' s instance variables Class PaperBoy { void collectPaymetents() { float payment = 2.0; float fundsCollected = 0.0; for (Customer customer : customerList) { float moneyInWallet  =  customer.getWallet().getMoney(); if (moneyInWallet >= payment) { customer.getWallet.setMoney(moneyInWallet – payment); fundsCollected += payment; } } } } Class PaperBoy { void collectPaymetents() { float payment = 2.0; float fundsCollected = 0.0; for (Customer customer : customerList) { try { fundsCollected += customer.makePayment(payment); } catch (NotEnoughMoneyComeLaterException e) { } } }
Make good use of polymorphism Slide    In object oriented languages, power of polymorphism comes from  Liskov’s substitution principle . “ A subclass can be used as an argument where a base class is expected” Class Mechanic { public void repair (Car car) { } } class HyundaiCar  implements Car { } class MarutiCar  implements Car { } class HyundaiSantro extends HyundaiCar { } HyundaiCar faultyHyundai = new HyundaiCar(); mechanic.repair (faultyHyunai); MarutiCar faultyMaruti = new MarutiCar(); mechanic.repair(faultyMaruti);
Program to interface, and put polymorphism to better use Slide    Class Driver { public void drive (Car car) { } public void drive (Truck truck) { } } Class Driver { public void drive (Vehicle vehicle) { } }
Open-closed principle Slide    if ( isGoingToMovie() ) { Vehicle vehicle = new Car(); driver.drive (vehicle ) } else ( ifRelocatingToNewHome () ) { Vehicle vehicle = new Truck(); driver.drive (vehicle ); } Vehicle vehicle = getVehicle(conditions); driver.drive (vehicle ); Class should be  open  for extension, but  closed  for modification.
Writing code that tests code
Problem You can order a cup of coffee. A cup of coffee costs Rs. 10. You can add many ingredients to it, say, chocolate chips, extra cream, Ice cream, etc. Each ingredients has its own cost. Slide
Traditional testing public static void main() { Coffee c = new Coffee(); c.add(new ExtraCream()); c.add(new ChocolateChip()); long cost = c.getCost(); system.out.println(“Pay : Rs.” + cost); } Slide    Issue:  Requires a human to confirm the value printed on console.
JUnit style of testing public class coffeeTest extends TestCase { public testCompuatationOfCoffeeCost() { Coffee c = new Coffee(); c.add(new ExtraCream()); c.add(new ChocolateChip()); long cost = c.getCost(); assertTrue(cost > 0); assetEquals(cost, Coffee.COST + ExtraCream.COST +  ChocolateChip.COST); } } Slide    Instant feedback (GUI ):  Green Bar indicates success, a red bar indicates failure.
Test Driven Development Cycle Add a test Run all tests and see the new one fail. Write some code. Run the automated tests and see them succeed. Refactor code Repeat http://en.wikipedia.org/wiki/Test-driven_development Slide
Parting thoughts
Don’t live with broken windows The pragmatic programmer by Andrew Hunt, David Thomas Slide    http://en.wikipedia.org/wiki/Fixing_Broken_Windows   &quot;Consider a building with a few broken windows. If the windows are not repaired, the tendency is for vandals to break a few more windows. Eventually, they may even break into the building, and if it's unoccupied, perhaps become squatters or light fires inside.  Or consider a sidewalk. Some litter accumulates. Soon, more litter accumulates. Eventually, people even start leaving bags of trash from take-out restaurants there or breaking into cars.&quot;  Psychology or culture at work is one of the factors that contribute to bad code. So, try to clean up every time you see a messy code. Broken Windows = Bad Design, Wrong decisions, Poor code
Knowledge Portfolio The pragmatic programmer by Andrew Hunt, David Thomas Slide    An investment in knowledge always pays the best interest Benjamin Franklin, One of the Founding Fathers of the United States of America Invest regularly Diversify Manage risk Buy low, sell high Review and re-balance Learn at least one new language every year. Read a technical book each quarter. Read non-technical books too. Take classes. Participate in local user groups. Experiment with different environments. Stay current. Get wired. Building investment portfolio Building knowledge portfolio
Write programs for fellow humans Slide    Any damn fool can write code that a computer can understand, the trick is to write code that humans can understand. Martin Fowler, Author of book “Refactoring” http://martinfowler.com/distributedComputing/refactoring.pdf
Books for someone aspiring to become a great (Java) programmer Slide
Books for someone aspiring to become a great (Java) programmer Slide    Free PDF available online ( http://www.agileskills.org/download.html.en  ) Some examples in these slides are from this book Some examples in these slides are from this book
Find a role model and follow them …read about what they are working on, what they consider exciting. Slide    Rod Johnson, Founder of Spring Framework  Douglas Crockford, Yahoo JavaScript Architect Yukihiro “Matz” Matsumoto , Creator of “Ruby” language  David Heinemeier Hansson Creator of “Ruby on RAILS” framework Gavin King Creation of “Hibernate” Framework
Copyright notice For more information see http://creativecommons.org/licenses/by/3.0/
Thanks
Ad

More Related Content

What's hot (20)

Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Unity Technologies
 
Clean code
Clean codeClean code
Clean code
Đàm Đàm
 
Docker로 서버 개발 편하게 하기
Docker로 서버 개발 편하게 하기Docker로 서버 개발 편하게 하기
Docker로 서버 개발 편하게 하기
Dronix
 
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
Authenticating Angular Apps with JWT
Authenticating Angular Apps with JWTAuthenticating Angular Apps with JWT
Authenticating Angular Apps with JWT
Jennifer Estrada
 
絶対落ちないアプリの作り方
絶対落ちないアプリの作り方絶対落ちないアプリの作り方
絶対落ちないアプリの作り方
Fumihiko Shiroyama
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
Allan Huang
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtleThirteen ways of looking at a turtle
Thirteen ways of looking at a turtle
Scott Wlaschin
 
Bowling Game Kata C#
Bowling Game Kata C#Bowling Game Kata C#
Bowling Game Kata C#
Dan Stewart
 
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureCoder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Thomas Pierrain
 
Java 8 - interfaces
Java 8 - interfacesJava 8 - interfaces
Java 8 - interfaces
Franck SIMON
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
Celery
CeleryCelery
Celery
Fatih Erikli
 
Lezione 11: Accesso ai RESTful Web Services in Java
Lezione 11: Accesso ai RESTful Web Services in JavaLezione 11: Accesso ai RESTful Web Services in Java
Lezione 11: Accesso ai RESTful Web Services in Java
Andrea Della Corte
 
Clean code
Clean codeClean code
Clean code
Mahmoud Zizo
 
MyBatis
MyBatisMyBatis
MyBatis
Roman Dovgan
 
Collection
CollectionCollection
Collection
Hum Chivorn
 
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Unity Technologies
 
Docker로 서버 개발 편하게 하기
Docker로 서버 개발 편하게 하기Docker로 서버 개발 편하게 하기
Docker로 서버 개발 편하게 하기
Dronix
 
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
Authenticating Angular Apps with JWT
Authenticating Angular Apps with JWTAuthenticating Angular Apps with JWT
Authenticating Angular Apps with JWT
Jennifer Estrada
 
絶対落ちないアプリの作り方
絶対落ちないアプリの作り方絶対落ちないアプリの作り方
絶対落ちないアプリの作り方
Fumihiko Shiroyama
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
Allan Huang
 
Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtleThirteen ways of looking at a turtle
Thirteen ways of looking at a turtle
Scott Wlaschin
 
Bowling Game Kata C#
Bowling Game Kata C#Bowling Game Kata C#
Bowling Game Kata C#
Dan Stewart
 
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architectureCoder sans peur du changement avec la meme pas mal hexagonal architecture
Coder sans peur du changement avec la meme pas mal hexagonal architecture
Thomas Pierrain
 
Java 8 - interfaces
Java 8 - interfacesJava 8 - interfaces
Java 8 - interfaces
Franck SIMON
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
Lezione 11: Accesso ai RESTful Web Services in Java
Lezione 11: Accesso ai RESTful Web Services in JavaLezione 11: Accesso ai RESTful Web Services in Java
Lezione 11: Accesso ai RESTful Web Services in Java
Andrea Della Corte
 

Similar to Practices For Becoming A Better Programmer (20)

Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
Alfonso Peletier
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
Clean code
Clean codeClean code
Clean code
Arturo Herrero
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
New C# features
New C# featuresNew C# features
New C# features
Alexej Sommer
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.ppt
psundarau
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
Oluwaleke Fakorede
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
SDFG5
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
Almamoon
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
mothertheressa
 
Introduction-to-Csharp programacion orientada a objetos
Introduction-to-Csharp programacion orientada a objetosIntroduction-to-Csharp programacion orientada a objetos
Introduction-to-Csharp programacion orientada a objetos
KilbertChusiHuamani
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
Alfonso Peletier
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.ppt
psundarau
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
Oluwaleke Fakorede
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
SDFG5
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
Almamoon
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
mothertheressa
 
Introduction-to-Csharp programacion orientada a objetos
Introduction-to-Csharp programacion orientada a objetosIntroduction-to-Csharp programacion orientada a objetos
Introduction-to-Csharp programacion orientada a objetos
KilbertChusiHuamani
 
Ad

Recently uploaded (20)

Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Ad

Practices For Becoming A Better Programmer

  • 1. Practices for becoming a better programmer Srikanth P Shreenivas [email_address] http://www.srikanthps.com
  • 2. Joys of the craft The Mythical Man-Month, Frederick P. Brooks. Jr Slide Why is programming fun? What delights may its practitioner expect as reward? First is the sheer joy of making things. Second is pleasure of making things that are useful to other people. Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts and watching them work in subtle cycles, playing out the consequences of principles built in the beginning. The programmed computer has all the effects of a pinball machine or jukebox mechanism, carried to the ultimate. Fourth is the joy of always learning, which springs from non-repeating nature of the task. Finally, there is the delight of working in such a tractable medium. The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from the air, creating by exertion of imagination. Programming gratifies creative longings built deep within us
  • 3. Values of Programming Implementation Patterns, Kent Beck Communication Simplicity Flexibility Slide
  • 5. Use Meaningful Names int d; //elapsed time in days int elapsedTimeInDays; int fileAgeInDays; int daysSinceLastModification; Intention-revealing names
  • 6. Use Meaningful Names Set hobbyList; Set hobbies; Avoid Disinformation
  • 7. Use Meaningful Names Slide Public void copy (String s1, String s2) Make meaningful distinctions Public void copy(String destination, String source)
  • 8. Meaningful names Slide class DtaRcrd102 Use pronounceable names class Customer
  • 9. Meaningful names Slide int r = 0; for (int j = 0; j < 5; j++) { r = r + j * 8; } Use searchable names int workingDaysInWeek = 5; int workingHoursPerDay = 8; int hoursInWeek = 0; for (int dayIndex = 0; dayIndex < workingDaysInWeek ; dayIndex ++) { hoursInWeek = hoursInWeek + dayIndex * workingHoursPerDay; }
  • 10. Meaningful names Slide Class names Should be nouns or noun phrases. Examples: Car, Account, DataRetrievalService, AddressParser
  • 11. Meaningful names Slide Method names Should be verb or verbPhrases Examples: parseData , deletePage , save Methods that return boolean values should sound like question. Example: isAuthenticated , hasNoErrors , isEmpty if (user.isAuthenticated()) { String data = parseData(input); if (hasErrors(data)) { throw ErrorInDataException(); } }
  • 12. Meaningful names Slide Pick one word per concept Don’t mix words like “fetch”, “get”, “retrieve”. Be consistent.
  • 13. Meaningful names Slide Don’t use same word for two different concepts Example: Don’t use “add”, where “insert” makes sense.
  • 14. Meaningful names Slide Use names from problem/solution domain Prefer “InvoiceGenerator” to “DataExtractor”
  • 15. You don’t need comments to communicate
  • 16. Turning Comments into Code Slide class InchToPointConvertor { //convert the quantity in inches to points. static float parseInch(float inch) { return inch * 72; //one inch contains 72 points. } } class InchToPointConvertor { final static int POINTS_PER_INCH=72; static float convertToPoints (float inch) { return inch * POINTS_PER_INCH ; } }
  • 17. Turning Comments into Code Slide class Account { ... //check if the password is complex enough, i.e., //contains letter and digit/symbol. boolean isComplexPassword(String password) { //found a digit or symbol? boolean dg_sym_found=false; //found a letter? boolean letter_found=false; for(int i=0; i<password.length(); i++){ char c=password.charAt(i); if(Character.isLowerCase(c)||Character.isUpperCase(c)) letter_found=true; else dg_sym_found=true; } return (letter_found) && (dg_sym_found); } } class Account { ... boolean isComplexPassword(String password){ return containsLetter(password) && (containsDigit(password) || containsSymbol(password)); } boolean containsLetter(String password) { ... } boolean containsDigit(String password) { ... } boolean containsSymbol(String password) { ... } }
  • 18. Turning comments into code Slide Are we writing comments because our code is unclear? Will you keep the comments up-to-date whenever code is updated? What’s wrong with Comments? Nothing wrong with comments. They are not bad. Why avoid comments? Unclear code with outdated comments. You don’t want: Try to convert comments into code that bring out the intent of the code, and use comments sparingly.
  • 20. Functions Slide Write small functions … .and try to write even smaller functions. Aim for functions that are not longer than 4 to 5 lines. Split the big methods in smaller methods (Extract method) Use intention-revealing names for methods. Public List<Person> filterList(List<Person> input) { List filteredList = new ArrayList(); for (Person p : input) { if (p.getDateOfBirth().getYear() > 1997) { filteredList.add(p); } if (p.getAddress().getCity().equals(“Bangalore”)) { filteredList.add(p); } } return filterdList; } Public List<Person> selectTeenAgersFromBangalore (List<Person> input) { List filteredList = new ArrayList(); for (Person p : input) { if (isTeenAger(p) || isFromBangalore(p)) { filteredList.add(p); } } return filterdList; }
  • 21. Functions Slide Do one thing in a function (Single responsibility) Public List<Person> filterList(List<Person> input) { List filteredList = new ArrayList(); for (Person p : input) { if (p.getDateOfBirth().getYear() > 1997) { filteredList.add(p); } if (p.getAddress().getCity().equals(“Bangalore”)) { filteredList.add(p); } } return filterdList; } Public List<Person> selectTeenAgersFromBangalore (List<Person> input) { List filteredList = new ArrayList(); for (Person p : input) { if (isTeenAger(p) && isFromBangalore(p)) { filteredList.add(p); } } return filterdList; } Filtering logic moved out
  • 22. Functions Slide All statements should be at same level of abstraction. Employee employee = employeeRepository.get(“m100XXXX”); employee.getSalaryDetails().setBasic( employee.getSalaryDetails().getBasic () * 1.10); employeeRepository.save(employee); Employee employee = employeeRepository.get(“m100XXXX”); raiseSalary(empoyee, “10%”); employeeRepository.save(employee); Functions should be read like top-down narrative. Every function should be followed by functions of next level of abstraction.
  • 23. Functions Slide Have no side effects. Public boolean checkPassword(String userName, String password) { User user = userService.getUser(userName); if (user.password.equals(password)) { Session.initalize(); return true; } return false; }
  • 24. Functions Slide Command query separation. Public boolean set(String attribute, String value) { … . } if (set(“color”, “red”)) { … . } if (attributeExists(“color”)) { }
  • 25. Functions Slide Prefer exceptions to return codes. if (deletePage(“myPage”) == E_OK) { … . } else { logger.log (“delete failed”); } try { deletePage(“myPage”); } catch (PageCannotBeDeletedException p) { … } catch (PageDoesNotExistException e) { … }
  • 26. Functions Slide Format your code. Use IDE supported code formatting tools. Configure IDE to support team-specific alignment rules. opening brace “{“ should be on the same line as the statement. use space after keywords if (someCondtion) use space to separate method arguments doSomething( param1, param2, param3 ); indent each scope by 4 spaces Ctrl+Shift+F in Eclipse
  • 27. DRY – Don’t repeat yourself
  • 28. Code which started well… Slide public class BookRental { String id; String customerName; ... } public class BookRentals { private Vector rentals; public String getCustomerName(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { return rental.getCustomerName(); } } throw new RentalNotFoundException(); } } public class RentalNotFoundException extends Exception { ... } Book Rentals Applications: Maintains a list of books rented to customers. New requirement: Add a method to delete rental given its id.
  • 29. Code updated for new requirement… Slide public class BookRental { String id; String customerName; ... } public class BookRentals { private Vector rentals; public String getCustomerName(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { return rental.getCustomerName(); } } throw new RentalNotFoundException(); } public void deleteRental(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { rentals.remove(i); return; } } throw new RentalNotFoundException(); } } public class RentalNotFoundException extends Exception { ... } Duplicate Code
  • 30. Duplicate code should be avoided Slide What’s wrong with duplicate code? If there is a bug in the code or code requires changes, then, one has to change it at multiple places. This is error-prone. public class BookRentals { private Vector rentals; public String getCustomerName(String rentalId) { int rentalIdx = getRentalIdxById(rentalId); return ((BookRental) rentals.elementAt(rentalIdx)).getCustomerName(); } public void deleteRental(String rentalId) { rentals.remove(getRentalIdxById(rentalId)); } private int getRentalIdxById(String rentalId) { for (int i = 0; i < rentals.size(); i++) { BookRental rental = (BookRental) rentals.elementAt(i); if (rental.getId().equals(rentalId)) { return i; } } throw new RentalNotFoundException(); } }
  • 31. Removing duplicate code Slide Point out and remove duplicate code class Organization { String id; String eName; //English name String cName; //Chinese name String telCountryCode; String telAreaCode; String telLocalNumber; String faxCountryCode; String faxAreaCode; String faxLocalNumber; String contactPersonEFirstName; //First name and last name in English String contactPersonELastName; String contactPersonCFirstName; //First name and last name in Chinese String contactPersonCLastName; String contactPersonTelCountryCode; String contactPersonTelAreaCode; String contactPersonTelNumber; String contactPersonFaxCountryCode; String contactPersonFaxAreaCode; String contactPersonFaxLocalNumber; String contactPersonMobileCountryCode; String contactPersonMobileAreaCode; String contactPersonMobileLocalNumber; ... } Organization’s and Person’s Telephone number format is same Organization’s and Person’s names are stored in English and Chinese.
  • 32. Removing duplicate code Slide Duplicate code removed class Organization { String id; String eName; String cName; TelNo telNo; TelNo faxNo; ContactPerson contactPerson; ... } class ContactPerson{ String eFirstName; String eLastName; String cFirstName; String cLastName; TelNo tel; TelNo fax; TelNo mobile; } class TelNo { String countryCode; String areaCode; String localNumber; } class ContactPerson { FullName eFullName; FullName cFullName; TelNo tel; TelNo fax; TelNo mobile; } class FullName { String firstName; String lastName; }
  • 34. Code Smells Duplicate code Switch statements Long method Large class Long parameter list Temporary field Etc. Slide “ If it stinks, change it.”
  • 35. How to remove a long if-then-else-if Slide class Shape { } class Line extends Shape { Point startPoint; Point endPoint; } class Rectangle extends Shape { Point lowerLeftCorner; Point upperRightCorner; } class Circle extends Shape { Point center; int radius; } class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { if (shapes[i] instanceof Line) { Line line = (Line)shapes[i]; graphics.drawLine(line.getStartPoint(),line.getEndPoint()); } else if (shapes[i] instanceof Rectangle) { Rectangle rect = (Rectangle)shapes[i]; graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); } else if (shapes[i] instanceof Circle) { Circle circle = (Circle)shapes[i]; graphics.drawCircle(circle.getCenter(), circle.getRadius()); } } } }
  • 36. How to remove a long if-then-else-if Slide class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { if (shapes[i] instanceof Line) { draw the line } else if (shapes[i] instanceof Rectangle) { draw the rectangle } else if (shapes[i] instanceof Circle) { draw the circle } } } } To remove long if-else conditions, try to make the code identical in each of the if else blocks class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { if (shapes[i] instanceof Line) { draw the shape } else if (shapes[i] instanceof Rectangle) { draw the shape } else if (shapes[i] instanceof Circle) { draw the shape } } } } class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { draw the shape } } } class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for (int i = 0; i < shapes.length; i++) { shapes[i].draw(graphics); } } }
  • 37. How to remove a long if-then-else-if Slide abstract class Shape { abstract void draw(Graphics graphics); } class Line extends Shape { Point startPoint; Point endPoint; void draw(Graphics graphics) { graphics.drawLine(getStartPoint(), getEndPoint()); } } class Rectangle extends Shape { Point lowerLeftCorner; Point upperRightCorner; void draw(Graphics graphics) { graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); } } class Circle extends Shape { Point center; int radius; void draw(Graphics graphics) { graphics.drawCircle(getCenter(), getRadius()); } } interface Shape { abstract void draw(Graphics graphics); } class Line implements Shape { … } class Rectangle implements Shape { … } class Circle implements Shape { … }
  • 38. Improved Code Slide interface Shape { void draw(Graphics graphics); } class Line implements Shape { Point startPoint; Point endPoint; void draw(Graphics graphics) { graphics.drawLine(getStartPoint(), getEndPoint()); } } class Rectangle implements Shape { Point lowerLeftCorner; Point upperRightCorner; void draw(Graphics graphics) { graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); graphics.drawLine(...); } } class Circle implements Shape { Point center; int radius; void draw(Graphics graphics) { graphics.drawCircle(getCenter(), getRadius()); } } class CADApp { void drawShapes(Graphics graphics, Shape shapes[]) { for ( int i = 0; i < shapes.length; i++) { shapes[i].draw(graphics); } } } If we need to support one more shape (e.g., triangle), none of classes needs to change. All it takes is to create a new Triangle class.
  • 39. Another Example There are three types of users: regular users,administrators and guests. Regular users must change their password once every 90 days (or sooner). Administrators must change their password once every 30 days. Guests don't need to change passwords. Only regular users and administrators can print reports. Slide
  • 40. Original code Slide class UserAccount { final static int USERTYPE_NORMAL = 0; final static int USERTYPE_ADMIN = 1; final static int USERTYPE_GUEST = 2; int userType; String id; String name; String password; Date dateOfLastPasswdChange; public boolean checkPassword(String password) { ... } } class InventoryApp { int getPasswordMaxAgeInDays(UserAccount account) { switch (account.getType()) { case UserAccount.USERTYPE_NORMAL: return 90; case UserAccount.USERTYPE_ADMIN: return 30; case UserAccount.USERTYPE_GUEST: return Integer.MAX_VALUE; } } void printReport(UserAccount currentUser) { boolean canPrint; switch (currentUser.getType()) { case UserAccount.USERTYPE_NORMAL: canPrint = true; break; case UserAccount.USERTYPE_ADMIN: canPrint = true; break; case UserAccount.USERTYPE_GUEST: canPrint = false; } if (!canPrint) { throw new SecurityException(&quot;You have no right&quot;); } //print the report. } } Issue is same as long if-then-else!
  • 41. Use subclass to represent type code value Slide abstract class UserAccount { String id; String name; String password; Date dateOfLastPasswdChange; abstract int getPasswordMaxAgeInDays(); abstract boolean canPrintReport(); } class NormalUserAccount extends UserAccount { int getPasswordMaxAgeInDays() { return 90; } boolean canPrintReport() { return true; } } class AdminUserAccount extends UserAccount { int getPasswordMaxAgeInDays() { return 30; } boolean canPrintReport() { return true; } } class GuestUserAccount extends UserAccount { int getPasswordMaxAgeInDays() { return Integer.MAX_VALUE; } boolean canPrintReport() { return false; } } Subclasses differ in values they return.
  • 42. Use an object to represent a type code value Slide class UserAccount { UserType userType; String id; String name; String password; Date dateOfLastPasswdChange; UserType getType() { return userType; } } class UserType { int passwordMaxAgeInDays; boolean allowedToPrintReport; UserType(int passwordMaxAgeInDays, boolean allowedToPrintReport) { this.passwordMaxAgeInDays = passwordMaxAgeInDays; this.allowedToPrintReport = allowedToPrintReport; } int getPasswordMaxAgeInDays() { return passwordMaxAgeInDays; } boolean canPrintReport() { return allowedToPrintReport; } static UserType normalUserType = new UserType(90, true); static UserType adminUserType = new UserType(30, true); static UserType guestUserType = new UserType(Integer.MAX_VALUE, false); } int getPasswordMaxAgeInDays(UserAccount account) { return account.getType().getPasswordMaxAgeInDays(); } void printReport(UserAccount currentUser) { boolean canPrint; canPrint = currentUser.getType().canPrintReport(); if (!canPrint) { throw new SecurityException(&quot;You have no right&quot;); } //print the report. }
  • 43. Better object orientation Additional Reference: http://www.objectmentor.com/resources/publishedArticles.html
  • 44. Apply the basic concepts Slide Goal of OOAD: Identify the classes and relations between them for a given problem. Read the problem statement carefully and identify: Nouns (Classes) Verbs (Behavior) Actors (Users) Identify relationships between classes Is-A (Generalization / Inheritance) Has-A (Composition) Uses (Dependency)
  • 45. Example Slide A basket contains oranges and apples. Basket Apple Orange Fruits have cost Basket Apple Orange Fruit 1 * * int Price; 1 * Generalize to accommodate new requirements.
  • 46. Example continued… Slide A user has password. Password can be encrypted and decrypted. User Password public String encrypt(); public String decrypt(); 1 1 String userid; Password is encrypted using a encryption service. User Password public String encrypt(); public String decrypt(); 1 1 String userid; EncryptionService public String encrypt(String); public String decrypt(String);
  • 47. Single responsibility principle Slide Class should have one and only one reason to change. Rectangle public draw() public area() Two responsibilities: Mathematical model of the geometry of rectangle Render rectangle to a graphical user interface. Rectangle Point topLeftCorner Point bottomRightCorner G eometric Rectangle public area()
  • 48. Law of demeter Principle of least knowledge Slide Module should not know internal details of objects it manipulates. A method M of an object O may only invoke the methods of the following kinds of objects: O itself M' s parameters any objects created/instantiated within M O' s instance variables Class PaperBoy { void collectPaymetents() { float payment = 2.0; float fundsCollected = 0.0; for (Customer customer : customerList) { float moneyInWallet = customer.getWallet().getMoney(); if (moneyInWallet >= payment) { customer.getWallet.setMoney(moneyInWallet – payment); fundsCollected += payment; } } } } Class PaperBoy { void collectPaymetents() { float payment = 2.0; float fundsCollected = 0.0; for (Customer customer : customerList) { try { fundsCollected += customer.makePayment(payment); } catch (NotEnoughMoneyComeLaterException e) { } } }
  • 49. Make good use of polymorphism Slide In object oriented languages, power of polymorphism comes from Liskov’s substitution principle . “ A subclass can be used as an argument where a base class is expected” Class Mechanic { public void repair (Car car) { } } class HyundaiCar implements Car { } class MarutiCar implements Car { } class HyundaiSantro extends HyundaiCar { } HyundaiCar faultyHyundai = new HyundaiCar(); mechanic.repair (faultyHyunai); MarutiCar faultyMaruti = new MarutiCar(); mechanic.repair(faultyMaruti);
  • 50. Program to interface, and put polymorphism to better use Slide Class Driver { public void drive (Car car) { } public void drive (Truck truck) { } } Class Driver { public void drive (Vehicle vehicle) { } }
  • 51. Open-closed principle Slide if ( isGoingToMovie() ) { Vehicle vehicle = new Car(); driver.drive (vehicle ) } else ( ifRelocatingToNewHome () ) { Vehicle vehicle = new Truck(); driver.drive (vehicle ); } Vehicle vehicle = getVehicle(conditions); driver.drive (vehicle ); Class should be open for extension, but closed for modification.
  • 52. Writing code that tests code
  • 53. Problem You can order a cup of coffee. A cup of coffee costs Rs. 10. You can add many ingredients to it, say, chocolate chips, extra cream, Ice cream, etc. Each ingredients has its own cost. Slide
  • 54. Traditional testing public static void main() { Coffee c = new Coffee(); c.add(new ExtraCream()); c.add(new ChocolateChip()); long cost = c.getCost(); system.out.println(“Pay : Rs.” + cost); } Slide Issue: Requires a human to confirm the value printed on console.
  • 55. JUnit style of testing public class coffeeTest extends TestCase { public testCompuatationOfCoffeeCost() { Coffee c = new Coffee(); c.add(new ExtraCream()); c.add(new ChocolateChip()); long cost = c.getCost(); assertTrue(cost > 0); assetEquals(cost, Coffee.COST + ExtraCream.COST + ChocolateChip.COST); } } Slide Instant feedback (GUI ): Green Bar indicates success, a red bar indicates failure.
  • 56. Test Driven Development Cycle Add a test Run all tests and see the new one fail. Write some code. Run the automated tests and see them succeed. Refactor code Repeat http://en.wikipedia.org/wiki/Test-driven_development Slide
  • 58. Don’t live with broken windows The pragmatic programmer by Andrew Hunt, David Thomas Slide http://en.wikipedia.org/wiki/Fixing_Broken_Windows &quot;Consider a building with a few broken windows. If the windows are not repaired, the tendency is for vandals to break a few more windows. Eventually, they may even break into the building, and if it's unoccupied, perhaps become squatters or light fires inside. Or consider a sidewalk. Some litter accumulates. Soon, more litter accumulates. Eventually, people even start leaving bags of trash from take-out restaurants there or breaking into cars.&quot; Psychology or culture at work is one of the factors that contribute to bad code. So, try to clean up every time you see a messy code. Broken Windows = Bad Design, Wrong decisions, Poor code
  • 59. Knowledge Portfolio The pragmatic programmer by Andrew Hunt, David Thomas Slide An investment in knowledge always pays the best interest Benjamin Franklin, One of the Founding Fathers of the United States of America Invest regularly Diversify Manage risk Buy low, sell high Review and re-balance Learn at least one new language every year. Read a technical book each quarter. Read non-technical books too. Take classes. Participate in local user groups. Experiment with different environments. Stay current. Get wired. Building investment portfolio Building knowledge portfolio
  • 60. Write programs for fellow humans Slide Any damn fool can write code that a computer can understand, the trick is to write code that humans can understand. Martin Fowler, Author of book “Refactoring” http://martinfowler.com/distributedComputing/refactoring.pdf
  • 61. Books for someone aspiring to become a great (Java) programmer Slide
  • 62. Books for someone aspiring to become a great (Java) programmer Slide Free PDF available online ( http://www.agileskills.org/download.html.en ) Some examples in these slides are from this book Some examples in these slides are from this book
  • 63. Find a role model and follow them …read about what they are working on, what they consider exciting. Slide Rod Johnson, Founder of Spring Framework Douglas Crockford, Yahoo JavaScript Architect Yukihiro “Matz” Matsumoto , Creator of “Ruby” language David Heinemeier Hansson Creator of “Ruby on RAILS” framework Gavin King Creation of “Hibernate” Framework
  • 64. Copyright notice For more information see http://creativecommons.org/licenses/by/3.0/