+ All Categories
Home > Engineering > Object-Oriented Children

Object-Oriented Children

Date post: 15-Jan-2015
Category:
Upload: kenji-hasunuma
View: 1,220 times
Download: 0 times
Share this document with a friend
Description:
 
Popular Tags:
46
Object-Oriented Children HASUNUMA Kenji GlassFish Community [email protected] Twitter: @khasunuma
Transcript

Object-Oriented Children

HASUNUMA KenjiGlassFish Community

[email protected]: @khasunuma

Object is ...

• Something responds to specified messages.

• Defined by following elements;

• representation (a.k.a. data set)

• operators (e.g. accessors, actions)

• relationship with other objects

Case #1Java Collections Frameworkwith Stream API

Provides the separation of algorithms and data structure.

Algorithm and Data structures

Basic concepts

Algorithm Data structures

Basic concepts

Algorithm Data structures

Collections CollectionMap

Data structures

Collection<E> Map<K, V>

Set<E> List<E> Queue<E>

Deque<E>Elements are • Unordered • No duplicate • Sequential Access

key and value pairs (Hash variable)

Elements are • Ordered • May duplicate • Random Access Elements are

• Ordered • May duplicate • Sequential Access

Collection of values

Set List<E> Deque Map

Hash Table HashSet -- -- HashMap

Resizable Array -- ArrayList ArrayDeque --

Balanced Tree TreeSet -- -- TreeMap

Linked List -- LinkedList LinkedList --

Hash Table+

Linked ListLinked

HashSet -- -- LinkedHashMap

Hash TableSequantial Access SlowRandom Access Fastest

Insert/Delete Fastest

Resizable Array

Sequantial Access Fast (size dependent)Random Access Fast (size dependent)

Insert/Delete Slow

Balanced Tree

Sequantial Access MediumRandom Access Medium

Insert/Delete Fast (constant)

Linked ListSequantial Access Fast (size dependent)Random Access Slow

Insert/Delete Fast (size dependent)

Methods of Collection<E>• boolean add(E e) • void clear() • boolean isEmpty() • boolean remove(Object o) • int size() • <T> T toArray(T[] a)

Additional methods of List<E>• boolean add(int index, E element) • E get(int index) • int indexOf(Object o) • int lastIndexOf(Object o) • int remove(int index) • E set(int index, E element)

For Random Access

Algorithm : CollectionsProvides general algorithms for Collection and Map

• Sort and shuffle elements (List)

• Reverse, fill and copy elements (List)

• Binary search (List)

• Minimum, maximum and frequency of elements

• Create synchronized or read only collection

• and more...

Basic concepts

Algorithm Data structures

Collections CollectionMap

Basic concepts

Algorithm Data structures

Collections CollectionMapStream

Collection and Stream API

Collection Streamstream()

collect()Data structure Operators for whole collection

Terminal Operations

<<Export>>

<<Import>>

Stream as Set operators(intermediate operations)

Method Role as Set operator

filter condition

map mapping values (a.k.a. production)

distinct reducing duplication

sorted sorting values

concat union with another set

limit truncation of values

Stream as Set operators(terminal operations)

Method Role as Set operatorreduce general purpose totaling

min minimum of valuesmax maximum of values

count count of valuesanyMatch whether any values match conditionallMatch whether all values match condition

noneMatch whether no value match condition

// Example // Create a view from the result of Twitter4J !Twitter twitter = TwitterFactory.getSingleton(); !

// snip !QueryResult result = twitter.search(query); List<Status> statuses = result.getTweets(); !List<Tweet> tweets =

statuses.stream() // to Stream (Set operations)

.filter(s -> s.getCreateAt().after(SOME_DAY))

.map(Tweet::new) // Convert Status to Tweet

.distinct() // Maybe, Stream has duplicates

.sort() // Sort by default order (prepare)

.limit(10) // Restrict 10 values from head

.collect(Collectors.toList); // List<Tweet>

Case #2JSR 310: Date and Time API

Provides human friendly representation and operators.

Time system (ISO 8601)

timetime-pointtime-pointtime-point

(epoch)

date date

period

Time system (JSR 310)

ClockInstantInstantInstant

(epoch)

Temporal (e.g. LocalDate)

PeriodDuration

Temporal (e.g. LocalDate)

Abstraction of time system1. Instant behaves as a time-point that has enough

resolution (nano-seconds unit) to use as seem as the linear scale.

2. Clock provides Instant that may be independent from the system clock. It partially behaves as the time axis.

3. Temporal is base interface of date and time, i.e., LocalDate, ZonedDateTime. That is mapped to ISO 8601 definitions.

Instant and Clock

Clock

Instant

UtcInstant TaiInstant

instant()

of() of()toInstant()

ThreeTen-Extra

w/o Leap Second (Exactly)

w/ Leap Second (Exactly)

It’s called from some convenient methods, i.e. LocalDate.now()

It may be independent from the System Clock

Representation of a time-point (The structure is hidden)

Temporal• Time system is complex so much.

• Java Language Specification lacks some object-oriented features to represent temporals ideally.

• Temporals and their relationship are defined by many overload methods and unified naming rules instead of using inheritance.

• Inheritance is adapt to mainly implementation of extension points, e.g. Chronology.

Date and Time classes

Class Field Time zone ISO 8601 Chrono.

LocalDate Date N/A compatible enable

LocalDateTime Date + Time N/A compatible enable

LocalTime Time N/A compatible N/A

OffsetDateTime Date + Time offset compatible disable

OffsetTime Time offset compatible N/A

ZonedDateTime Date + Time zone id extended enable

Date and Time conversions

Date and Time conversionsOper. Description

of-Create from fields. e.g. LocalDate today = LocalDate.of(2014, 5, 18); // today.toString() : “2014-05-18”

at-Expand with fields. e.g. LocalDateTime current = today.atTime(13:30); // current.toString() : “2014-05-18T13:30:00”

to-Truncate fields. e.g. LocalDate someday = current.toLocalDate(); // someday.toString() : “2014-05-18”

Date and Time operatorsOper. Description

isBefore isEqual isAfter

Compare with other date/time. e.g. LocalDate today = LocalDate.of(2014, 5, 18); boolean b = today.isAfter(LocalDate.of(2014, 5, 22)); // b == true

plus- minus-

Add/subtract field value. e.g. LocalDate tomorrow = today.plusDays(2); // tomorrow.toString() : “2014-05-20”

isLeapYearVerify a date is leap year. e.g. boolean leap = today.isLeapYear(); // leap == false

Date and Time formattingMethod Description

toString()Format using default formatter. e.g. String s = today.toString(); // s : “2014-05-18”

format(DateTimeFormatter f) Format using custom formatter. e.g. String s = today.format(formatter);

parse(String s)Parse using default formatter. e.g. LocalDate d = LocalDate .parse(“2014-05-18”);

parse(String s, DateTimeFormatter f)

Parse using custom formatter. e.g. LocalDate d = LocalDate .parse(“2014-05-18”, formatter);

ChronologyTemporal

ChronoLocalDateChronoLocalDateTime<D> ChronoZonedDateTime<D>

LocalDateLocalDateTime ZonedDateTimeJapaneseDate

MinguoDate

ThaiBuddhistDate

HijrahDate

Same as ChronoLocalDateTime

<LocalDate>

Same as ChronoZonedDateTime

<LocalDate>

Chronology supports

Chronology Era ChronoLocalDateIsoChronology IsoEra LocalDate

JapaneseChronology JapaneseEra JapaneseDateMinguoChronology MinguoEra MinguoDate

ThaiBuddhistChronology ThaiBuddhistEra ThaiBuddhistDateHijrahChronology HijrahEra HijrahDateCopticChronology CopticEra CopticDateJulianChronology JulianEra JulianDate

Remarks: Coptic and Julian are extension of ThreeTen-Extra

Case #3JSR 363: Units of Measurement API

Provides the representation and operators based on human scale units.

History of "Unit-API"

• JSR 108: Units Specification (2001) -- Withdrawn in 2004

• JSR 275: Units Specification (2005) -- Public Review rejected in 2010

• JSR 363: Units of Measurement API (2014) -- JSR Review accepted at 2014-04-08

Measurement

• Consists of value and unit.

• Provides arithmetic operations; add, subtract, multiply, divide and inverse.

• Converts unit and adjusts value with it.

• Supports derived unit.

Measurement and Quantity

Measurement<Q, V>

Quantity<Q>

MassLength Time ElectricCurrent[m] [kg] [s] [A]

and more...

Unit

Implementation of Unit and contains following;

• Symbol (e.g. "kg")

• Quantity (e.g. Mass)

• Dimension (e.g. QuantityDimension.MASS)

• and more...

SystemOfUnits

Provides unit(s) following ways;

• by Quantity

• by Dimension

• whole system of units

e.g. SI (SI units), US (Yard, Pound, Inch, ...)

SI (SI base units)Unit Symbol Dimension Quantity

METRE m LENGTH Length

KIROGRAM kg MASS Mass

SECOND s TIME Time

AMPARE A ELECTRIC_CURRENT ElectricCurrent

KELVIN K TEMPERATURE Temperature

CANDERA cd LUMINOUS_INTENSITY LuminousIntensity

MOLE mol AMOUNT_OF_SUBSTANCE AmountOfSubstance

SI (SI derived units)Unit Symbol Dimension Quantity

ONE - - Dimensionless

RADIAN rad ONE Angle

STERADIAN st ONE SolidAngle

BIT bit ONE Information

HERTZ Hz ONE / SECOND Frequency

NEWTON N METRE * KIROGRAM / SECOND Force

PASCAL Pa NEWTON / METRE Pressure

JOULE J NEWTON * METRE Energy

WATT W JOULE / SECOND Power

SI (SI derived units)Unit Symbol Dimension Quantity

AMPARE_TUNE At AMPARE MagnetomotiveForce

COULOMB C SECOND * AMPARE ElectricCharge

VOLT V WATT / AMPARE ElectricPotential

FARAD F COULOMB / VOLT ElectricCapacitance

OHM Ohm VOLT / AMPARE ElectricResistance

SIEMENS S AMPARE / VOLT ElectricConductance

WEBER Wb VOLT * SECOND MagneticFlux

TESLA T WEBER / METRE MagneticFluxDensity

HENRY H WEBER / AMPARE ElectricInductance

SI (SI derived units)Unit Symbol Dimension Quantity

LUMEN lm CANDELA * STERADIAN LuminousFlux

LUX lx LUMEN / METRE Illuminance

BECQUEREL Bq ONE / SECOND Radioactivity

GRAY Gy JOULE / KIROGRAM RadiationDoseAbsorbed

SIEVELT Sv JOULE / KIROGRAM RadiationDoseEffective

GRAM g KIROGRAM / 1000 Mass

CELCIUS - KELVIN - 273.15 Temperature

KATAL kat MOLE / SECOND CatalysticActivity

SIPrefix• SIPrefix declares following prefixes;

• YOTTA(1024), ZETTA(1021), EXA(1018), PETA(1015), TERA(1012), GIGA(109), MEGA(106), KIRO(103), HECTO(102), DEKA(101)

• DECI(10-1), CENTI(10-2), MILLI(10-3), MICRO(10-6), NANO(10-9), PICO(10-12), FEMTO(10-15), ATTO(10-18), ZEPTO(10-21), YOCTO(10-24)

• Informations needed by conversion is declared as enum fields.

• Interfaces is declared as static methods.

Examples of SIPrefix• CENTI(METRE) // SIPrefix.CENTI(SI.METRE)

- means ‘cm'

• NANO(SECOND) // SIPrefix.NANO(SI.SECOND)- means 'ns'

• MILLI(AMPARE) // SIPrefix.MILLI(SI.AMPARE)- means 'mA'

• HECTO(PASCAL) // SIPrefix.HECTO(SI.PASCAL)- means 'hPa'

// Exmaple // Representation of a famous formula // by Units of Measurement API (JSR 363) !// Defected mass Mass m = QuantityFactory.getInstance(Mass.class) .create(0.5, GRAM); !// Light speed Speed c = QuantityFactory.getInstance(Speed.class) .create(299_792_458, METRE_PER_SECOND); !// Result: E = mc2 System.out.println(m.multiply(c).multiply(c));

Conclusions• We Java programmers are able to abstract

various data and treat them as habitual, logical or scientific conception.

• We should say goodbye to COBOL-like style, for example, every data are presented by “java.lang.String”.

• Java APIs are improved day by day. Let’s use the modern Java!

Object-Oriented Children

HASUNUMA KenjiGlassFish [email protected]: @khasunuma


Recommended