C OMP 110 S TYLE Instructor: Jason Carter. 2 I NTERFACES AND M ORE S TYLE Define contracts between our users and implementers Optional – they may not.

Slides:



Advertisements
Similar presentations
Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
Advertisements

Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
***** SWTJC STEM ***** Chapter 4-1 cg 42 Object Oriented Program Terms Up until now we have focused on application programs written in procedural oriented.
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
C OMP 110 S TATE Instructor: Jason Carter. 2 O UTLINE Instance Variables Procedures Properties Print Statements Println vs. Print Overloading.
C OMP 110 T YPES Instructor: Jason Carter. 2 O BJECTS VS. P RIMITIVE T YPES Instances of classes and interfaces are objects All other values are primitives.
C OMP 110 F UNCTIONS Instructor: Jason Carter. 2 O UTLINE Programmatic instantiation of objects Functions calling other functions Algorithm and stepwise.
C OMP 401 C LASS S TATE Instructor: Prasun Dewan.
C OMP 110 C ONDITIONALS Instructor: Jason Carter.
H OW O BJECTS B EHAVE. O VERVIEW Methods use object state Arguments and return types in methods Java passes by value Getters and Setters Encapsulation.
C OMP 401 O BJECTS Instructor: Prasun Dewan 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
C OMP 110 L OAN C ASE S TUDY Instructor: Jason Carter.
C OMP 110 O BJECTS Instructor: Jason Carter. 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
By - Qiong Han. DON’T FALL BEHIND IN READING Submission Instruction Everyone needs to submit the printed HARD- COPY of the codes and the grading sheets.
Midterm Exam 75 points 1 min per point Allocate time proportionate to points Closed book Chapters 1-5 (except char) PDF/PS with index and corrections coming.
Object-based Programming Intuitive explanation Using objects to read input Creating objects Style rules.
Program Style Identifier Names Comments Named Constants Avoiding Code Repetition Giving Least Privilege Efficiency Interfaces.
Comp 14 (3) By Stephan Sherman Office hours, W, 3:00-3:50pm.
Object-based Programming Intuitive explanation Using objects to read input Creating objects Style rules.
1 Introduction to Software Engineering Lecture 42 – Communication Skills.
More on Recursive Recursion vs. Iteration Why Recursion?
Programmer-Defined Types Object Types as Programmer-defined Types Two-way Dependencies Representation Errors Primitive Vs Object Properties Constructors.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Object-based Programming Intuitive explanation Two concrete examples Calculators addition BMI Programming Environment.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
State Instance Variables Procedures Properties Print Statements Println Vs Print Overloading J++
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Bicycle Car Types pedal() pushAccelerator(). Stringdoubleint Programming Language Types “three”“four” = 7 = “threefour” + + / = 0 / = 0.75.
Chapter Four Defining Your Own Classes continued.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
C OMP 401 C LASS S TATE Instructor: Prasun Dewan.
C OMP 401 P ATTERNS, I NTERFACES AND O BJECT E DITOR Instructor: Prasun Dewan.
C OMP 110/401 C OMPOSITE A NNOTATIONS Instructor: Prasun Dewan.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Object-Oriented Programming (OOP). Implementing an OOD in Java Each class is stored in a separate file. All files must be stored in the same package.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
Classes CS 21a: Introduction to Computing I First Semester,
C OMP 401: C ONSTRUCTORS AND P OINTERS Instructor: Prasun Dewan (FB 150,
C OMP 110 T YPES Instructor: Prasun Dewan 2 P REREQUISITES Interfaces.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
C OMP 110/401 D OCUMENTATION : C OMMENTS Instructor: Prasun Dewan.
C OMP 110/401 E NCAPSULATION AND L EAST P RIVILEGE Instructor: Prasun Dewan.
Identifiers Identifiers in Java are composed of a series of letters and digits where the first character must be a letter. –Identifiers should help to.
I NCREASING THE A UTOMATION OF A T OOLKIT WITHOUT R EDUCING ITS A BSTRACTION AND U SER - I NTERFACE F LEXIBILITY Prasun Dewan University of North Carolina.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 5.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
A DVANCED P ROGRAMMING C HAPTER 4: I NTRODUCTION TO I NTRODUCTION TO C LASSES, O BJECTS, M ETHODS AND STRINGS Dr Shahriar Bijani Winter 2016.
C OMP 401 E XCEPTIONS -R EMAINDER Instructor: Prasun Dewan.
C OMP 110/401 D OCUMENTATION : A NNOTATIONS Instructor: Prasun Dewan.
COMP Information Hiding and Encapsulation Yi Hong June 03, 2015.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
More Sophisticated Behavior
Reference: COS240 Syllabus
Methods Chapter 6.
Instructor: Prasun Dewan
Comp 110/401 Documentation: Comments
Recitation 4 September 16, 2011.
Unit 3 Test: Friday.
Defining Classes and Methods
Recitation 3 September 9, 2011 Wade Gobel.
Building Java Programs
Classes CS 21a: Introduction to Computing I
Building Java Programs
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

C OMP 110 S TYLE Instructor: Jason Carter

2 I NTERFACES AND M ORE S TYLE Define contracts between our users and implementers Optional – they may not be used Good style to use them Will study additional elements of style in this chapter

3 T WO W AYS OF D OING THE BMI S PREADSHEET ABMISpreadsheet is one way to implement the spreadsheet user-interface Let us create AnotherBMISpreadsheet to illustrate another way Difference is in number of variables used

4 BMI S PREADSHEET

5 ABMIS PREADSHEET ABMISpreadsheet Instance weight height getWeight()setWeight()getHeight()setHeight()getBMI() ObjectEditor calls writes weight calls reads height calls readswrites calls new weight new height reads

6 A NOTHER BMIS PREADSHEET AnotherBMISpreadsheet Instance weight height getWeight()setWeight()getHeight()setHeight()getBMI() ObjectEditor calls writes weight calls reads height calls reads writes calls new weight new height reads bmi

7 M ETHODS THAT C HANGE ABMISpreadsheet Instance weight height setWeight()setHeight()getBMI() ObjectEditor writes calls writes calls new weight new height reads bmi

8 SET W EIGHT () ABMISpreadsheet Instance weight setWeight() ObjectEditor writes calls new weight bmi public void setWeight( double newWeight) { weight = newWeight; bmi = weight / (height*height); }

9 SET H EIGHT () ABMISpreadsheet Instance height setHeight() ObjectEditor writes calls new height bmi public void setHeight( double newHeight) { height = newHeight; bmi = weight / (height*height); }

10 GET BMI() ABMISpreadsheet Instance getBMI() ObjectEditor reads bmi public double getBMI() { return bmi; }

11 C OMPLETE C ODE public class AnotherBMISpreadsheet { double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = weight/(height*height); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } public double getBMI() { return bmi; }

12 G RAPHICAL A LGORITHM ABMISpreadsheet Instance weight height getWeight()setWeight()getHeight()setHeight()getBMI() ObjectEditor calls writes weight calls reads height calls reads writes calls new weight new height reads bmi

13 E NGLISH A LGORITHM Declare three instance variables weight, height and, bmi Define three getter methods return values of the three instance variables Define two setter methods to change weight and height The setter methods assign new weight and height values and compute and assign new BMI value to bmi

14 A LGORITHM Description of solution to a problem Can be in any “language” graphical natural or programming language natural + programming language (pseudo code) Can describe solution to various levels of detail

15 S TEPWISE R EFINEMENT Declare three instance variables weight, height and, bmi Define three getter methods return values of the three instance variables Define two setter methods to change weight and height The setter methods assign new weight and height values and compute and assign new BMI value to bmi public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } Natural Language Programming Language

16 O BJECT E DITOR U SER I NTERFACE ? public class AnotherBMISpreadsheet { double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = weight/(height*height); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } public double getBMI() { return bmi; }

17 O BJECT E DITOR U SER I NTERFACES

18 S IMILARITIES IN THE T WO C LASSES public class AnotherBMISpreadsheet { double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = weight/(height*height); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } public double getBMI() { return bmi; } public class ABMISpreadsheet { double height; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; } double weight; public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

19 R EAL -W ORLD A NALOGY manufactures Corvette Specification implements manufactures

20 I NTERFACE

21 public class AnotherBMISpreadsheet implements BMISpreadsheet { double height, weight, bmi; public double getHeight() { return height; } public void setHeight ( double newHeight) { height = newHeight; bmi = weight/(height*height); } … I MPLEMENTING AN I NTERFACE Contract Parameter names never matter to Java

22 implements I NTERFACE ABMISpreadsheet BMISpreadsheet ABMISpreadsheet instance ABMISpreadsheet instance instance of AnotherBMISpreadsheet instance AnotherBMISpreadsheet instance instance of

23 implements U SING I NTERFACES TO C LASSIFY ABMISpreadsheet BMISpreadsheet instance BMISpreadsheet instance instance of AnotherBMISpreadsheet BMISpreadsheet instance BMISpreadsheet instance instance of

24 U SING C AR S PECIFICATIONS TO C LASSIFY manufactures Corvette Specification implements manufactures Corvette

25 C ANNOT I NSTANTIATE S PECIFICATION Cannot order a car from a specification Must order from factory A car defined by Corvette specification ordered from factory implementing the specification Cannot instantiate interface Must instantiate class BMISpreadsheet instance created by instantiating class implementing interface

26 I NTERFACE AS A S YNTACTIC S PECIFICATION public class ABMISpreadsheet implements BMISpreadsheet{ double height; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; } double weight; public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

27 I NTERFACE AS A S YNTACTIC S PECIFICATION public class ABMISpreadsheet implements BMISpreadsheet{ double height; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; } double weight; public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return 13450; } Syntactic Contract Bombay Market Index

28 I NTERFACE R EQUIRED Define interfaces for All classes (that are instantiated) Some are not Include all public methods

29 D IFFERENCES IN THE T WO C LASSES public class AnotherBMISpreadsheet { double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = weight/(height*height); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } public double getBMI() { return bmi; } public class ABMISpreadsheet { double height; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; } double weight; public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

30 ABMIS PREADSHEET VS. A NOTHER BMIS PREADSHEET ABMISpreadsheet uses less space (variables) Getter methods of AnotherBMISpreadhseet are faster Setter methods of ABMISpreadsheet are faster Usually getter methods are called more often that setter methods e.g. when ObjectEditor refresh command is executed Typically AnotherBMISpreadsheet will be faster, overall

31 T IME -S PACE T RADEOFF Time Miser Space Miser Space Time

32 T IME -S PACE T RADEOFF Space Time Time Miser Space Miser

33 R ELATING I NTERFACE AND C LASS N AMES Class Name: - ABMISpreadsheet - ASpaceEfficientBMISpreadsheet - SpaceEfficientBMISpreadsheet - ABMISpreadsheet - ASpaceEfficientBMISpreadsheet - SpaceEfficientBMISpreadsheet Impl - BMISpreadsheetImpl - BMISpreadsheetSpaceEfficientImpl Impl - BMISpreadsheetImpl - BMISpreadsheetSpaceEfficientImpl Interface Name: Interface - ABMISpreadsheetInterface Interface - ABMISpreadsheetInterface

34 P ROGRAMMING S TYLE : T HE A RT OF P ROGRAMMING Science of programming Does the program work correctly? Art programming Does the program follow “good” style rules? Good style rules make it easier to Get the program working correctly Change the program

35 W RITING S TYLE To the point Avoid repetition Good flow Illustrate ideas There is more than one way to write a document that conveys some facts: e.g. the influence of BMI on health

36 P ROGRAMMING S TYLE : T HE A RT OF P ROGRAMMING Define interfaces Make programs efficient Space vs. time Comment program Use appropriate identifier names Use named constants Variables vs. names Constants vs. magic numbers Avoid code repetition Give least privilege No public instance variables Implementation independent constants in interfaces Initialize variables Independent code in separate method There is more than one way to write a program that correctly meets its specification: e.g. implement the BMI user-interface

37 P ROGRAMMING S TYLE : T HE A RT OF P ROGRAMMING Use Interfaces Efficiency Comment Program Avoid Code Repetition Giving Least Privilege Use Named Constants

38 C OMMENTS double bmi; //computed by setWeight and setHeight Single line comments /* This version recalculates the bmi when weight or height change, not when getBMI is called */ public class AnotherBMISpreadsheet {…} /* recompute dependent properties */ bmi = weight / (height * height); Arbitrary comments

39 J AVA D OC C ONVENTIONS /* This version recalculates the bmi when weight or height change, not when getBMI is called */ public class AnotherBMISpreadsheet {…} /* This version recalculates the bmi * when weight or height change, not when * getBMI is called */ public class AnotherBMISpreadsheet {…} You should use this convention

40 System.out.println(newHeight); /*debugging statement */ R EMOVING D EBUGGING C ODE /* System.out.println(newHeight); /*debugging statement */ */ /* System.out.println(newHeight); // debugging statement */

41 W HAT TO C OMMENT ? Any code fragment needing explanation Class Top-level algorithm, author, date modified Variable declaration Purpose, where used, how its value is computed Method declaration params, return value, algorithm, author, date modified Statement sequence Explanation Debugging code Summarizing vs. Elaborating Comments?

42 W HAT TO C OMMENT ? double w; // weight double weight; // weight double weight; double bmi; // computed by setWeight and setHeight Bad variable name Redundant Self-commenting Useful comment

43 J AVA D OC T AGS /* Prasun Dewan newWeight the new value of the property, weight. * sets new values of the variables, weight and bmi */ public void setWeight ( double newWeight) { … } /* Prasun Dewan the value of the variable, weight */ public double getWeight () { … } JavaDoc tags

44 C OMMENTING I NTERFACES /* newWeight the new value of the property, weight */ public void setWeight ( double newWeight) { } /* the value of the variable, weight */ public double getWeight () { } Implementation independent comments Commenting both interface and implementation?

45 P ROGRAMMING S TYLE : T HE A RT OF P ROGRAMMING Use Interfaces Efficiency Comment Program Avoid Code Repetition Giving Least Privilege Use Named Constants

46 I MPROVING THE S TYLE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = weight/(height*height); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } public double getBMI() { return bmi; } Code repetition Assuming ABMICalculator does not exist

47 I MPROVING THE S TYLE (E DIT ) public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } … public void setWeight( double newWeight) { weight = newWeight; bmi = calculateBMI(); } public double getBMI() { return bmi; } double calculateBMI() { return weight/(height*height); }

48 R E - USING C ODE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = calculateBMI(); } double calculateBMI() { return weight/(height*height); } …. }

49 C HANGING R E - USED C ODE O NCE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = calculateBMI(); } double calculateBMI() { return (weight/2.2)/(height * 2.54/100*height*2.54/100); } … } Declaring vs. calling methods?

50 P ROGRAMMING S TYLE : T HE A RT OF P ROGRAMMING Use Interfaces Efficiency Comment Program Avoid Code Repetition Giving Least Privilege Use Named Constants

51 O NLY P UBLIC M ETHODS IN I NTERFACE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } … double calculateBMI() () { return (weight/2.2)/(height * 2.54/100*height*2.54/100); } … } Not in interface

52 P RINCIPLE OF L EAST P RIVILEGE Do not give a user of some code more rights than it needs Code is easier to change Need to learn less to use code Less likelihood of accidental or malicious damage to program Like hiding engine details from car driver ObjectEditor ABMICalculator User ABMICalculator getWeight() setWeight() getHeight() setHeight() getBMI() computeBMI()

53 I MPROVING THE S TYLE Use Interfaces Efficiency Comment Program Use Named Constants Avoid Code Repetition Giving Least Privilege

54 I MPROVING THE S TYLE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } … double calculateBMI() () { return (weight/2.2)/(height * 2.54/100*height*2.54/100); } … } Magic numbers

55 I MPROVING THE S TYLE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } … double calculateBMI() () { return (weight/LBS_IN_KG) / (height*CMS_IN_INCH/100*height*CMS_IN_INCH/100); } … } Named constants

56 D ECLARING N AMED C ONSTANTS public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi;... final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() { return (weight/LBS_IN_KG) / (height*CMS_IN_INCH/100*height*CMS_IN_INCH/100); } … } Un-initializing declaration Initializing declaration

57 M ORE ON V ARIABLES VS. N AMED C ONSTANTS public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi;... double lbsInKg = 2.2; double cmsInInch = 2.54; … double calculateBMI() { return (weight/lbsInKg) / (height*cmsInInch/100*height*cmsInInch/100); } … }

58 A CCIDENTAL OR M ALICIOUS M ODIFICATION public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi;... double lbsInKg = 2.2; double cmsInInch = 2.54; … double calculateBMI() { lbsInKg = 22; return (weight/lbsInKg) / (height*cmsInInch/100*height*cmsInInch/100); } … } Violating least privilege

59 L ITERALS VS. N AMED C ONSTANTS VS. V ARIABLES Use constants for program values that do not change Use named constants for magic numbers

60 M ORE C ODE R EPETITION public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi;... final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() { return (weight/LBS_IN_KG) / (height*CMS_IN_INCH/100*height*CMS_IN_INCH/100); } … } Within same method and has the same value

61 R EMOVING C ODE R EPETITION (E DIT ) public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi;... final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() { double heightInMeters = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMeters*heightInMeters); } … }

62 R EMOVING C ODE R EPETITION public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi;... final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() { double heightInMeters = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMeters*heightInMeters); } … }

63 L OCAL VS. G LOBAL V ARIABLE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; double heightInMeters = height*CMS_IN_INCH/100;... final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() { return (weight/LBS_IN_KG) / (heightInMeters*heightInMeters); } … }

64 L OCAL VS. G LOBAL V ARIABLE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; double heightInMeters = height*CMS_IN_INCH/100;... final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … public void setHeight( double newHeight) { heightInMeters = newHeight; bmi = calculateBMI(); } … double calculateBMI() { return (weight/LBS_IN_KG) / (heightInMeters*heightInMeters); } … } Violating least privilege

65 public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } … double calculateBMI () { double heightInMetres = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … } SCOPE heightInMeters scope Not a scope height scope

66 S COPE OF P UBLIC I TEMS public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … public double getWeight() { return weight; } … } public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … public double getWeight() { return weight; } … } ObjectEditor ABMISpreadsheet getWeight() scope

67 I DENTIFIER S COPE Region of code where the identifier is visible Arbitrary scopes not possible Least Privilege => Make scope as small as possible

68 S COPE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … public void setHeight( double newHeight) { height = newHeight; bmi = calculateBMI(); } public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; bmi = weight/(height*height); } … double calculateBMI() () { double heightInMetres = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … } heightInMeters scope

69 I NITIALIZING D ECLARATION public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() () { double heightInMetres = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … }

70 U N - INITIALIZING D ECLARATION public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() () { double heightInMetres; heightInMeters = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … }

71 U N - INITIALIZED V ARIABLE public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() () { double heightInMetres; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … }

72 I NITIALIZING A LL V ARIABLES public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height, weight, bmi; … final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() () { double heightInMetres; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … }

73 I NITIALIZING A LL V ARIABLES (E DIT ) public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height = 60, weight = 70, bmi = getBMI(); … final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() () { double heightInMetres = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … }

74 I NITIALIZING A LL V ARIABLES public class AnotherBMISpreadsheet implements BMISpreadsheet{ double height = 70, weight = 160, bmi = calculateBMI(); … final double LBS_IN_KG = 2.2; final double CMS_IN_INCH = 2.54; … double calculateBMI() () { double heightInMetres = height*CMS_IN_INCH/100; return (weight/LBS_IN_KG) / (heightInMetres*heightInMetres); } … }

75 P RINTING P ROPERTIES public class ABMISpreadsheet implements BMISpreadsheet { double height; public double getHeight() { return height; } public void setHeight( double newHeight) { height = newHeight; } double weight; public double getWeight() { return weight; } public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

76 P RINTING P ROPERTIES (E DIT ) public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { System.out.println(“Height: “ + newHeight); height = newHeight; } double weight; … public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

77 P RINTING P ROPERTIES public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); double bmi = getBMI(); System.out.println(“BMI: “ + bmi); height = newHeight; } double weight; … public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

78 L ESS C LUTTERED C ODE (E DIT ) public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); double bmi = getBMI(); System.out.println(“BMI: “ + bmi); height = newHeight; } double weight; … public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

79 L ESS C LUTTERED C ODE public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); System.out.println(“BMI: “ + getBMI()); height = newHeight; } double weight; … public void setWeight( double newWeight) { weight = newWeight; } public double getBMI() { return weight/(height*height); }

80 R EMOVING D UPLICATION public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); System.out.println(“BMI: “ + getBMI()); height = newHeight; } double weight; … public void setWeight( double newWeight) { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); System.out.println(“BMI: “ + getBMI()); weight = newWeight; } public double getBMI() { return weight/(height*height); }

81 R EMOVING D UPLICATION (E DIT ) public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { printProperties(); height = newHeight; } double weight; … public void setWeight( double newWeight) { printProperties(); weight = newWeight; } public double getBMI() { return weight/(height*height); } void printProperties() { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); System.out.println(“BMI: “ + getBMI()); }

82 R EMOVING D UPLICATION public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { printProperties(); height = newHeight; } double weight; … public void setWeight( double newWeight) { printProperties(); weight = newWeight; } … void printProperties() { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); System.out.println(“BMI: “ + getBMI()); }

83 S EPARATION OF C ONCERNS public class ABMISpreadsheet implements BMISpreadsheet { double height; … public void setHeight( double newHeight) { printProperties(); height = newHeight; } double weight; … public void setWeight( double newWeight) { printProperties(); weight = newWeight; } … void printProperties() { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); System.out.println(“BMI: “ + getBMI()); } Less cluttered

84 I NDEPENDENT C ODE = M ETHOD Separate method for: Any independent piece of code Even if it is not duplicated If it is more than one line public void setWeight(double newWeight) { System.out.println(“Weight: “ + weight); weight = newWeight; } public void setWeight(double newWeight) { printWeight(); weight = newWeight; }

85 P RINTING BMI IN GET BMI() public class ABMISpreadsheet implements BMISpreadsheet { double height; … public double getBMI() { printProperties(); return weight/(height*height); } … void printProperties() { System.out.println(“Weight: “ + weight); System.out.println(“Height: “ + height); System.out.println(“BMI: “ + getBMI()); } getBMI() never terminates Recursive, calls itself indirectly Infinite recursion Avoid recursion for now

86 N ON - PUBLIC I NSTANCE V ARIABLES public class ABMISpreadsheet implements BMISpreadsheet { double height, weight, bmi; … }

87 M AKING I NSTANCE V ARIABLES P UBLIC public class ABMISpreadsheet implements BMISpreadsheet { public double height, weight, bmi; … } Other classes

88 H ARD TO C HANGE public class ABMISpreadsheet implements BMISpreadsheet { public double height, weight; … } Other classes

89 C ONSISTENCY C ONSTRAINTS V IOLATED Inconsistent values

90 P RECONDITIONS C ANNOT BE E NFORCED More on this later

91 E NCAPSULATION P RINCIPLE Do not make instance variables public Expose them through public methods

92 public final double CMS_IN_INCH = 2.54; P UBLIC C ONSTANTS public interface BMISpreadsheet { public final double CMS_IN_INCH = 2.54; } Inconsistent value cannot be stored Implementation independent ABMISpreadsheet AnotherBMISpreadsheet

93 P RINCIPLE Declare implementation-independent named constants in interfaces implementing classes can access them

94

95 E XTRA S LIDES

96 S TEPWISE R EFINEMENT Declare two instance variables weight and height Define a getter method that computes the value of BMI and returns it public double getBMI() { return weight/(height*height); } Natural Language Programming Language

97 R EAL -W ORLD A NALOGY manufactures Corvette Specification implements manufactures