1. Trang chủ
  2. » Công Nghệ Thông Tin

OOP 04

23 181 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 23
Dung lượng 160,02 KB

Nội dung

Contents • • • • • CHAPTER Elegance and Methods INTRODUCTION CODING STYLES AND NAMING CONVENTIONS METHODS AND DECOMPOSITION COHESIVE METHODS WELL-FORMED OBJECTS AND CLASS INVARIANTS NNL – Khoa Tốn Tin ĐHKHTN Contents INTRODUCTION • INTERNAL DOCUMENTATION • EXTERNAL DOCUMENTATION • SOME CASE STUDIES NNL – Khoa Tốn Tin ĐHKHTN • The three OO design levels are: Conceptual Specification Implementation • This chapter focuses mostly on implementation and specification issues NNL – Khoa Toán Tin ĐHKHTN CODING STYLES AND NAMING CONVENTIONS INTRODUCTION • More precisely, this chapter discusses standard forms for methods and elegant implementations of methods • One important factor in determining the elegance of code is its readability In fact, “Programs must be written for people to read, and only incidentally for machines to execute.” NNL – Khoa Toán Tin ĐHKHTN CODING STYLES AND NAMING CONVENTIONS NNL – Khoa Toán Tin ĐHKHTN CODING STYLES AND NAMING CONVENTIONS • One of the most important coding conventions affecting readability and elegance of code is the proper naming of your variables, classes, and methods • Classes and interfaces should have names that reflect the role or intention of the objects of those types Interfaces often have names ending in “able” or “ible” Guidelines Choose a standard coding style and follow that style throughout all your code NNL – Khoa Toán Tin ĐHKHTN • There are many coding styles for writing the bodies of classes and their methods using Java • However, there are valid reasons for following certain agreed-upon stylistic conventions as much as possible • Sun Microsystems suggests certain conventions when writing Java programs (http://java.sun.com/docs/codeconv/) NNL – Khoa Toán Tin ĐHKHTN CODING STYLES AND NAMING CONVENTIONS CODING STYLES AND NAMING CONVENTIONS • The method name should indicate the intent of the method, that is, what the method is supposed to accomplish The name should not indicate how the method accomplishes its goal but rather what that goal is • Variables need to be named appropriately to promote readability (Ex: nT, theNumberOfThreadsInTheCurrentApplicatio nRunningRightNow.) • Using good names is even more important for constants • Finally, not only is choosing the right names important, but also following convention in the capitalization of the names is important • Follow a consistent capitalization scheme, starting your class and interface names with capital letters and starting your variable and method names with small letters NNL – Khoa Toán Tin ĐHKHTN CODING STYLES AND NAMING CONVENTIONS 10 METHODS AND DECOMPOSITION • Programmers can treat methods as if they were built-in higher-level features in the programming language, and so they can conceptualize larger sections of code • The process of breaking code into methods is called functional decomposition • The decomposition of code into well-designed methods not only improves the readability of the code, it also promotes reusability Guideline Use intention-revealing names for all variables, methods, and classes so that they accurately describe the role or intentions of the things they are naming NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN 11 NNL – Khoa Toán Tin ĐHKHTN 12 METHODS AND DECOMPOSITION METHODS AND DECOMPOSITION public void parse(String expression) { // some parsing if( ! nextToken.equals("+") ) { //error System.out.println("Expected +, but found " + nextToken); System.exit(1); } if( ! nextToken.equals("*") ) { //error System.out.println("Expected *, but found " + nextToken); System.exit(1); } } • When should a method be decomposed into other methods? • Decomposition should also be considered when there is duplicate code • Consider some examples NNL – Khoa Toán Tin ĐHKHTN 13 METHODS AND DECOMPOSITION 14 METHODS AND DECOMPOSITION public void parse(String expression) { if( ! nextToken.equals("+") ) handleError("Expected '+', but found" + nextToken); if( ! nextToken.equals('*') ) handleError("Expected '+', but found" + nextToken); } private void handleError(String message) { System.out.println(message); System.exit(1); } NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN public class Family { public Family(Person father, Person mother, Person[] children) { code } public Family(Person father, Person mother) { this(father, mother, new Person[0]); } other methods } 15 NNL – Khoa Toán Tin ĐHKHTN 16 METHODS AND DECOMPOSITION COHESIVE METHODS • One important property of methods is that they should be as self-contained as possible • Another important property of methods is that they only one thing Guideline A method should one thing only and it well Guideline Use methods, especially private auxiliary methods, for decomposition to reduce duplication of code and to raise the level of abstraction of the code NNL – Khoa Toán Tin ĐHKHTN 17 COHESIVE METHODS 18 COHESIVE METHODS void doThisOrThat(boolean flag) { if( flag ) { twenty lines of code to this } else { twenty lines of code to that } } NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN void doThisOrThat(boolean flag) { if( flag ) doThis(); else doThat(); } 19 NNL – Khoa Toán Tin ĐHKHTN 20 COHESIVE METHODS COHESIVE METHODS void doThisOrThat(boolean flag) { if( flag ) { doThis(); } else { twenty lines of code to that } } NNL – Khoa Toán Tin ĐHKHTN Guideline All code in a method should execute at the same level 21 NNL – Khoa Toán Tin ĐHKHTN 22 COHESIVE METHODS COHESIVE METHODS • There is another implication to the statement that a method should one thing only The implication is that a method should not both return a value and modify the state of some object (Command-Query Separation Principle) • (Some standard methods in the Java library classes that not follow this guideline.) Guideline Functions (which return a value) should not modify any existing object’s state in a way visible to other objects and modifier methods (which modify one or more objects’ state) should have “void” as the return type NNL – Khoa Toán Tin ĐHKHTN 23 NNL – Khoa Toán Tin ĐHKHTN 24 WELL-FORMED OBJECTS AND CLASS INVARIANTS WELL-FORMED OBJECTS AND CLASS INVARIANTS • Consider what would happen if the value of length was different than the actual number of nodes • Clearly, we need the two values (length and the number of nodes) to be the same if the class is to be usable • It is this kind of internal consistency that we mean when we say a class is “well-formed.” Guideline • Public methods should always keep objects in a well-formed state • Consider a MyLinkedList class that has an instance variable head of type Node and another instance variable length of type int that indicates the number of nodes NNL – Khoa Toán Tin ĐHKHTN 25 NNL – Khoa Toán Tin ĐHKHTN 26 WELL-FORMED OBJECTS AND CLASS INVARIANTS WELL-FORMED OBJECTS AND CLASS INVARIANTS • A good way is to specify what makes objects of a class well-formed is to list the class invariants • A class invariant is a statement about the state of objects of the class between public method calls • The statement of equality of the value of length and the number of Nodes in an object of the MyLinkedList class is an example of a class invariant • Is it a good idea to have such a length instance variable, as we described above? After all, you can compute the length of the list whenever you want by traversing it and counting the number of nodes NNL – Khoa Toán Tin ĐHKHTN 27 NNL – Khoa Toán Tin ĐHKHTN 28 WELL-FORMED OBJECTS AND CLASS INVARIANTS INTERNAL DOCUMENTATION Guideline Be aware that, although it can increase the efficiency of your code, caching values instead of computing them when they are needed can also increase the complexity and number of invariants of your class • A software package, no matter how well designed otherwise, is almost worthless if documentation is not included • Internal documentation is the documentation for someone who is looking at the source code • Internal documentation should also clearly state any class or method invariants that exist NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN 29 INTERNAL DOCUMENTATION INTERNAL DOCUMENTATION • Internal documentation should not repeat what the code says Instead, it should summarize the intent or purpose of the code or gives a higher-level explanation • Internal documentation mostly consists of comments in the source code, but the code itself can be a useful part of the documentation if the code is well written NNL – Khoa Toán Tin ĐHKHTN 30 Guideline Always strive for “self-documenting code” that is so clear that no comments are necessary • Code needing a large number of comments usually indicates poor code 31 NNL – Khoa Toán Tin ĐHKHTN 32 INTERNAL DOCUMENTATION INTERNAL DOCUMENTATION • When should comments be added to the code? Guideline Write comments before or while writing the code, not after “Build it in, don’t add it on.” Guideline If your code is so complicated that it needs explaining with lots of internal or external documentation, then the code should probably be rewritten NNL – Khoa Toán Tin ĐHKHTN 33 INTERNAL DOCUMENTATION 34 INTERNAL DOCUMENTATION • The role of documentation (Kernigan and Plauger): If a program is incorrect, it matters little what the documentation says If documentation does not agree with the code, it is not worth much NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN 35 Consequently, code must largely document itself If it cannot, rewrite the code rather than increase the supplementary documentation Good code needs fewer comments than bad code does Comments should provide additional information that is not readily obtainable from the code itself They should never parrot the code Mnemonic variable names and labels, and a layout that emphasizes logical structure, help make a program self-documenting NNL – Khoa Toán Tin ĐHKHTN 36 EXTERNAL DOCUMENTATION EXTERNAL DOCUMENTATION • External documentation is for the users of the code who can’t look at or don’t care about the source code itself • It describes the public classes, interfaces, methods, fields, and packages and how to use them • External documentation might also include design documents such as UML diagrams • What should be included in the external documentation of a method? • This documentation must include the full method signature and return type so that the user knows the syntax to use in a method call, but much more is needed as well NNL – Khoa Tốn Tin ĐHKHTN 37 EXTERNAL DOCUMENTATION 38 EXTERNAL DOCUMENTATION • What should be included in external documentation? • One of the important steps in the design process is the development of a precise specification of the behavior of the method before the method is implemented • This specification is useful to the designer so that he or she can document exactly the role the method will play in the system NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN • If the designer’s specification is too vague and general, problems can occur during the implementation phase For example (bad documentation): public double nthRoot(double value, int n) returns the n-th root of the double value 39 NNL – Khoa Tốn Tin ĐHKHTN 40 EXTERNAL DOCUMENTATION EXTERNAL DOCUMENTATION • Another problem with external documentation can occur if the designer is overly restrictive, specifying too many details • Here is an example of more complete documentation for the nthRoot method: public double nthRoot(double value, int n) returns the n-th root of the double value If n is even, the positive n-th root is returned If n is odd, the n-th root will have the same sign as the value If n < or if n is odd and value < then an IllegalArgumentException is thrown NNL – Khoa Toán Tin ĐHKHTN public static Set intersect(Set s1, Set s2) returns a Set with the common elements of s1 and s2 by first creating an empty Set to be filled with the common elements and then stepping through the elements of s1 using an iterator and testing whether those elements are also in s2 by calling s2.contains(e), where e is the next element of s1 to be tested If s2 contains e, then e is added to the Set that is returned 41 EXTERNAL DOCUMENTATION 42 EXTERNAL DOCUMENTATION • How you determine when the external documentation for a method is just right? • Think of a method as a service: specify clearly what the users need to and what your object will in return when it executes the method • In terms of a contract: If a user provides appropriate arguments, then your method promises to perform a specific service Guideline The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow all implementations that are acceptable NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN 43 NNL – Khoa Toán Tin ĐHKHTN 44 EXTERNAL DOCUMENTATION EXTERNAL DOCUMENTATION • A precondition is a condition that must be true in order for a method to work A postcondition tells what the method guarantees will happen when it is executed • It is up to the client to make sure the preconditions are satisfied before attempting the method call Guideline Specify precisely all preconditions and postconditions for each of your methods in the external documentation These conditions form the contract for your method NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN 45 EXTERNAL DOCUMENTATION EXTERNAL DOCUMENTATION Example: Better external documentation would warn the user that the two parameters must not be null: An example of even better documentation of the intersect method is the following: public static Set intersect(Set s1, Set s2) Precondition: none Postcondition: returns a Set with the common elements of s1 and s2 if s1 and s2 are not null If s1 or s2 is null, an IllegalArgumentException is thrown public static Set intersect(Set s1, Set s2) Precondition: s1 and s2 are not null Postcondition: returns a Set with the common elements of s1 and s2 NNL – Khoa Toán Tin ĐHKHTN 46 47 NNL – Khoa Toán Tin ĐHKHTN 48 EXTERNAL DOCUMENTATION EXTERNAL DOCUMENTATION Guideline Try to make your methods something appropriate in all cases so that there are no preconditions • This guideline is one example of a practice called defensive programming • There are situations where this guideline needs to be ignored NNL – Khoa Toán Tin ĐHKHTN Guideline (Liskov Substitution Principle) It is acceptable to make B a subclass of A only if for every public method with identical signatures in both A and B, the preconditions for B’s method are no stronger than the preconditions for A’s method and the postconditions for B’s method are no weaker than the postconditions for A’s method 49 NNL – Khoa Toán Tin ĐHKHTN 50 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA • Suppose you have created a new class and have decided to override the equals(Object) method inherited from the Object class or another superclass • You can’t, of course, change the method arbitrarily and still expect to have an elegant design • The Java API specifies the following equivalence relational properties for the Object class’ equals method: NNL – Khoa Toán Tin ĐHKHTN It is reflexive: for any nonnull reference value x, x.equals(x) should return true It is symmetric: for any nonnull reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true 51 NNL – Khoa Toán Tin ĐHKHTN 52 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA It is transitive: for any nonnull reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true It is consistent: for any nonnull reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified For any nonnull reference value x, x.equals(null) should return false NNL – Khoa Toán Tin ĐHKHTN 53 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA • Because the equals method of the Object class implements an equivalence relation, all overriding equals methods in subclasses are also expected to so (due to the Liskov Substitution Principle) • The implementation of the equals method in the Object class tests object identity • Some standard Java classes, such as String and Point, override this method to test equality in a different way NNL – Khoa Toán Tin ĐHKHTN 54 OVERRIDING THE EQUALS METHOD IN JAVA OVERRIDING THE EQUALS METHOD IN JAVA public class Triangle { private Point p1, p2, p3; //the three corners public Triangle(Point p1, Point p2, Point p3) { if( p1 == null ) p1 = new Point(0,0); if( p2 == null ) p2 = new Point(0,0); if( p3 == null ) p3 = new Point(0,0); this.p1 = p1; this.p2 = p2; this.p3 = p3; } other methods } //version — in Triangle class public boolean equals(Object obj) { if( ! (obj instanceof Triangle) ) return false; Triangle otherTriangle = (Triangle) obj; return (p1.equals(otherTriangle.p1) && p2.equals(otherTriangle.p2) && p3.equals(otherTriangle.p3)); } NNL – Khoa Toán Tin ĐHKHTN 55 NNL – Khoa Toán Tin ĐHKHTN 56 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA OVERRIDING THE EQUALS METHOD IN JAVA • Note how this method elegantly uses the equals method of its components Does this equals method implement an equivalence relation? Yes, it is • Now let’s create a subclass of Triangle public class ColoredTriangle extends Triangle { private Color color; public ColoredTriangle (Color c, Point p1, Point p2, Point p3) { super(p1, p2, p3); if( c == null ) c = Color.red; color = c; } other methods } NNL – Khoa Toán Tin ĐHKHTN 57 NNL – Khoa Toán Tin ĐHKHTN 58 OVERRIDING THE EQUALS METHOD IN JAVA OVERRIDING THE EQUALS METHOD IN JAVA Triangle t = new Triangle(new Point(0,0), new Point(1,3), new Point(2,2)); ColoredTriangle ct = new ColoredTriangle(Color.red, new Point(0,0), new Point(1,3), new Point(2,2)); System.out.println(t.equals(ct)); System.out.println(ct.equals(t)); ColoredTriangle redTriangle = new ColoredTriangle(Color.red, new Point(0,0), new Point(1,3), new Point(2,2)); ColoredTriange blueTriangle = new ColoredTriangle(Color.blue, new Point(0,0), new Point(1,3), new Point(2,2)); System.out.println(redTriangle.equals(blueTr iangle)); System.out.println(blueTriangle.equals(redTr iangle)); NNL – Khoa Toán Tin ĐHKHTN 59 NNL – Khoa Toán Tin ĐHKHTN 60 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA //version — in ColoredTriangle class public boolean equals(Object obj) { if( ! (obj instanceof ColoredTriangle) ) return false; ColoredTriangle otherColoredTriangle = (ColoredTriangle) obj; return super.equals(otherColoredTriangle) && this.color.equals(otherColoredTriangle.color); } • It seems reasonable to implement the ColoredTriangle’s equals method in a way similar to the Triangle’s equals method: • So we are done? Consider this test code: NNL – Khoa Toán Tin ĐHKHTN 61 NNL – Khoa Toán Tin ĐHKHTN 62 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA // Test code Triangle t = new Triangle(new Point(0,0), new Point(1,3), new Point(2,2)); ColoredTriangle rct = new ColoredTriangle(Color.red, new Point(0,0), new Point(1,3), new Point(2,2)); System.out.println(t.equals(rct)); System.out.println(rct.equals(t)); • To fix the symmetry, we could change the ColoredTriangle’s equals method so that, if the argument is a Triangle rather than a ColoredTriangle, then the method just calls and returns the result of the superclass’ (Triangle’s) equals method NNL – Khoa Toán Tin ĐHKHTN 63 NNL – Khoa Toán Tin ĐHKHTN 64 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA //version — in ColoredTriangle class public boolean equals(Object obj) { if( obj instanceof ColoredTriangle ) { ColoredTriangle otherColoredTriangle = (ColoredTriangle) obj; return super.equals(otherColoredTriangle) && this.color.equals(otherColoredTriangle.color); } else if( obj instanceof Triangle ) { return super.equals(obj); } else return false; } //version — in the Triangle class public boolean equals(Object obj) { if( obj == null ) return false; if( obj.getClass() != this.getClass() ) return false; Triangle otherTriangle = (Triangle) obj; return (p1.equals(otherTriangle.p1) && p2.equals(otherTriangle.p2) && p3.equals(otherTriangle.p3)); } • The method now implements an equivalence relation ? NNL – Khoa Toán Tin ĐHKHTN 65 NNL – Khoa Toán Tin ĐHKHTN 66 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA //version – in ColoredTriangle class public boolean equals(Object obj) { if( obj == null ) return false; if( obj.getClass() != this.getClass() ) return false; if( ! super.equals(obj) ) return false; ColoredTriangle otherColoredTriangle = (ColoredTriangle) obj; return this.color.equals(otherColoredTriangle.color); } • These latest versions (version of equals in the Triangle class and version of equals in the ColoredTriangle class) both implement equivalence relations So, are we done? • Suppose a user has three variables t1, t2, and t3 of type Triangle Consider: t1.equals(t3) t2.equals(t3) NNL – Khoa Toán Tin ĐHKHTN 67 NNL – Khoa Toán Tin ĐHKHTN 68 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA • What is going on here? In the process of getting reflexivity, symmetry, and transitivity to work, we ended up giving the ColoredTriangle class’ equals method significantly different behavior than its superclass’ equals method • This problem is not unique to the Triangle and ColoredTriangle classes Therefore, we have two choices: NNL – Khoa Toán Tin ĐHKHTN Allow two classes in an inheritance chain to override the Object class’ equals method, but accept the fact that the Liskov Substitution Principle will be violated In any inheritance chain, have at most one class that overrides the Object class’ equals method 69 NNL – Khoa Toán Tin ĐHKHTN 70 CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA CASE STUDY: OVERRIDING THE EQUALS METHOD IN JAVA • Note: We might implement public boolean equals(Triangle otherTriangle) //in Triangle class { return (p1.equals(otherTriangle.p1) && p2.equals(otherTriangle.p2) && p3.equals(otherTriangle.p3)); } • And simplify slightly the implementation of the equals(Object): public boolean equals(Object obj) //in Triangle class { if( ! (obj instanceof Triangle) ) return false; return this.equals((Triangle) obj); } NNL – Khoa Toán Tin ĐHKHTN 71 NNL – Khoa Toán Tin ĐHKHTN 72 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • The method’s intention is to create and return an object that is a clone of the object on which the method is invoked • Objects are not actually clonable unless their class implements the Cloneable interface • If you want to allow everyone to clone objects of your class, you need to state that your class implements the Cloneable interface NNL – Khoa Toán Tin ĐHKHTN 73 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • The interface of the clone method is: public Object clone() • A shallow clone is one for which only the object itself is copied • A deep clone is one in which all objects referred to by instance variables are also (deeply) cloned NNL – Khoa Toán Tin ĐHKHTN 74 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • //in the Triangle class—correct shallow clone implementation public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } • // in the Triangle class—shallow clone implementation public Object clone() { return new Triangle(p1, p2, p3); } • This clone method is less than elegant NNL – Khoa Toán Tin ĐHKHTN CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA 75 NNL – Khoa Toán Tin ĐHKHTN 76 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • • //in the ColoredTriangle class—correct shallow clone implementation public Object clone() { return super.clone(); } NNL – Khoa Toán Tin ĐHKHTN 77 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • //in the ColoredTriangle class—incorrect implementation public Object clone() { try { ColoredTriangle clone = (ColoredTriangle) super.clone(); clone.color = (Color) color.clone(); return clone; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } NNL – Khoa Toán Tin ĐHKHTN CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA //in the Triangle class—correct deep clone implementation public Object clone() { try { Triangle clone = (Triangle) super.clone(); clone.p1 = (Point) p1.clone(); clone.p2 = (Point) p2.clone(); clone.p3 = (Point) p3.clone(); return clone; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } NNL – Khoa Toán Tin ĐHKHTN 78 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • Unfortunately, this code doesn’t quite work The Java compiler will complain because the Color class does not implement Cloneable What we now? • General problem: How you create a deep clone of an object if the attributes of the object not implement Cloneable? 79 NNL – Khoa Toán Tin ĐHKHTN 80 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • This method is not always going to produce an exact deep clone Suppose you created a subclass of Color: public class NamedColor extends Color { private String name; public NamedColor(String s, int rgb) { super(rgb); name = s; } public String getName() { return name; } } • //in the ColoredTriangle class—incorrect implementation public Object clone() { try { ColoredTriangle clone = (ColoredTriangle) super.clone(); clone.color = new Color(color.getColorSpace(), color.getColorComponents(color.getColorSpace(), null), color.getAlpha()); return clone; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } NNL – Khoa Toán Tin ĐHKHTN 81 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • // Test code NNL – Khoa Toán Tin ĐHKHTN 82 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA • The lesson here is that it is hard to create a deep clone of an object if the object’s attributes are not Cloneable • Even if all instance variables refer to Cloneable objects, those objects’ clone methods may produce shallow clones of themselves NamedColor mauve = new NamedColor("Mauve", 3456); ColoredTriangle ct = new ColoredTriangle(mauve, new Point(0,0), new Point(1,1), new Point(2,2)); ColoredTriangle clone = (ColoredTriangle) ct.clone(); NNL – Khoa Toán Tin ĐHKHTN CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA 83 NNL – Khoa Toán Tin ĐHKHTN 84 CASE STUDY: OVERRIDING THE CLONE METHOD IN JAVA CODE OPTIMIZATION In summary: • An elegant equals method can be implemented in your classes as long as you are aware of all the pitfalls • In contrast, creating an elegant clone method depends not just on your understanding of the pitfalls, but also on the proper behavior of the superclasses of your class • Well-written code performs its tasks using a reasonable amount of resources such as time and memory • Unfortunately, making complex changes to the code to optimize it is very hard on the readability of the code • How can you maximize the readability of the code and at the same time get the performance that you need? • NNL – Khoa Tốn Tin ĐHKHTN NNL – Khoa Tốn Tin ĐHKHTN 85 CODE OPTIMIZATION SYMMARY • Choose a standard coding style and follow that style throughout all your code • Use intention-revealing names for all variables, methods, and classes so that they accurately describe the role or intentions of the things they are naming • Use methods, especially private auxiliary methods, for decomposition to reduce duplication of code and to raise the level of abstraction of the code • A good programmer will write code that is readable and only later worry about optimization • Programmers make a common mistake when they try to optimize their code too early Guideline Balance optimization needs with readability needs NNL – Khoa Toán Tin ĐHKHTN 86 87 NNL – Khoa Tốn Tin ĐHKHTN 88 SYMMARY SYMMARY • A method should one thing only and it well • All code in a method should execute at the same level • Functions (which return a value) should not modify any existing object’s state in a way visible to other objects, and modifier methods (which modify one or more objects’ state) should have “void” as the return type • Public methods should always keep objects in a well-formed state • Be aware that, although it can increase the efficiency of your code, caching values instead of computing them when they are needed can also increase the complexity and number of invariants of your classes • Always strive for “self-documenting code” that is so clear that no comments are necessary NNL – Khoa Toán Tin ĐHKHTN NNL – Khoa Toán Tin ĐHKHTN 89 90 SYMMARY SYMMARY • If your code is so complicated that it needs explaining with lots of internal or external documentation, • then the code should probably be rewritten • Write comments before or during writing the code, not after “Build it in, don’t add it on.” • The external documentation for a method should be sufficiently specific to exclude implementations that are unacceptable but sufficiently general to allow all implementations that are acceptable • Specify precisely all preconditions and postconditions for each of your methods in the external documentation These conditions form the contract for your method • Try to make your methods something appropriate in all cases so that there are no preconditions • Balance optimization needs with readability needs NNL – Khoa Toán Tin ĐHKHTN 91 NNL – Khoa Toán Tin ĐHKHTN 92

Ngày đăng: 02/12/2017, 00:00

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN