Message Channel class - - PowerPoint PPT Presentation
Message Channel class - - PowerPoint PPT Presentation
Message Channel class MessageChannelSimple Console StringProducer + readln() : String TestStringQ / MyQ + remove() : String TextGUI StringConsumer + write() : void
(c) schmiedecke 06 Inf1-9b-Encapsulation 2
Message Channel
class MessageChannelSimple
Console + readln() : String TextGUI + write() : void StringProducer StringConsumer TestStringQ / MyQ + remove() : String
... it looks simple enough ...
(c) schmiedecke 06 Inf1-9b-Encapsulation 3
The Message Channel Shock
class MessageChannelCompleteConsole + readln() : String TextGUI + write() : void StringProducer StringConsumer TestStringQ AnimatorThread «interface» Animate «interface» TextContainer + enter() : void + remove() : String MyQ EmptyException FullException Exception RuntimeException Start + main() : void
and that is still a tiny program...
(c) schmiedecke 06 Inf1-9b-Encapsulation 4
Comprehension Alarm!
- We need structure rules to ensure
understandability:
- Rules against Complexity!
(c) schmiedecke 06 Inf1-9b-Encapsulation 6
Step 1: Readable Code
- Code needs to follow conventions:
– ordering rules
- attributes – constructors – main - public methods – private
methods
– indentation and whitespace rules
- indent after an opening brace, unindent after a closing brace
- always leave a blank line between methods
- heavily indent line continuation
– naming and spelling rules
- use camelCase style for names
- only class names start with capital letter
- write constants in all-capitals
- used conjugated verb in modifiers
- use get/set and is/set for getters and setters
(c) schmiedecke 06 Inf1-9b-Encapsulation 7
... Readable Code
– code templates for certain constructs
- always use new line for conditional or loop body
- indent, even if single statement without braces
- put catch on same line as previous closing bracket
- always provide a standard constructor together with an
explicit constructor
- always import classes individually
– general styles for literals, exceptions, ...
- avoid using literals except in initializations
- avoid using String literals except in initializations
- never ignore an exception
– size rules for methods and classes
- a class must not have more than 20 public members
- a method must not be longer than 15 lines
(c) schmiedecke 06 Inf1-9b-Encapsulation 8
... Readable Code
– commenting rules
- always provide javadoc comments for classes
and public members
- use line comments for adding technical
explanations
(c) schmiedecke 06 Inf1-9b-Encapsulation 9
Readable Code
- Java Style Guides
– strictly enforced in professional projects – http://java.sun.com/docs/codeconv/html/CodeCon vTOC.doc.html – http://www.bluej.org/objects-first/styleguide.html – http://www.cwu.edu/~gellenbe/javastyle/
- Supported by IDEs
– in Eclipse, you can choose and modify the coding style – you can choose "edit-format"
- n a selecred code portion to
make Eclipse format it accor- ding to your coding style guide
(c) schmiedecke 06 Inf1-9b-Encapsulation 10
Documentation Requirements
- For every class:
– Author, Date – Overview, purpose
- for every method
– Author, Date – Overview, purpose – Exceptions: type, condition – Parameters: type, purpose, value set
- for attributes / groups of attributes
– Author, Date – Meaning, purpose, value set
(c) schmiedecke 06 Inf1-9b-Encapsulation 11
The Javadoc Tool
- command line tool javadoc.exe
- generates standard HTML documentation
– for a class – or a package (directory)
- precision adjustable:
– public – protected – package – private
- command:
javadoc –protected Singleton.java
- in eclipse:
– Project Generate Javadoc
(c) schmiedecke 06 Inf1-9b-Encapsulation 12
public class Singleton { private Singleton() {} private static Singleton instance; public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } }
Class Singleton
(c) schmiedecke 06 Inf1-9b-Encapsulation 13
Generated HTML Documentation
(c) schmiedecke 06 Inf1-9b-Encapsulation 14
Javadoc Comments
- Now "enrich" your javadoc documentation:
- javadoc adds comments to your documentation:
- comment markers /** .... */
- HTML text in between
- important Javadoc tags
(to be placed immediately before commented unit):
– @author – @exception – @param – @return – @see – @since – @throws – @version http://java.sun.com/j2se/javadoc/writingdoccomments/index.html
(c) schmiedecke 06 Inf1-9b-Encapsulation 15
/** class allows only one instace to be created. * @author smi 04 * @version 1.0 * */ public class Singleton { /** private constructor prevents external instantiation */ private Singleton() {} /** private filed instance for storing the single instance */ private static Singleton instance; /** public static method getInstance provides the only instance of * the class; if none exists, it is created here * * @author smi * @return instance of type Singleton */ pubic static Singleton getInstance() { if (instance == null) // create if necessary instance = new Singleton(); return instance; } }
(c) schmiedecke 06 Inf1-9b-Encapsulation 16
(c) schmiedecke 06 Inf1-9b-Encapsulation 17
Step 2: Encapsulation
! "# $ %
(c) schmiedecke 06 Inf1-9b-Encapsulation 18
Encapsulation in Every-Day life:
Enable Usage Without Detailed Knowledge I need not be a mechanic to drive a car I need not be an electronic engineer to turn on a tv set ... and non computer scientists are using computers all over the world It is normal to hide technical details from users
(c) schmiedecke 06 Inf1-9b-Encapsulation 19
Java: Two Levels of Encapsulation
- classes
– hide all private methods (algorithms) – and attributes (inner state)
- packages
– hide "technical" classes
(c) schmiedecke 06 Inf1-9b-Encapsulation 20
Package
Group of classes, not all of them public. Non-public classes only visible within the package. Packages can be nested. Class corresponds to file (same name) Package corresponds to directory (same name) Package statement (first line!) puts a class into a package: package mypackage; Classes without package statement belong to the default package.
(c) schmiedecke 06 Inf1-9b-Encapsulation 21
Classes and Packages
package bank; public class Account {} package bank.exchange; public class ExchangeRate { package bank.customers; public class Company {} package bank.customers; public class Customer {} package bank.estate; public class Appartment {} package bank; public class Credit {} package bank.exchange; public class Currency {}
(c) schmiedecke 06 Inf1-9b-Encapsulation 22
Files and Directories
Classpath:
- Classpath can contain several directories with the same name.
- A package can be distributed over several directory paths.
(c) schmiedecke 06 Inf1-9b-Encapsulation 23
Namespaces
- How many methods called getX exist in the Java
universe?
- How many getX methods are in your classpath?
(Think about libraries, e.g. cs101!)
- How many getX methods exist in your BallWorld
project (overridden methods)?
- All different – because they belong to different
classes
- A class is a namespace for its attributes and
methods.
(c) schmiedecke 06 Inf1-9b-Encapsulation 24
How many Date classes exist in the Java universe? How many Date classes exist in your classpath? Class namespace: package. classes have a fist and second name: pakagename.Class
- uterpackage.innerpackage.Class
Probable classes in your classpath: java.util.Date java.sql.Date java.util.List java.awt.List cs101.io.Console cs101ext.Console
Packages as Namespaces
(c) schmiedecke 06 Inf1-9b-Encapsulation 25
The import statement
- No mixing up possible:
public class Textleser { public int ganzzahlLesen() { java.util.List zahl = new java.util.List() ; char c = cs101ext.Console.read(); while (c>='0' && c<='9') { zahl.add(c); cs101ext.Console.read(); } return Integer.parseInt(zahl.toString()); } }
- Writing long package paths is tedious.
- import saves (ONLY!!!) writing effort!
import cs101.ext.Console; // first nam basis w.Console import java.util.List; // first name basis w. List public class Textleser { public int ganzzahlLesen() { List zahl = new List() ; char c = Console.read(); while (c>='0' && c<='9') { zahl.add(c); Console.read(); } return Integer.parseInt(zahl.toString()); } }
(c) schmiedecke 06 Inf1-9b-Encapsulation 26
Using imports
Remember:
- import does not change anything:
– neither visibility (in code) – nor reachability (in runtime environment)
- importing all classes of a package
import cs101.ext.*;
- does not import subpackages!.
import cs101.*; // not enough!
- conflicting imports:
import cs101.ext.*; import cs101.io.*;
- In case of conflict,
import is ignored.
import cs101.ext.*; import cs101.io.*; public class Importtest { public static void main(String[] a){ Console.println("HI"); } } // Error – Console cannot be resolved. import cs101.ext.*; import cs101.io.*; public class Importtest { public static void main(String[] a){ cs101.io.Console.println("HI"); } } // in case of ambiguity // use full package path!
(c) schmiedecke 06 Inf1-9b-Encapsulation 27
Default Import
You cannot write a Java program without standard libraries. The standard libraries are in the classpath by default. All standard library classes are in subpackages of java and javax. java.lang contains classes like System, String, Object, Integer, Math..., which are needed by every program. java.lang is imported by default. The Java Collections Framework is in the java.util package. Not imported by default use import statement.
(c) schmiedecke 06 Inf1-9b-Encapsulation 28
Using packages in the command shell
The AnimationGUI class has the following package statement: package animation.a1; The directory path consists of the program root path followed by the package path, e.g.
- Classpath:
Add program root path (without package path):
- Compilation:
Use program root path as working directory:
- Compile stating package path:
Execution: Use program root path as working directory:
- Execute stating package path:
(c) schmiedecke 06 Inf1-9b-Encapsulation 29
Package Visibility
public class Account {} public class Credit {} public class ExchangeRates {} class SolvencyAssurance {} class Marketing {} class ProfitControlling {} class InterestAdaption {} package bank;
(c) schmiedecke 06 Inf1-9b-Encapsulation 30
Controlled Visibility: Modifier
X X abstract X X X final X X static X X X private X X X X <default> X X X protected X X X X public Constructor Method Attribute Class
(c) schmiedecke 06 Inf1-9b-Encapsulation 31
Modifier:
- public:
unlimited usage / instantiation
- protected:
usage restricted to subclasses – unlimited within own package -
- <default>
unlimited within package, invisible outside
- private:
invisible outside class
(visible within other instances of same class)
- final:
class cannot be extended, method cannot be overridden, variable cannot be changed.
(c) schmiedecke 06 Inf1-9b-Encapsulation 32
Class interfaces
public class TopClass { public void forAll(); protected void forHeirs(); private void secret(); public class User { public void meth() { new TopClass().forAll(); } } public class Heir extends TopClass { public void meth() { this.forAll(); this.forHeirs(); } }
(c) schmiedecke 06 Inf1-9b-Encapsulation 33
Getter and Setter
- avoid public attributes
- rather export getter and setter methods:
public class Person { // Attributes (fields) private String name, firstName, address; private int age; // Access methods ("getters and setters" public String getName(); public void setName(String name); public String getAddress(); public void setAddress(String address); public int getAge(); public void setAge(int age); }
(c) schmiedecke 06 Inf1-9b-Encapsulation 34
Why Getter and Setter?
- can be used polymorphically and in interfaces
- hide implementation details
- avoid illegal states
public class Person { // Attributes (fields) private String name, firstName, address; private int alter; // Access methods("getter and setter" public String getName() { // concatenates name and firstName } public void setName(String name) { // separates name and firstName } public void setAge(int age) throws TooYoungException {...} }
(c) schmiedecke 06 Inf1-9b-Encapsulation 35
Private constructors
- private constructors prevent instantiation from
- utside the class:
– utility classes with only static methods and attributes – instances need a certain context (iterator) – Avoid multiple instances ("Singleton") public class Singleton { private static Singleton instance; public static Singleton getInstance(){ if (instance == null) instance = new Singleton(); return instance; } }
Attention: Subclasses cannot be instantiated either.
A protected constructor mends this.
(c) schmiedecke 06 Inf1-9b-Encapsulation 36
Private Methods
- procedural abstraction
- Methods with 16 and more lines are
– badly comprehendable – badly changeable
- Divide into private procedures
– for internal use only – may use local context knowledge – need not be robust (protected against inadequate usage)
(c) schmiedecke 06 Inf1-9b-Encapsulation 37
Exampe BinSearch
public int search(Vehicle vh) { int min = 0, max = numCars - 1; while (min <= max) { int middle = (min + max) / 2; Vehicle vhmid = vehicles[middle]; if (vhmid.larger(vh)) max = middle – 1; else if (vh.eq(vhm)) return middle; else min = middle + 1; } return –1; // not found }
(c) schmiedecke 06 Inf1-9b-Encapsulation 38
Example BinSearch: readable Version
public int search(Vehicle vh) { int min = 0, max = numCars – 1, middle; while (min <= max) { findMiddle(); Vehicle vhmid = vehicles[middle]; if (vhmid.larger(vh)) searchTop(); else if (vhmid.eq(vh)) return mitte; else searchBottom(); } return –1; // not found }
private void findMiddle() { middle = (min + max) / 2; } private void searchTop() { max = middle – 1; } private void searchBottom() { min = middle + 1; }
(c) schmiedecke 06 Inf1-9b-Encapsulation 39
Procedural Abstraction
- procedures reduce complexity:
– length – loop nesting – complex algorithms
- Put into a private procedure, if
– describable – repeated
- Worried about efficiency?
compiler will often use inline replacement
&&& #
- ☺
☺ ☺ ☺
'()* # &