SlideShare a Scribd company logo
1 of 65
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 ,[object Object],[object Object],[object Object],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    ,[object Object],[object Object],What’s wrong with Comments? ,[object Object],Why avoid comments? ,[object Object],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. ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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  ,[object Object],[object Object],[object Object],[object Object],[object Object],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. ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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() ,[object Object],[object Object],[object Object],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. ,[object Object],[object Object],[object Object],[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],Slide
Traditional testing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Slide    Issue:  Requires a human to confirm the value printed on console.
JUnit style of testing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Slide    Instant feedback (GUI ):  Green Bar indicates success, a red bar indicates failure.
Test Driven Development Cycle ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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    ,[object Object],[object Object],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

More Related Content

What's hot

20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIAjit Nayak
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Monadic Java
Monadic JavaMonadic Java
Monadic JavaCodemotion
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2Aadil Ansari
 
Beauty and/or elegance in functional programming
Beauty and/or elegance in functional programmingBeauty and/or elegance in functional programming
Beauty and/or elegance in functional programmingSilviaP24
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Scott Wlaschin
 
Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Scott Wlaschin
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismJussi Pohjolainen
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsRasan Samarasinghe
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 

What's hot (20)

20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
 
Beauty and/or elegance in functional programming
Beauty and/or elegance in functional programmingBeauty and/or elegance in functional programming
Beauty and/or elegance in functional programming
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)
 
Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Clean code
Clean codeClean code
Clean code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 

Similar to Practices for becoming a better programmer

Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant 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 LabsAlfonso Peletier
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of cTushar B Kute
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
New C# features
New C# featuresNew C# features
New C# featuresAlexej Sommer
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.pptpsundarau
 
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
 
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 FunctionsOluwaleke Fakorede
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
Clean Code
Clean CodeClean Code
Clean CodeNascenia IT
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharpSDFG5
 
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.pptAlmamoon
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.pptmothertheressa
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpg_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Sachin Singh
 

Similar to Practices for becoming a better programmer (20)

Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
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
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Clean code
Clean codeClean code
Clean code
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
New C# features
New C# featuresNew C# features
New C# features
 
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++
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.ppt
 
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#
 
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
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Clean Code
Clean CodeClean Code
Clean Code
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
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...
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 

Recently uploaded

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂșjo
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 48.
  • 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.
  • 54.
  • 55.
  • 56.
  • 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.
  • 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/