Скачать презентацию JAVA course structure Code Style code conventions Скачать презентацию JAVA course structure Code Style code conventions

java-course-lec-05.pptx

  • Количество слайдов: 76

JAVA course structure Code Style • code conventions • patterns JAVA course structure Code Style • code conventions • patterns

JAVA code style Why Have Code Conventions • 80% of the lifetime cost of JAVA code style Why Have Code Conventions • 80% of the lifetime cost of a piece of software goes to maintenance • hardly any software is maintained for its whole life by the original author • code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly • if you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create maintenance ~ 80% cost

JAVA code style Common source file structure • beginning comments (license, etc) • package JAVA code style Common source file structure • beginning comments (license, etc) • package and import statements • class/interface documentation comment • class or interface statement • class/interface implementation comment, if necessary • class (static) variables • instance variables • constructors • methods

JAVA code style Class (static) variables order • public class variables • protected • JAVA code style Class (static) variables order • public class variables • protected • package level (no access modifier) • private ORDER ! Instance variables order • public • protected • package level (no access modifier) • private ORDER ! Constructors Methods Should be grouped by functionality rather than by scope or accessibility. The goal is to make reading and understanding the code easier.

JAVA code style Indentation Unit: Tabs: 4 spaces 8 spaces (not 4) Line length JAVA code style Indentation Unit: Tabs: 4 spaces 8 spaces (not 4) Line length • Original requirement: not longer than 80 characters (not handled well by many terminals and tools) • Be rational and don’t exceed boundaries

JAVA code style Wrapping lines (general principles) • break after a comma • break JAVA code style Wrapping lines (general principles) • break after a comma • break before an operator • prefer higher-level breaks to lower-level breaks • align the new line with the beginning of the expression at the same level on the previous line • if the above rules lead to confusing code, just indent 8 spaces instead Examples some. Method(long. Expression 1, long. Expression 2, long. Expression 3, T A B long. Expression 4, long. Expression 5); var = some. Method 1(long. Expression 1, some. Method 2(long. Expression 2, long. Expression 3)); Arithmetic expressions long. Name 1 = long. Name 2 * (long. Name 3 + long. Name 4 - long. Name 5) + 4 * longname 6; // PREFER T A B long. Name 1 = long. Name 2 * (long. Name 3 + long. Name 4 - long. Name 5) + 4 * longname 6; T A B // AVOID

JAVA code style Wrapping lines (general principles) Method declarations // CONVENTIONAL INDENTATION some. Method(int JAVA code style Wrapping lines (general principles) Method declarations // CONVENTIONAL INDENTATION some. Method(int an. Arg, Object another. Arg, String yet. Another. Arg, Object and. Still. Another) {. . . } //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS private static synchronized horking. Long. Method. Name(int an. Arg, Object another. Arg, String yet. Another. Arg, T A B Object and. Still. Another) {. . . } // VARIANT private static synchronized horking. Long. Method. Name(int an. Arg, T A B Object another. Arg, String yet. Another. Arg, Object and. Still. Another) {. . . }

JAVA code style Wrapping lines (general principles) If statements (should generally use the 8 JAVA code style Wrapping lines (general principles) If statements (should generally use the 8 -space rule) // DON'T USE THIS INDENTATION if ((condition 1 && condition 2) || (condition 3 && condition 4) ||!(condition 5 && condition 6)) { //BAD WRAPS do. Something. About. It(); //MAKE THIS LINE EASY TO MISS } // USE THIS INDENTATION INSTEAD if ((condition 1 && condition 2) || (condition 3 && condition 4) ||!(condition 5 && condition 6)) { do. Something. About. It(); } // OR USE THIS if ((condition 1 && condition 2) || (condition 3 && condition 4) ||!(condition 5 && condition 6)) { do. Something. About. It(); }

JAVA code style Wrapping lines (general principles) Ternary expressions alpha = (a. Long. Boolean. JAVA code style Wrapping lines (general principles) Ternary expressions alpha = (a. Long. Boolean. Expression) ? beta : gamma;

JAVA code style Block comments • Used for • descriptions of files • methods JAVA code style Block comments • Used for • descriptions of files • methods • data structures • algorithms • Should be indented to the same level as the code they describe. • Should be preceded by a blank line to set it apart from the rest of the code. [BLANK LINE] /* * Here is a block comment with some very special formatting * * one * two * three */

JAVA code style Single line comments • Should be indented to the level of JAVA code style Single line comments • Should be indented to the level of the code that follows. • If a comment can't be written in a single line, it should follow the block comment format. • A single-line comment should be preceded by a blank line. [BLANK LINE] if (condition) { [BLANK LINE] /* Handle the condition. */. . . } Trailing comments • Should be shifted far enough to separate them from the statements. • If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. if (a == 2) { return TRUE; } else { return is. Prime(a); } /* special case */ /* works only for odd a */

JAVA code style End of line comments • Shouldn't be used on consecutive multiple JAVA code style End of line comments • Shouldn't be used on consecutive multiple lines for text comments. if (foo > 1) { // Do a double-flip. . } else { return false; } // Explain why here. • Can be used in consecutive multiple lines for commenting out sections of code. //if (bar > 1) { // // // Do a triple-flip. //. . . //} //else { // return false; //}

JAVA code style Documentation comments • Describe Java classes, interfaces, constructors, methods, and fields. JAVA code style Documentation comments • Describe Java classes, interfaces, constructors, methods, and fields. • Each doc comment is set inside the comment delimiters /**. . . */. • Should appear just before the declaration. /** * The Example class provides. . . */ public class Example {. . . Notes The first line of doc comment (/**) for classes and interfaces is not indented; subsequent doc comment lines each have 1 space of indentation (to vertically align the asterisks). Details about the implementation of a class should go into an implementation block comment following the class statement, not in the class doc comment.

JAVA code style Declarations (style & initialization) • One declaration per line is recommended JAVA code style Declarations (style & initialization) • One declaration per line is recommended since it encourages commenting: int level; // indentation level int size; // size of table !!! is preferred over int level, size; // this is BAD • Do not put different types on the same line: int foo, fooarray[]; // WRONG! !!! NOTE The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e. g. : int Object NOTE level; size; current. Entry; // indentation level // size of table // currently selected table entry Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

JAVA code style Declarations (placement) • Put declarations only at the beginning of blocks: JAVA code style Declarations (placement) • Put declarations only at the beginning of blocks: void my. Method() { int 1 = 0; if (condition) { int 2 = 0; . . . } } // beginning of method block // beginning of "if" block • Don't wait to declare variables until their first use, it can confuse the unwary programmer and reduce code portability. The one exception to the rule is indexes of for loops: for (int i = 0; i < max. Loops; i++) {. . . } • Avoid local declarations that hide declarations at higher levels: int count; . . . my. Method() { if (condition) { int count = 0; . . . } } // AVOID!

JAVA code style Class & interface declarations • No space between a method name JAVA code style Class & interface declarations • No space between a method name and the parenthesis. • Open brace "{" appears at the end of the same line as the declaration. • Closing brace "}" starts a line by itself indented to match its corresponding opening statement. class Sample extends Object { int ivar 1; int ivar 2; Sample(int i, int j) { ivar 1 = i; ivar 2 = j; }. . . } • Methods are separated by a blank line

JAVA code style Simple statements Each line should contain at most one statement: argv++; JAVA code style Simple statements Each line should contain at most one statement: argv++; // Correct argc--; // Correct argv++; argc--; // AVOID! !!! Compound statements • These are statements that contain lists of statements enclosed in braces "{ statements }“. • The enclosed statements should be indented one more level than the compound statement. • The opening brace should be at the end of the line that begins the compound statement. • The closing brace should begin a line and be indented to the beginning of the compound statement. • Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces. !!!

JAVA code style if, if-else, if else-if-else statements if (condition) { statements; } else JAVA code style if, if-else, if else-if-else statements if (condition) { statements; } else { statements; } Note: if statements always use braces, {}. Avoid the following error-prone form: if (condition) statement; //AVOID! THIS OMITS THE BRACES {}! !!!

JAVA code style Cycle statements for (initialization; condition; update) { statements; } An empty JAVA code style Cycle statements for (initialization; condition; update) { statements; } An empty for statement should have the following form: for (initialization; condition; update); while (condition) { statements; } while (condition); do { statements; } while (condition);

JAVA code style Switch statements Should have the following form: switch (condition) { case JAVA code style Switch statements Should have the following form: switch (condition) { case ABC: statements; /* falls through */ case DEF: statements; break; case XYZ: statements; break; default: statements; break; } Every time a case falls through (doesn't include a break statement), add a comment where the break statement would normally be. (/* falls through */ comment. ) Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.

JAVA code style White spaces | blank lines Blank lines improve readability by setting JAVA code style White spaces | blank lines Blank lines improve readability by setting off sections of code that are logically related. Two blank lines should always be used in the following circumstances: • Between sections of a source file • Between class and interface definitions One blank line should always be used in the following circumstances: • Between methods • Between the local variables in a method and its first statement • Before a block or single-line comment • Between logical sections inside a method to improve readability

JAVA code style White spaces | blank spaces • A keyword followed by a JAVA code style White spaces | blank spaces • A keyword followed by a parenthesis should be separated by a space: while (true) {. . . } • Blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls. • A blank space should appear after commas in argument lists. • All binary operators except “. ” should be separated from their operands by spaces. • Blank spaces should never separate unary operators "++” and “--” from operands. a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } print. Size("size is " + foo + "n"); • The expressions in a for statement should be separated by blank spaces for (expr 1; expr 2; expr 3) • Casts should be followed by a blank space. Examples: my. Method((byte) a. Num, (Object) x, (int) (cp + 5));

JAVA code style Naming Variable names should be short yet meaningful. The choice of JAVA code style Naming Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are: i, j, k, m and n for integers; c, d and e for characters. int char float i; c; my. Width; The names of variables declared class constants should be all uppercase with words separated by underscores ("_"): static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1;

JAVA code style Practices Variables access Don't make any instance or class variable public JAVA code style Practices Variables access Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten. One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior (like struct in c/c++). Referring to Class Variables and Methods Avoid using an object to access a class (static) variable or method. Use a class name instead. For example: class. Method(); AClass. class. Method(); an. Object. class. Method(); //OK // AVOID! Constants Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values. !!!

JAVA code style Practices Variable Assignments • Avoid assigning several variables to the same JAVA code style Practices Variable Assignments • Avoid assigning several variables to the same value in a single statement. It is hard to read: foo. Bar. f. Char = bar. Foo. lchar = 'c'; // AVOID! • Do not use the assignment operator in a place where it can be easily confused with the equality operator. if (c++ = d++) {. . . } // AVOID! (Java disallows) Should be written as: if ((c++ = d++) != 0) {. . . } • Do not use embedded assignments: d = (a = b + c) + r; Should be written as: a = b + c; d = a + r; // AVOID! !!!

JAVA code style Practices Parentheses It is generally a good idea to use parentheses JAVA code style Practices Parentheses It is generally a good idea to use parentheses in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others: if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // RIGHT !!! Returning values Try to make the structure of your program match the intent: if (boolean. Expression) { return true; } else { return false; } Similarly, if (condition) { return x; } return y; Should instead be written as: return boolean. Expression; Should be written as return (condition ? x : y);

JAVA course structure Various • code conventions • Go. F JAVA course structure Various • code conventions • Go. F

JAVA patterns “Design Patterns: Elements of Reusable Object-Oriented Software”, The original publication date was JAVA patterns “Design Patterns: Elements of Reusable Object-Oriented Software”, The original publication date was October 21, 1994. Authors • Erich Gamma • Richard Helm • Ralph Johnson • John Vlissides • with foreword by Grady Booch Over 40 re-printings… Over 500, 000 copies… Go. F Gang of Four

JAVA patterns What the pattern is the pattern name is a handle we can JAVA patterns What the pattern is the pattern name is a handle we can use to describe a design problem, Go. F: its solutions, and consequences in a word or two. Naming a pattern immediately increases our design vocabulary. It lets us design at a higher level of abstraction. Having a vocabulary for patterns lets us talk about them with our colleagues, in our documentation, and even to ourselves. It makes it easier to think about designs and to communicate them and their trade-offs to others. Finding good names has been one of the hardest parts of developing our catalog.

JAVA patterns Common principles • Maximize cohesion and minimize coupling • Abstract coupling or JAVA patterns Common principles • Maximize cohesion and minimize coupling • Abstract coupling or Program to an interface, not an implementation

JAVA patterns Law of Demeter Requires for a method m of an object O JAVA patterns Law of Demeter Requires for a method m of an object O may only invoke the methods of the following kinds of objects: • O itself • m's parameters • any objects created/instantiated within m • O's direct component objects • a global variable, accessible by O, in the scope of m For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. But it may also result in having to write many wrapper methods to propagate calls to components; in some cases, this can add noticeable time and space overhead.

JAVA patterns Patterns by Type Creational patterns are ones that create objects for you, JAVA patterns Patterns by Type Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case. Structural These concern class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality. Behavioral Most of these design patterns are specifically concerned with communication between objects.

JAVA patterns Creational patterns JAVA patterns Creational patterns

JAVA patterns Abstract Factory Essence Provide an interface for creating families of related or JAVA patterns Abstract Factory Essence Provide an interface for creating families of related or dependent objects without specifying their concrete classes. • Factory returns an abstract pointer to the created concrete object. • Client code uses Factory and has no knowledge of the concrete type, not needing to include any class declarations (deals only with the abstract type). Advantages • No need to modify every location in client code where new objects are created in case of new concrete classes (or other modifications). Example JAXP (java api for xml processing): • there are several different xml parsers • each parser implements the same parsing API • abstract factory initializes and returns the appropriate parser • client has access to abstract factory

JAVA course structure Abstract Factory JAVA course structure Abstract Factory

JAVA course structure Abstract Factory JAVA course structure Abstract Factory

JAVA course structure Factory method Essence Defines an interface for creating an object, but JAVA course structure Factory method Essence Defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses. Problem Creating an object often requires complex processes not appropriate to include within a composing object. Solution The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of object that will be created. Note Abstract Factory consist of factory methods.

JAVA patterns Factory method JAVA patterns Factory method

JAVA patterns Builder Essence Solution to the telescoping constructor anti-pattern. * The telescoping constructor JAVA patterns Builder Essence Solution to the telescoping constructor anti-pattern. * The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Solution Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once. Notes • Often, designs start out using Factory Method and evolve toward Abstract Factory, Prototype, or Builder as the designer discovers where more flexibility is needed. • Sometimes creational patterns are complementary, Builder can use one of the other patterns to implement which components are built.

JAVA paterns Builder Example // telescoping constructor new Product(a, b, c, d, e, f, JAVA paterns Builder Example // telescoping constructor new Product(a, b, c, d, e, f, g, h, …); Builder builder = …; builder. set. A(); … builder. set. H(); builder. get. Result();

JAVA course structure Singleton Restricts the instantiation of a class to only one object. JAVA course structure Singleton Restricts the instantiation of a class to only one object. Advantages Useful when exactly one object is needed to coordinate actions across the system. Criticism Sometimes considered as anti-pattern, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application. Example public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton get. Instance() { return instance; } }

JAVA patterns Structural patterns JAVA patterns Structural patterns

JAVA course structure Adapter Used when there is a need for two different classes JAVA course structure Adapter Used when there is a need for two different classes with incompatible interfaces to work together. Interfaces may be incompatible but the inner functionality should suit the need. Object adapter Class adapter

JAVA course structure Adapter Used when there is a need for two different classes JAVA course structure Adapter Used when there is a need for two different classes with incompatible interfaces to work together. Interfaces may be incompatible but the inner functionality should suit the need. Sequence diagram

JAVA course structure Composite Essence Describes that a group of objects are to be JAVA course structure Composite Essence Describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose“ objects into tree structures to represent part-whole hierarchies. Advantages Implementing the composite pattern lets clients treat individual objects and compositions uniformly. Diargam

JAVA course structure Decorator Essence Allows behavior to be added to an individual object, JAVA course structure Decorator Essence Allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. Diagram

JAVA course structure Decorator Notes • Multiple decorators can be stacked on top of JAVA course structure Decorator Notes • Multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s). • Alternative to subclassing (subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects). Example

JAVA course structure Decorator Essence Allows behavior to be added to an individual object, JAVA course structure Decorator Essence Allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. Diagram

JAVA course structure Façade Essence Provides a simplified interface to a larger body of JAVA course structure Façade Essence Provides a simplified interface to a larger body of code, such as a class library. Advantages • make a software library easier to use, understand test, since the facade has convenient methods for common tasks • make the library more readable, for the same reason • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system • wrap a poorly designed collection of api with a single well-designed api.

JAVA course structure Façade Sequence diagram (example) JAVA course structure Façade Sequence diagram (example)

JAVA course structure Façade Diagram (example) JAVA course structure Façade Diagram (example)

JAVA patterns Proxy Essence Provide a surrogate or placeholder for another object to control JAVA patterns Proxy Essence Provide a surrogate or placeholder for another object to control access to it. Common situations in which the Proxy pattern is applicable • A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests/accesses the object. • A remote proxy provides a local representative for an object that resides in a different address space (“stub” code in RPC and CORBA). • A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request. • A smart proxy interposes additional actions when an object is accessed. Typical uses include: • Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer), • Loading a persistent object into memory when it’s first referenced, • Checking that the real object is locked before it is accessed to ensure that no other object can change it.

JAVA patterns Proxy Diagram Sequence diagram (example) JAVA patterns Proxy Diagram Sequence diagram (example)

JAVA patterns Structural patterns review Adapter Converts one interface to another so that it JAVA patterns Structural patterns review Adapter Converts one interface to another so that it matches what the client is expecting Decorator Dynamically adds responsibility to the interface by wrapping the original code Façade Provides a simplified interface Proxy Provide a surrogate or placeholder for another object to control access to it

JAVA patterns Behavioral patterns JAVA patterns Behavioral patterns

JAVA course structure Chain of responsibility Essence Avoid coupling the sender of a request JAVA course structure Chain of responsibility Essence Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Details Each processing object contains logic that defines the types of command objects it can handle, the rest are passed to the next processing object in the chain. Variation In a variation of the standard chain-of-responsibility model, some handlers may act as dispatchers, capable of sending commands out in a variety of directions, forming a tree of responsibility.

JAVA course structure Chain of responsibility Diagram JAVA course structure Chain of responsibility Diagram

JAVA course structure Command Essence An object is used to represent and encapsulate all JAVA course structure Command Essence An object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes: • the method name • the object that owns the method • values for the method parameters Terms • command • receiver • invoker • client has a receiver object and invokes a method of the receiver in a way that is specific to that receiver's class does the work invokes the command contains the decision making about which commands to execute at which points. To execute a command, it passes the command object to the invoker object Notes Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the class of the method or the method parameters.

JAVA patterns Command Sequence diagram (sample) JAVA patterns Command Sequence diagram (sample)

JAVA patterns Iterator Essence Provides a way to access the elements of a collection JAVA patterns Iterator Essence Provides a way to access the elements of a collection object sequentially without a need to expose it’s implementation details. Decouples algorithms from containers. Advantages Abstracts the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each structure transparently.

JAVA patterns Iterator Diagram interface List: Iterator<E> iterator(); Implementations (own iterators): Array. List. iterator(); JAVA patterns Iterator Diagram interface List: Iterator iterator(); Implementations (own iterators): Array. List. iterator(); Linked. List. iterator(); …

JAVA course structure Mediator Essence Defines an object that encapsulates how a set of JAVA course structure Mediator Essence Defines an object that encapsulates how a set of objects interact. Notes • Communication between objects is encapsulated with a mediator object. • Objects no longer communicate directly with each other. • Reduces the dependencies between communicating objects (lowering the coupling). Diagram

JAVA course structure Mediator Essence Defines an object that encapsulates how a set of JAVA course structure Mediator Essence Defines an object that encapsulates how a set of objects interact. Example

JAVA patterns Observer Essence Pattern in which an object, called the subject, maintains a JAVA patterns Observer Essence Pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes. Notes • Mainly used to implement distributed event handling systems. • It’s also a key part in the familiar (MVC) architectural pattern. • Implemented in numerous programming libraries and systems, including almost all GUI toolkits. Diagram

JAVA patterns Observer Essence Pattern in which an object, called the subject, maintains a JAVA patterns Observer Essence Pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes. Example

JAVA course structure Strategy Essence Define a family of algorithms, encapsulate each one, and JAVA course structure Strategy Essence Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it. Notes For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, and/or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. Diagram

JAVA course structure Strategy Essence Define a family of algorithms, encapsulate each one, and JAVA course structure Strategy Essence Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it. Example

JAVA course structure Visitor Essence Represent an operation to be performed on the elements JAVA course structure Visitor Essence Represent an operation to be performed on the elements of an object structure. Notes Many distinct and unrelated operations need to be performed on node objects in a heterogeneous aggregate structure. You want to avoid “polluting” the node classes with these operations. And, you don’t want to have to query the type of each node and cast the pointer to the correct type before performing the desired operation. Diagram

JAVA course structure Visitor Essence Represent an operation to be performed on the elements JAVA course structure Visitor Essence Represent an operation to be performed on the elements of an object structure. Example

JAVA course structure Code Style • code conventions • patterns • examples of bad JAVA course structure Code Style • code conventions • patterns • examples of bad code

JAVA bad code From the internet… catch (Exception e ) {} JAVA bad code From the internet… catch (Exception e ) {}

JAVA bad code From the internet… class Singletons { public static final My. Exception JAVA bad code From the internet… class Singletons { public static final My. Exception my. Exception = new My. Exception(); } class Test { public void do. Something() throws My. Exception { throw Singletons. my. Exception; } }

JAVA bad code From the internet… if (expensive. Function() > a. Var) { a. JAVA bad code From the internet… if (expensive. Function() > a. Var) { a. Var = expensive. Function(); } for (int i=0; i < expensive. Function(); ++i) { System. out. println(expensive. Function()); }

JAVA bad code From the internet… if () { if () {. . JAVA bad code From the internet… if () { if () {. .

JAVA bad code From the internet… try { j = 0; while(true) { array[j] JAVA bad code From the internet… try { j = 0; while(true) { array[j] = [some calculations]; j++; } } catch(Exception e) {}

JAVA course structure FIN JAVA course structure FIN