Message Channel class - - PowerPoint PPT Presentation

message channel
SMART_READER_LITE
LIVE PREVIEW

Message Channel class - - PowerPoint PPT Presentation

Message Channel class MessageChannelSimple Console StringProducer + readln() : String TestStringQ / MyQ + remove() : String TextGUI StringConsumer + write() : void


slide-1
SLIDE 1
slide-2
SLIDE 2

(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 ...

slide-3
SLIDE 3

(c) schmiedecke 06 Inf1-9b-Encapsulation 3

The Message Channel Shock

class MessageChannelComplete

Console + 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...

slide-4
SLIDE 4

(c) schmiedecke 06 Inf1-9b-Encapsulation 4

Comprehension Alarm!

  • We need structure rules to ensure

understandability:

  • Rules against Complexity!
slide-5
SLIDE 5
slide-6
SLIDE 6

(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
slide-7
SLIDE 7

(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
slide-8
SLIDE 8

(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

slide-9
SLIDE 9

(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

slide-10
SLIDE 10

(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

slide-11
SLIDE 11

(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

slide-12
SLIDE 12

(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

slide-13
SLIDE 13

(c) schmiedecke 06 Inf1-9b-Encapsulation 13

Generated HTML Documentation

slide-14
SLIDE 14

(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

slide-15
SLIDE 15

(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; } }

slide-16
SLIDE 16

(c) schmiedecke 06 Inf1-9b-Encapsulation 16

slide-17
SLIDE 17

(c) schmiedecke 06 Inf1-9b-Encapsulation 17

Step 2: Encapsulation

! "# $ %

slide-18
SLIDE 18

(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

slide-19
SLIDE 19

(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

slide-20
SLIDE 20

(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.

slide-21
SLIDE 21

(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 {}

slide-22
SLIDE 22

(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.
slide-23
SLIDE 23

(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.

slide-24
SLIDE 24

(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

slide-25
SLIDE 25

(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()); } }

slide-26
SLIDE 26

(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!

slide-27
SLIDE 27

(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.

slide-28
SLIDE 28

(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:
slide-29
SLIDE 29

(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;

slide-30
SLIDE 30

(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

slide-31
SLIDE 31

(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.

slide-32
SLIDE 32

(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(); } }

slide-33
SLIDE 33

(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); }

slide-34
SLIDE 34

(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 {...} }

slide-35
SLIDE 35

(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.

slide-36
SLIDE 36

(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)

slide-37
SLIDE 37

(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 }

slide-38
SLIDE 38

(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; }

slide-39
SLIDE 39

(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

slide-40
SLIDE 40

&&& #

☺ ☺ ☺

'()* # &