Value Semantics - John Lakos - CppCon 2015
Value Semantics - John Lakos - CppCon 2015
John Lakos
Thursday, September 24, 2015
1
Copyright Notice
© 2015 Bloomberg L.P. Permission is granted to copy, distribute, and display
this material, and to make derivative works and commercial use of it. The
information in this material is provided "AS IS", without warranty of any
kind. Neither Bloomberg nor any employee guarantees the correctness or
completeness of such information. Bloomberg, its employees, and its
affiliated entities and persons shall not be liable, directly or indirectly, in any
way, for any inaccuracies, errors or omissions in such information. Nothing
herein should be interpreted as stating the opinions, policies,
recommendations, or positions of Bloomberg.
2
Abstract
When people talk about a type as having *value* *semantics*, they are often thinking about its ability
to be passed to (or returned from) a function by value. In order to do that, the C++ language requires
that the type implement a copy constructor, and so people routinely implement copy constructors on
their classes, which begs the question, "Should an object of that type be copyable at all?" If so, what
should be true about the copy? Should it have the same state as the original object? Same
behavior? What does copying an object mean?!
By *value* *type*, most people assume that the type is specifically intended to represent a member of
some set (of values). A value-semantic type, however, is one that strives to approximate an abstract
*mathematical* type (e.g., integer, character set, complex-number sequence), which comprises
operations as well as values. When we copy an object of a value-semantic type, the new object
might not have the same state, or even the same behavior as the original object; for proper value
semantic types, however, the new object will have the same value.
In this talk, we begin by gaining an intuitive feel for what we mean by *value* by identifying *salient*
*attributes*, i.e., those that contribute to value, and by contrasting types whose objects naturally
represent values with those that don't. After quickly reviewing the syntactic properties common to
typical value types, we dive into the much deeper issues that value semantics entail. In particular, we
explore the subtle Essential Property of Value, which applies to every *salient* mutating operation on
a value-semantic object, and then profitably apply this property to realize a correct design for each of
a variety of increasingly interesting (value-semantic) classes.
3
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential Property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
4
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential Property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
5
1. Introduction and Background
What’s the Problem?
6
1. Introduction and Background
What’s the Problem?
Large-Scale C++ Software Design:
• Involves many subtle logical and physical aspects.
7
1. Introduction and Background
Logical versus Physical Design
What distinguishes Logical from Physical Design?
Logical
physical
8
1. Introduction and Background
Logical versus Physical Design
What distinguishes Logical from Physical Design?
Logical
physical
9
1. Introduction and Background
Logical versus Physical Design
What distinguishes Logical from Physical Design?
Logical
physical
// component.t.cpp
#include <component.h>
// ...
int main(...)
{
//... // component.h // component.cpp
#include <component.h>
// ... // ...
}
//-- END OF FILE --
component.t.cpp
component.h component.cpp
component
11
1. Introduction and Background
Component: Uniform Physical Structure
Implementation
// component.t.cpp
#include <component.h>
// ...
int main(...)
{
//... // component.h // component.cpp
#include <component.h>
// ... // ...
}
//-- END OF FILE --
component.t.cpp
component.h component.cpp
component
12
1. Introduction and Background
Component: Uniform Physical Structure
Header
// component.t.cpp
#include <component.h>
// ...
int main(...)
{
//... // component.h // component.cpp
#include <component.h>
// ... // ...
}
//-- END OF FILE --
component.t.cpp
component.h component.cpp
component
13
1. Introduction and Background
Component: Uniform Physical Structure
Test Driver
// component.t.cpp
#include <component.h>
// ...
int main(...)
{
//... // component.h // component.cpp
#include <component.h>
// ... // ...
}
//-- END OF FILE --
component.t.cpp
component.h component.cpp
component
14
1. Introduction and Background
Component: Uniform Physical Structure
The Fundamental Unit of Design
// component.t.cpp
#include <component.h>
// ...
int main(...)
{
//... // component.h // component.cpp
#include <component.h>
// ... // ...
}
//-- END OF FILE --
component.t.cpp
component.h component.cpp
component
15
1. Introduction and Background
What’s the Problem?
Large-Scale C++ Software Design:
• Involves many subtle logical and physical aspects.
• Requires an ability to isolate and modularize
logical functionality within discrete, fine-grained
physical components.
16
1. Introduction and Background
Logical versus Physical Design
Logical content aggregated into a
Physical hierarchy of components
a b
17
1. Introduction and Background
What’s the Problem?
Large-Scale C++ Software Design:
• Involves many subtle logical and physical aspects.
• Requires an ability to isolate and modularize logical
functionality within discrete, fine-grained physical
components.
• Compels the designer to delineate logical behavior
precisely, while managing the physical
dependencies on other subordinate components.
18
1. Introduction and Background
Implied Dependency
PointList Polygon
PointList_Link
Point Shape
Depends-On
Uses-in-the-Interface Uses in name only
19
Uses-in-the-Implementation Is-A
1. Introduction and Background
Implied Dependency
PointList Polygon
PointList_Link
Point Shape
Depends-On
Uses-in-the-Interface Uses in name only
20
Uses-in-the-Implementation Is-A
1. Introduction and Background
What’s the Problem?
Large-Scale C++ Software Design:
• Involves many subtle logical and physical aspects.
• Requires an ability to isolate and modularize logical
functionality within discrete, fine-grained physical
components.
• Compels the designer to delineate logical behavior
precisely, while managing the physical
dependencies on other subordinate components.
• Demands a consistent, shared understanding of the
properties of common class categories: Value Types.
21
1. Introduction and Background
The Big Picture yes
no Is object-
Takes allocator?
instantiable?
Type only 2
meta- no yes
utility protocol Has “value”?
function
2
bsls::AlignmentUtil bslmf::IsFundamental baetzo::Loader
Value-
Semantic Type
2
2
externalizable,
Externalizable? no allocator
Mechanism 4
4
reference general
2 semantic bdem::ElemRef
container: VST
attribute enumeration
type associative?
X ordered?
X unique? x
a X indexed? 4
bdet::Date baetzo::LocalTimeValidity
bslma::DeallocatorGuard
guard/
2
proctor
bslma::DestructorProctor
a x a
baet::LocalDatetime baetzo::LocalTimePeriod
2 singleton bslma::NewDeleteAllocator
a
baetzo::LocalTimeDescriptor
no yes x
Referable
elements? bteso::LingerOptions
stateless
2 bsl::less
functor 64 64
a x
bassvc::ControlMessageResponse
packed standard
container container externalization
available from
bslx
bdea::BitArray
a x
bsl::vector
a
22
1. Introduction and Background
Common
Category
The Big Picture yes
no Is object-
Takes allocator?
instantiable?
Type only 2 Common
Common
utility
meta-
function
protocol Category
no
Has “value”?
yes
Category
2
2
2
externalizable,
Externalizable? no allocator
Common
Mechanism 4
Category 4
reference general
2 semantic bdem::ElemRef
container: VST
attribute enumeration
type associative?
X ordered?
X unique? x
a X indexed? 4
bdet::Date baetzo::LocalTimeValidity
bslma::DeallocatorGuard
guard/
2
proctor
bslma::DestructorProctor
a x a
baet::LocalDatetime baetzo::LocalTimePeriod
2 singleton bslma::NewDeleteAllocator
a
baetzo::LocalTimeDescriptor
no yes x
Referable
elements? bteso::LingerOptions
stateless
2 bsl::less
functor 64 64
a x
bassvc::ControlMessageResponse
packed standard
container container externalization
available from
bslx
bdea::BitArray
a x
bsl::vector
a
23
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential Property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
24
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential Property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
25
2. Understanding Value Semantics
Purpose of this Talk
Answer some key questions about value:
What do we mean by value?
Why is the notion of value important?
Which types should be considered value types?
What do we expect syntactically of a value type?
What semantics should its operations have?
How do we design proper value-semantic types?
When should value-related syntax be omitted?
26
2. Understanding Value Semantics
Value versus Non-Value Types
Getting Started:
27
2. Understanding Value Semantics
Value versus Non-Value Types
Getting Started:
• Not all useful C++ classes are value types.
28
2. Understanding Value Semantics
Value versus Non-Value Types
Getting Started:
• Not all useful C++ classes are value types.
• Still, value types form an important category.
29
2. Understanding Value Semantics
Value versus Non-Value Types
Getting Started:
• Not all useful C++ classes are value types.
• Still, value types form an important category.
• Let’s begin with understanding some basic
properties of value types.
30
2. Understanding Value Semantics
Value versus Non-Value Types
Getting Started:
• Not all useful C++ classes are value types.
• Still, value types form an important category.
• Let’s begin with understanding some basic
properties of value types.
• Then we’ll contrast them with non-value
types, to create a type-category hierarchy.
31
2. Understanding Value Semantics
Value versus Non-Value Types
Getting Started:
• Not all useful C++ classes are value types.
• Still, value types form an important category.
• Let’s begin with understanding some basic
properties of value types.
• Then we’ll contrast them with non-value
types, to create a type-category hierarchy.
• After that, we’ll dig further into the details of
value syntax and semantics. 32
2. Understanding Value Semantics
True Story
• Date: Friday Morning, October 5th, 2007
• Place: LWG, Kona, Hawaii
• Defect: issue #684: Wording of Working Paper
33
2. Understanding Value Semantics
True Story
• Date: Friday Morning, October 5th, 2007
• Place: LWG, Kona, Hawaii
• Defect: issue #684: Wording of Working Paper
34
2. Understanding Value Semantics
“The Same”
What do we mean by “the same”?
35
2. Understanding Value Semantics
“The Same”
What do we mean by “the same”?
• The two objects are identical?
– same address, same process, same time?
36
2. Understanding Value Semantics
“The Same”
What do we mean by “the same”?
• The two objects are identical?
– same address, same process, same time?
• The two objects are distinct, yet have certain
properties in common.
37
2. Understanding Value Semantics
“The Same”
What do we mean by “the same”?
• The two objects are identical?
– same address, same process, same time?
• The two objects are distinct, yet have certain
properties in common.
(It turned out to be the latter.)
38
2. Understanding Value Semantics
“The Same”
What do we mean by “the same”?
• The two objects are identical?
– same address, same process, same time?
• The two objects are distinct, yet have certain
properties in common.
(It turned out to be the latter.)
So the meaning was clear…
39
2. Understanding Value Semantics
“The Same”
What do we mean by “the same”?
• The two objects are identical?
– same address, same process, same time?
• The two objects are distinct, yet have certain
properties in common.
(It turned out to be the latter.)
So the meaning was clear… Or was it?
40
2. Understanding Value Semantics
What exactly has to be “the Same”?
The discussion continued…
…some voiced suggestions:
41
2. Understanding Value Semantics
What exactly has to be “the Same”?
The discussion continued…
…some voiced suggestions:
• Whatever the copy constructor preserves.
42
2. Understanding Value Semantics
What exactly has to be “the Same”?
The discussion continued…
…some voiced suggestions:
• Whatever the copy constructor preserves.
• As long as the two are “equal”.
43
2. Understanding Value Semantics
What exactly has to be “the Same”?
The discussion continued…
…some voiced suggestions:
• Whatever the copy constructor preserves.
• As long as the two are “equal”.
• As long as they’re “equivalent”.
44
2. Understanding Value Semantics
What exactly has to be “the Same”?
The discussion continued…
…some voiced suggestions:
• Whatever the copy constructor preserves.
• As long as the two are “equal”.
• As long as they’re “equivalent”.
• “You know what I mean!!”
45
2. Understanding Value Semantics
What exactly has to be “the Same”?
The discussion continued…
…some voiced suggestions:
• Whatever the copy constructor preserves.
• As long as the two are “equal”.
• As long as they’re “equivalent”.
• “You know what I mean!!”
Since “purely wording” left solely to the editor!
46
2. Understanding Value Semantics
Not just an “Editorial Issue”?
47
2. Understanding Value Semantics
Not just an “Editorial Issue”?
48
2. Understanding Value Semantics
Not just an “Editorial Issue”?
50
2. Understanding Value Semantics
What does a Copy Constructor do?
51
2. Understanding Value Semantics
What does a Copy Constructor do?
After copy construction, the
resulting object is…
52
2. Understanding Value Semantics
What does a Copy Constructor do?
After copy construction, the
resulting object is…
substitutable for the original one
with respect to “some criteria”.
53
2. Understanding Value Semantics
What does a Copy Constructor do?
After copy construction, the
resulting object is…
substitutable for the original one
with respect to “some criteria”.
What Criteria?
54
2. Understanding Value Semantics
Same Object?
55
2. Understanding Value Semantics
Same Object?
std::vector<double> a, b(a);
assert(&a == &b); // ??
56
2. Understanding Value Semantics
Same Object?
std::vector<double> a, b(a);
assert(&a == &b); // ??
assert(0 == b.size());
a.push_back(5.0);
assert(1 == b.size()); // ??
57
2. Understanding Value Semantics
Same Object?
std::vector<double> a, b(a);
assert(&a == &b); // ??
assert(0 == b.size());
a.push_back(5.0);
assert(1 == b.size()); // ??
58
2. Understanding Value Semantics
Same Object?
std::vector<double> a, b(a);
assert(&a == &b); // ??
assert(0 == b.size());
a.push_back(5.0);
assert(1 == b.size()); // ??
59
2. Understanding Value Semantics
Same Object?
std::vector<double> a, b(a);
assert(&a == &b); // ??
assert(0 == b.size());
a.push_back(5.0);
assert(1 == b.size()); // ??
60
2. Understanding Value Semantics
Same Object?
std::vector<double> a, b(a);
assert(&a == &b); // ??
assert(0 == b.size());
a.push_back(5.0);
assert(1 == b.size()); // ??
61
2. Understanding Value Semantics
Same State?
62
2. Understanding Value Semantics
Same State?
class String {
char *d_array_p; // dynamic
int d_capacity;
int d_length;
public:
String();
String(const String& original);
// ...
};
63
2. Understanding Value Semantics
Same State?
class String {
char *d_array_p; // dynamic
int d_capacity;
int d_length; What happens if this
address is copied?
public:
String();
String(const String& original);
// ...
};
64
2. Understanding Value Semantics
Same Behavior?
65
2. Understanding Value Semantics
Same Behavior?
If we apply the same sequence of operations to both
objects, the observable behavior will be the same:
66
2. Understanding Value Semantics
Same Behavior?
If we apply the same sequence of operations to both
objects, the observable behavior will be the same:
void f(bool x)
{
std::vector<int> a;
a.reserve(65536); // is capacity copied?
std::vector<int> b(a); assert(a == b)
67
2. Understanding Value Semantics
Same Behavior?
If we apply the same sequence of operations to both
objects, the observable behavior will be the same:
void f(bool x)
{
std::vector<int> a;
a.reserve(65536); // is capacity copied?
std::vector<int> b(a); assert(a == b)
a.reserve(65536); // no reallocation!
b.reserve(65536); // memory allocation?
68
2. Understanding Value Semantics
Same Behavior?
If we apply the same sequence of operations to both
objects, the observable behavior will be the same:
void f(bool x)
{
std::vector<int> a;
a.reserve(65536); // is capacity copied?
std::vector<int> b(a); assert(a == b)
a.reserve(65536); // no reallocation!
b.reserve(65536); // memory allocation?
a.push_back(5); b.push_back(5); // so not empty
std::vector<int>& r = x ? a : b;
if (&r[0] == &a[0]) { std::cout << "Hello"; }
else { std::cout << "Goodbye"; }
}
69
2. Understanding Value Semantics
Same What?
70
2. Understanding Value Semantics
Same What?
What should be “the same”
after copy construction?
(It better be easy to understand.)
74
2. Understanding Value Semantics
What do we mean by “value”?
75
2. Understanding Value Semantics
Mathematical Types
76
2. Understanding Value Semantics
Mathematical Types
A mathematical type consists of
• A set of globally unique values
– Each one describable independently of any
particular representation.
77
2. Understanding Value Semantics
Mathematical Types
A mathematical type consists of
• A set of globally unique values
– Each one describable independently of any
particular representation.
– For example, the decimal integer 5:
5, 5, V, 101(binary), five , IIII
78
2. Understanding Value Semantics
Mathematical Types
A mathematical type consists of
• A set of globally unique values
– Each one describable independently of any
particular representation.
– For example, the decimal integer 5:
5, 5, V, 101(binary), five , IIII
• A set of operations on those values
– For example: +, -, x (3 + 2)
79
2. Understanding Value Semantics
Mathematical Types
A mathematical type consists of
• A set of globally unique values
– Each one describable independently of any
particular representation.
– For example, the decimal integer 5:
5, 5, V, 101(binary), five , IIII
• A set of operations on those values Operations
will
– For example: +, -, x (3 + 2) become
important
shortly!
80
2. Understanding Value Semantics
C++ Type
81
2. Understanding Value Semantics
C++ Type
• A C++ type may represent (an approximation
to) an abstract mathematical type:
– For example: The C++ type int represents (an
approximation to) the mathematical type integer.
• An object of such a C++ type represents one of
(a subset of) the globally unique values in the
set of the abstract mathematical type.
• The C++ object is just another representation
of that globally unique, abstract value.
82
2. Understanding Value Semantics
C++ Type
• A C++ type may represent (an approximation
to) an abstract mathematical type:
– For example: The C++ type int represents (an
approximation to) the mathematical type integer.
• An object of such a C++ type represents one of
(a subset of) the globally unique values in the
set of the abstract mathematical type.
• The C++ object is just another representation
of that globally unique, abstract value.
83
2. Understanding Value Semantics
C++ Type
• A C++ type may represent (an approximation
to) an abstract mathematical type:
– For example: The C++ type int represents (an
approximation to) the mathematical type integer.
• An object of such a C++ type represents one of
(a subset of) the globally unique values in the
set of that abstract mathematical type.
• The C++ object is just another representation
of that globally unique, abstract value.
84
2. Understanding Value Semantics
C++ Type
• A C++ type may represent (an approximation
to) an abstract mathematical type:
– For example: The C++ type int represents (an
approximation to) the mathematical type integer.
• An object of such a C++ type represents one of
(a subset of) the globally unique values in the
set of that abstract mathematical type.
• The C++ object is just another representation
of that globally unique, abstract value, e.g., 5.
85
2. Understanding Value Semantics
So, what do we mean by “value”?
class Date {
short d_year;
char d_month;
char d_day;
public:
// …
int year();
int month();
int day();
};
87
2. Understanding Value Semantics
So, what do we mean by “value”?
class Date {
short d_year;
char d_month;
char d_day;
public:
// …
int year();
int month();
int day();
};
88
2. Understanding Value Semantics
So, what do we mean by “value”?
class Date {
short d_year;
char d_month;
char d_day;
public:
// …
int year();
int month();
int day();
};
89
2. Understanding Value Semantics
So, what do we mean by “value”?
class Date {
short d_year;
char d_month;
char d_day;
public:
// …
90
2. Understanding Value Semantics
So, what do we mean by “value”?
class Date { class Date {
short d_year;
char d_month; int d_serial;
char d_day;
public: public:
// … // …
91
2. Understanding Value Semantics
So, what do we mean by “value”?
class Date { class Date {
short d_year;
char d_month; int d_serial;
char d_day;
public: public:
// … // …
92
2. Understanding Value Semantics
So, what do we mean by “value”?
Salient Attributes
int year();
int month();
int day();
93
2. Understanding Value Semantics
So, what do we mean by “value”?
Salient Attributes
The documented set of (observable)
named attributes of a type T that
must respectively “have” (refer to)
the same value in order for two
instances of T to “have” (refer to) the
same value.
94
2. Understanding Value Semantics
So, what do we mean by “value”?
class Time { class Time {
char d_hour; int d_mSeconds;
char d_minute;
char d_second;
short d_millisec;
public: public:
// … // …
int hour(); int hour();
int minute(); int minute();
int second(); int second();
int millisecond(); int millisecond();
}; };
95
2. Understanding Value Semantics
So, what do we mean by “value”?
class Time { class Time {
Internal Representation Internal Representation
VALUE
public: public:
// … // …
int hour(); int hour();
int minute(); int minute();
int second(); int second();
int millisecond(); int millisecond();
}; };
96
2. Understanding Value Semantics
So, what do we mean by “value”?
QUESTION:
What would be the simplest
overarching mathematical type
for which std::string and
(const char *)are both
approximations?
97
2. Understanding Value Semantics
So, what do we mean by “value”?
QUESTION:
So if they both represent the
character sequence “Fred” do
they represent the same value?
98
2. Understanding Value Semantics
So, what do we mean by “value”?
QUESTION:
What about integers and
integers mod 5?
99
2. Understanding Value Semantics
So, what do we mean by “value”?
An “interpretation” of a subset of instance state.
100
2. Understanding Value Semantics
So, what do we mean by “value”?
An “interpretation” of a subset of instance state.
• The values of the Salient Attributes, and not
the instance state used to represent them,
comprise what we call the value of an object.
101
2. Understanding Value Semantics
So, what do we mean by “value”?
An “interpretation” of a subset of instance state.
• The values of the Salient Attributes, and not
the instance state used to represent them,
comprise what we call the value of an object.
• This definition may be recursive in that a
documented Salient Attribute of a type T may
itself be of type U having its own Salient
Attributes.
102
2. Understanding Value Semantics
So, what do we mean by “value”?
class Point {
short int d_x;
short int d_y;
public:
// …
int x();
int y();
};
103
2. Understanding Value Semantics
So, what do we mean by “value”?
class Point {
Internal Representation
public:
// …
int x();
int y();
};
104
2. Understanding Value Semantics
So, what do we mean by “value”?
class Point { class Box {
Internal Representation Point d_topLeft;
Point d_botRight;
public: public:
// … // …
int x(); Point origin();
int y(); int length();
}; int width();
};
105
2. Understanding Value Semantics
So, what do we mean by “value”?
class Point { class Box {
Internal Representation Internal Representation
public: public:
// … // …
int x(); Point origin();
int y(); int length();
}; int width();
};
106
2. Understanding Value Semantics
So, what do we mean by “value”?
class Point { class Box {
Internal Representation Internal Representation
public: public:
// … // …
int x(); Point origin();
int y(); int length();
}; int width();
};
107
2. Understanding Value Semantics
What are “Salient Attributes”?
108
2. Understanding Value Semantics
What are “Salient Attributes”?
class vector {
T *d_array_p;
size_type d_capacity;
size_type d_size;
// ...
public:
vector();
vector(const vector<T>& orig);
// ...
};
109
2. Understanding Value Semantics
What are “Salient Attributes”?
Consider std::vector<int>:
What are its salient attributes?
110
2. Understanding Value Semantics
What are “Salient Attributes”?
Consider std::vector<int>:
What are its salient attributes?
111
2. Understanding Value Semantics
What are “Salient Attributes”?
Consider std::vector<int>:
What are its salient attributes?
112
2. Understanding Value Semantics
What are “Salient Attributes”?
Consider std::vector<int>:
What are its salient attributes?
113
2. Understanding Value Semantics
What are “Salient Attributes”?
Consider std::vector<int>:
What are its salient attributes?
114
2. Understanding Value Semantics
What are “Salient Attributes”?
Salient Attributes:
115
2. Understanding Value Semantics
What are “Salient Attributes”?
Salient Attributes:
1. Are a part of logical design.
116
2. Understanding Value Semantics
What are “Salient Attributes”?
Salient Attributes:
1. Are a part of logical design.
2. Should be “natural” & “intuitive”.
117
2. Understanding Value Semantics
What are “Salient Attributes”?
Salient Attributes:
1. Are a part of logical design.
2. Should be “natural” & “intuitive”
3. Must be documented explicitly!
118
Why is value
important?
119
2. Understanding Value Semantics
Why are unique values important?
120
2. Understanding Value Semantics
Why are unique values important?
IPC
Inter-Process
Communication
121
2. Understanding Value Semantics
Why are unique values important?
Abstract date Type C++ Date Class
122
2. Understanding Value Semantics
Why are unique values important?
Abstract date Type C++ Date Class
Has an infinite set of
valid date values.
123
2. Understanding Value Semantics
Why are unique values important?
Abstract date Type C++ Date Class
Has an infinite set of
valid date values.
1000000 B.C. 1969-07-16
1959-03-08
1941-12-07
99999-12-31 1917-12-10
2008-04-03
1994-08-14 1919-02-05
1999-12-31
2001-09-11
1000000 A.D.
1776-07-04
1959-03-08
1941-12-07
99999-12-31 1917-12-10
2008-04-03 Date
1994-08-14 1919-02-05
1999-12-31
2001-09-11
1000000 A.D.
1776-07-04
C++
Globally Unique Values
128
2. Understanding Value Semantics
Why are unique values important?
Database
1959-03-08
1941-12-07
99999-12-31 1917-12-10
2008-04-03 Date
1994-08-14 1919-02-05
1999-12-31
2001-09-11
1000000 A.D.
1776-07-04
C++
Globally Unique Values
129
2. Understanding Value Semantics
Why are unique values important?
D
Database
1959-03-08
1941-12-07
99999-12-31 1917-12-10
2008-04-03 Date
1994-08-14 1919-02-05
1999-12-31
2001-09-11
1000000 A.D.
1776-07-04
C++
Globally Unique Values
130
2. Understanding Value Semantics
Why are unique values important?
D
Database
1959-03-08
1941-12-07
99999-12-31 1917-12-10
2008-04-03 Date
1994-08-14 1919-02-05
1999-12-31
2001-09-11
1000000 A.D.
1776-07-04
C++
Globally Unique Values
131
2. Understanding Value Semantics
Why are unique values important?
Date
Java D
Database
1959-03-08
1941-12-07
99999-12-31 1917-12-10
2008-04-03 Date
1994-08-14 1919-02-05
1999-12-31
2001-09-11
1000000 A.D.
1776-07-04
C++
Globally Unique Values
132
2. Understanding Value Semantics
Why are unique values important?
Date
Java D
Database
134
2. Understanding Value Semantics
Why are unique values important?
(Not just an academic exercise.)
137
2. Understanding Value Semantics
Does state always imply a “value”?
138
2. Understanding Value Semantics
Does state always imply a “value”?
139
2. Understanding Value Semantics
Does state always imply a “value”?
140
2. Understanding Value Semantics
Does state always imply a “value”?
141
2. Understanding Value Semantics
Does state always imply a “value”?
142
2. Understanding Value Semantics
Does state always imply a “value”?
143
2. Understanding Value Semantics
Does state always imply a “value”?
144
2. Understanding Value Semantics
Does state always imply a “value”?
145
2. Understanding Value Semantics
Does state always imply a “value”?
146
2. Understanding Value Semantics
Does state always imply a “value”?
147
2. Understanding Value Semantics
Does state always imply a “value”?
148
2. Understanding Value Semantics
Does state always imply a “value”?
150
2. Understanding Value Semantics
Does state always imply a “value”?
Not every stateful object has an obvious value.
151
2. Understanding Value Semantics
Does state always imply a “value”?
Not every stateful object has an obvious value.
• TCP/IP Socket
• Thread Pool
• Condition Variable
• Mutex Lock
• Reader/Writer Lock
• Scoped Guard
152
2. Understanding Value Semantics
Does state always imply a “value”?
Not every stateful object has an obvious value.
• TCP/IP Socket What would
• Thread Pool copy construction
even mean here?
• Condition Variable
• Mutex Lock
• Reader/Writer Lock
• Scoped Guard
153
2. Understanding Value Semantics
Does state always imply a “value”?
Not every stateful object has an obvious value.
• TCP/IP Socket What would
• Thread Pool copy construction
even mean here?
• Condition Variable
• Mutex Lock
• Reader/Writer Lock We could invent
some notion of value,
• Scoped Guard but to what end??
154
2. Understanding Value Semantics
Does state always imply a “value”?
Not every stateful object has an obvious value.
• TCP/IP Socket • Base64 En(De)coder
• Thread Pool • Expression Evaluator
• Condition Variable • Language Parser
• Mutex Lock • Event Logger
• Reader/Writer Lock • Object Persistor
• Scoped Guard • Widget Factory
155
2. Understanding Value Semantics
Does state always imply a “value”?
QUESTION:
Suppose we have a thread-safe
queue used for inter-task
communication: Is it a value
type? Should this object type
support value-semantic syntax?
156
2. Understanding Value Semantics
Does state always imply a “value”?
This class is a rare
and subtle
QUESTION: middle ground.
158
2. Understanding Value Semantics
Common
Category
The Big Picture yes
no Is object-
Takes allocator?
instantiable?
Type only 2 Common
Common
utility
meta-
function
protocol Category
no
Has “value”?
yes
Category
2
2
externalizable,
Externalizable? no allocator
Common
Mechanism 4
Category 4
reference general
2 semantic bdem::ElemRef
container: VST
attribute enumeration
type associative?
X ordered?
X unique? x
a X indexed? 4
bdet::Date baetzo::LocalTimeValidity
bslma::DeallocatorGuard
guard/
2
proctor
bslma::DestructorProctor
a x a
baet::LocalDatetime baetzo::LocalTimePeriod
2 singleton bslma::NewDeleteAllocator
a
baetzo::LocalTimeDescriptor
no yes x
Referable
elements? bteso::LingerOptions
stateless
2 bsl::less
functor 64 64
a x
bassvc::ControlMessageResponse
packed standard
container container externalization
available from
bslx
bdea::BitArray
a x
bsl::vector
a
159
2. Understanding Value Semantics
Categorizing Object Types
MyObjectType
160
2. Understanding Value Semantics
Categorizing Object Types
The first question: “Does it have state?”
Object
161
2. Understanding Value Semantics
Categorizing Object Types
The first question: “Does it have state?”
Object
162
2. Understanding Value Semantics
Categorizing Object Types
The first question: “Does it have state?”
Object
163
2. Understanding Value Semantics
Categorizing Object Types
The first question: “Does it have state?”
struct DateUtil {
// This 'struct' provides a namespace for a
// suite of pure functions that operate on
// 'Date' objects.
2
2
YOU Mechanism
Common
Category 4
Externalizable?
4
externalizable,
no allocator
ARE 2
reference
semantic
type
bdem::ElemRef
container:
associative?
X ordered?
X unique?
general
VST
x
attribute enumeration
a X indexed? 4
HERE
bdet::Date baetzo::LocalTimeValidity
bslma::DeallocatorGuard
guard/
2
proctor
bslma::DestructorProctor
a x a
baet::LocalDatetime baetzo::LocalTimePeriod
2 singleton bslma::NewDeleteAllocator
a
baetzo::LocalTimeDescriptor
no yes x
Referable
elements? bteso::LingerOptions
stateless
2 bsl::less
functor 64 64
a x
bassvc::ControlMessageResponse
packed standard
container container externalization
available from
bslx
bdea::BitArray
a x
bsl::vector
a
166
2. Understanding Value Semantics
Categorizing Object Types
The second question: “Does it have value?”
Object
167
2. Understanding Value Semantics
Categorizing Object Types
The second question: “Does it have value?”
Object
168
2. Understanding Value Semantics
Categorizing Object Types
The second question: “Does it have value?”
Yes
Object
169
2. Understanding Value Semantics
Categorizing Object Types
The second question: “Does it have value?”
No
Object
170
2. Understanding Value Semantics
Top-Level Categorizations
start here
no Is object- yes
Takes allocator?
instantiable?
Type only 2
no yes
2 Has “value”?
Value-
Mechanism
Semantic Type
2
2
171
2. Understanding Value Semantics
Top-Level Categorizations
start here
no Is object- yes
Takes allocator?
instantiable?
Type only 2
no yes
2 Has “value”?
2
Mechanism
Yes Value-
Semantic Type
172
2. Understanding Value Semantics
Top-Level Categorizations
start here
no Is object- yes
Takes allocator?
instantiable?
Type only 2
no yes
2 Has “value”?
2
Mechanism
No Value-
Semantic Type
173
2. Understanding Value Semantics
The Big Picture yes
no Is object-
Takes allocator?
instantiable?
Type only 2
meta- no yes
utility protocol Has “value”?
function
2
bsls::AlignmentUtil bslmf::IsFundamental baetzo::Loader
Value-
Semantic Type
2
2
externalizable,
Externalizable? no allocator
Mechanism 4
4
reference general
2 semantic bdem::ElemRef
container: VST
attribute enumeration
type associative?
X ordered?
X unique? x
a X indexed? 4
bdet::Date baetzo::LocalTimeValidity
bslma::DeallocatorGuard
guard/
2
proctor
bslma::DestructorProctor
a x a
baet::LocalDatetime baetzo::LocalTimePeriod
2 singleton bslma::NewDeleteAllocator
a
baetzo::LocalTimeDescriptor
no yes x
Referable
elements? bteso::LingerOptions
stateless
2 bsl::less
functor 64 64
a x
bassvc::ControlMessageResponse
packed standard
container container externalization
available from
bslx
bdea::BitArray
a x
bsl::vector
a
174
2. Understanding Value Semantics
Common
Category
The Big Picture yes
no Is object-
Takes allocator?
instantiable?
Type only 2 Common
Common
utility
meta-
function
protocol Category
no
Has “value”?
yes
Category
2
bsls::AlignmentUtil bslmf::IsFundamental baetzo::Loader
Value-
Semantic Type
2
2
externalizable,
pure
Externalizable? no allocator
Common
Mechanism 4
Category 4
reference general
2 semantic bdem::ElemRef
container: VST
attribute enumeration
abstract
type associative?
X ordered?
X unique? x
a X indexed? 4
bdet::Date baetzo::LocalTimeValidity
bslma::DeallocatorGuard
guard/
2
proctor
bslma::DestructorProctor
2 factory bteso::InetStreamSocketFactory
a
64
unconstrained
baet::LocalDatetime
simply
constrained
a x
interface complex
constrained
baetzo::LocalTimePeriod
a
pure
2 singleton bslma::NewDeleteAllocator
a
baetzo::LocalTimeDescriptor
no yes x
Referable
elements? bteso::LingerOptions
stateless
2 bsl::less
functor 64 64
a x
bassvc::ControlMessageResponse
packed standard
container container externalization
available from
bslx
bdea::BitArray
a x
bsl::vector
a
175
2. Understanding Value Semantics
The Big Picture
QUESTION:
What does it mean for two
abstract types to compare equal?
176
2. Understanding Value Semantics
The Big Picture
QUESTION:
What does it mean for two
abstract types to compare equal?
177
2. Understanding Value Semantics
The Big Picture
QUESTION:
What does it mean for two
abstract types to compare equal?
Data members are for:
180
2. Understanding Value Semantics
Value-Semantic Properties
A value-semantic type T defines the following:
• Default construction: T a, b; assert(a == b);
181
2. Understanding Value Semantics
Value-Semantic Properties
Typically, but
not necessarily
A value-semantic type T defines the following:
(e.g., int)
182
2. Understanding Value Semantics
Value-Semantic Properties
Typically, but
not necessarily
A value-semantic type T defines the following:
(e.g., int)
183
2. Understanding Value Semantics
Value-Semantic Properties
A value-semantic type T defines the following:
• Default construction: T a, b; assert(a == b);
• Copy construction: T a, b(a); assert(a == b);
184
2. Understanding Value Semantics
Value-Semantic Properties
A value-semantic type T defines the following:
• Default construction: T a, b; assert(a == b);
• Copy construction: T a, b(a); assert(a == b);
• Destruction: (Release all resources.)
185
2. Understanding Value Semantics
Value-Semantic Properties
A value-semantic type T defines the following:
• Default construction: T a, b; assert(a == b);
• Copy construction: T a, b(a); assert(a == b);
• Destruction: (Release all resources.)
• Copy assignment: a = b; assert(a == b);
186
2. Understanding Value Semantics
Value-Semantic Properties
A value-semantic type T defines the following:
• Default construction: T a, b; assert(a == b);
• Copy construction: T a, b(a); assert(a == b);
• Destruction: (Release all resources.)
• Copy assignment: a = b; assert(a == b);
• Swap (if well-formed): T a(α), b(β); swap(a, b);
assert(β == a);
assert(α == b);
187
2. Understanding Value Semantics
Value-Semantic Properties
A value-semantic type T defines the following:
• Default construction: T a, b; assert(a == b);
• Copy construction: T a, b(a); assert(a == b);
• Destruction: (Release all resources.)
• Copy assignment: a = b; assert(a == b);
• Swap (if well-formed): T a(α), b(β); swap(a, b);
assert(β == a);
assert(α == b);
188
2. Understanding Value Semantics
Value-Semantic Properties
operator==(T, T) describes what’s called
an equivalence relation:
1. a == a (reflexive)
2. a == b b == a (symmetric)
3. a == b && b == c a == c (transitive)
189
2. Understanding Value Semantics
Value-Semantic Properties
operator==(T, T) describes what’s called
an equivalence relation:
1. a == a (reflexive)
2. a == b b == a (symmetric)
3. a == b && b == c a == c (transitive)
!(a == b) a != b
190
2. Understanding Value Semantics
Value-Semantic Properties
operator==(T, T) describes what’s called
an equivalence relation:
1. a == a (reflexive)
2. a == b b == a (symmetric)
3. a == b && b == c a == c (transitive)
!(a == b) a != b
a == d (compiles) d == a (compiles)
(Note that d is not of the same type as a.)
191
2. Understanding Value Semantics
Value-Semantic Properties
operator==(T, T) describes what’s called
What am I
an equivalence relation:
1. a == a talking (reflexive)
2. a == b b == a about? (symmetric)
3. a == b && b == c a == c (transitive)
!(a == b) a != b
a == d (compiles) d == a (compiles)
(Note that d is not of the same type as a.)
192
2. Understanding Value Semantics
Value-Semantic Properties
Member operator==
class T {
// …
public:
// …
bool operator==(const T& rhs) const;
// …
};
193
2. Understanding Value Semantics
Value-Semantic Properties
Member operator==
class T { class D {
// … // …
public: public:
// … // …
bool operator==(const T& rhs) const; operator const T&() const;
// … // …
}; };
194
2. Understanding Value Semantics
Value-Semantic Properties
Member operator==
class T { class D {
// … // …
public: public:
// … // …
bool operator==(const T& rhs) const; operator const T&() const;
// … // …
}; };
195
2. Understanding Value Semantics
Value-Semantic Properties
Member operator==
class T { class D {
// … // …
public: public:
// … // …
bool operator==(const T& rhs) const; operator const T&() const;
// … // …
}; };
196
2. Understanding Value Semantics
Value-Semantic Properties
Free operator==
class T { class D {
// … // …
public: public:
// … // …
}; operator const T&() const;
// … // …
bool operator==(const T& lhs, const T& rhs); };
197
2. Understanding Value Semantics
Value-Semantic Properties
Free operator==
class T { class D {
// … // …
public: public:
};
// … (proper) // …
operator const T&() const;
// … // …
bool operator==(const T& lhs, const T& rhs); };
198
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member
// …
public: Operator==
Str(const char *other);
// …
bool operator==(const char *rhs) const;
// …
};
// …
bool operator==(const Str& lhs, const Str&
rhs); bool operator==(const char *lhs, const
Str& rhs);
199
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member
// …
public: Operator==
Str(const char *other);
// …
bool operator==(const char *rhs) const;
// …
};
// …
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
200
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member
// …
public: Operator==
Str(const char *other);
// …
bool operator==(const char *rhs) const;
// …
};
// …
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
201
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member Operator==
// …
public:
Str(const char *other);
// …
bool operator==(const char *rhs) const;
// …
};
// …
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
202
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member Operator== class Foo {
// … // …
public: public:
// …
Str(const char *other);
// … operator const Str&() const;
// …
bool operator==(const char *rhs) const;
// … };
};
// …
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
203
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member Operator== class Foo {
// … // …
public: public:
// …
Str(const char *other);
// … operator const Str&() const;
// …
bool operator==(const char *rhs) const;
// … };
};
// …
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
class Bar {
// …
public:
// …
operator const char *() const;
// …
};
204
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member Operator== class Foo {
// … // …
public: public:
// …
Str(const char *other);
// … operator const Str&() const;
// …
bool operator==(const char *rhs) const;
// … };
};
// …
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
205
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Member Operator== class Foo {
// … // …
public: public:
// …
Str(const char *other);
// … operator const Str&() const;
// …
bool operator==(const char *rhs) const;
// … };
};
// …
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
206
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Free Operator== class Foo {
// … // …
public: public:
// …
Str(const char *other);
// … operator const Str&() const;
// …
};
// … };
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
bool operator==(const Str& lhs, const char *rhs);
207
2. Understanding Value Semantics
Value-Semantic Properties
class Str { Free Operator== class Foo {
// … // …
public: public:
// …
Str(const char *other);
// … (proper) operator const Str&() const;
// …
};
// … };
bool operator==(const Str& lhs, const Str& rhs);
bool operator==(const char *lhs, const Str& rhs);
bool operator==(const Str& lhs, const char *rhs);
208
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
209
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
210
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
211
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
212
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
213
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
214
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
215
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
216
2. Understanding Value Semantics
Value-Semantic Properties
The operator== should ALWAYS be free!
Same for most* binary operators with const parameters:
== != (equality)
< <= > => (relational)
+ - * / % (arithmetic)
| & ^ << >> (logical)
X += -= *= /= %= (assignment)
X |= &= ^= <<= >>= (assignment)
*Except for operators such as operator[] that return a reference instead of a value, and operator().
217
What semantics
should value-type
operations have?
218
2. Understanding Value Semantics
Where is “Value” Defined?
219
2. Understanding Value Semantics
Where is “Value” Defined?
220
2. Understanding Value Semantics
Where is “Value” Defined?
221
2. Understanding Value Semantics
Where is “Value” Defined?
225
2. Understanding Value Semantics
Where is “Value” Defined?
Copy Constructor?
• By def., all salient attributes must be copied.
• What about “non-salient” attributes?
– E.g., capacity()
226
2. Understanding Value Semantics
Where is “Value” Defined?
Copy Constructor?
• By def., all salient attributes must be copied.
• What about “non-salient” attributes?
– E.g., capacity()
• Non-salient attributes may or may not be copied.
227
2. Understanding Value Semantics
Where is “Value” Defined?
Copy Constructor?
• By def., all salient attributes must be copied.
• What about “non-salient” attributes?
– E.g., capacity()
• Non-salient attributes may or may not be copied.
• Hence, we cannot infer from the implementation of
a Copy Constructor which attributes are “salient.”
228
2. Understanding Value Semantics
Where is “Value” Defined?
Copy Constructor?
• By def., all salient attributes must be copied.
• What about “non-salient” attributes?
– E.g., capacity()
• Non-salient attributes may or may not be copied.
• Hence, we cannot infer from the implementation of
a Copy Constructor which attributes are “salient.”
• Cannot tell us if two objects have the same value!
229
2. Understanding Value Semantics
Where is “Value” Defined?
232
2. Understanding Value Semantics
Where is “Value” Defined?
operator==
The associated, homogeneous (free) operator==
for a type T
233
2. Understanding Value Semantics
Where is “Value” Defined?
operator==
The associated, homogeneous (free) operator==
for a type T
1. Provides an operational definition of what it means
for two objects of type T to have “the same” value.
234
2. Understanding Value Semantics
Where is “Value” Defined?
operator==
The associated, homogeneous (free) operator==
for a type T
1. Provides an operational definition of what it means
for two objects of type T to have “the same” value.
2. Defines the salient attributes of T as those
attributes whose respective values must
compare equal in order for two instances of T to
compare equal.
235
2. Understanding Value Semantics
Value-Semantic Properties
Value-semantic objects share many properties.
• Each of these properties is objectively
verifiable, irrespective of the intended
application domain.
• Most are (or should be) intuitive.
• Those few that are not, are particularly useful
for providing design guidance in “unusual” cases.
236
2. Understanding Value Semantics
Value-Semantic Properties
Value-semantic objects share many properties.
• Each of these properties is objectively
verifiable, irrespective of the intended
application domain.
• Most are (or should be) intuitive.
• Those few that are not, are particularly useful
for providing design guidance in “unusual” cases.
237
2. Understanding Value Semantics
Value-Semantic Properties
Value-semantic objects share many properties.
• Each of these properties is objectively
verifiable, irrespective of the intended
application domain.
• Most are (or should be) intuitive.
• Those few that are not, are particularly useful
for providing design guidance in “unusual” cases.
238
2. Understanding Value Semantics
What should be copied?
Should attributes that are orthogonal to value
be copied?
NMOS CMOS
01001001 11110011
239
2. Understanding Value Semantics
What should be copied?
Should attributes that are orthogonal to value
be copied?
NMOS CMOS
01001001 11110011
240
2. Understanding Value Semantics
What should be copied?
Should attributes that are orthogonal to value
be copied?
NMOS CMOS
01001001
!= 11110011
241
2. Understanding Value Semantics
What should be copied?
Should attributes that are orthogonal to value
be copied?
242
2. Understanding Value Semantics
What should be copied?
Should attributes that are orthogonal to value
be copied?
243
2. Understanding Value Semantics
What should be copied?
Should attributes that are orthogonal to value
be copied?
NMOS
CMOS
?? assignment CMOS
11110011
== 11110011
244
2. Understanding Value Semantics
What should be copied?
245
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
As it turns out…
246
2. Understanding Value Semantics
Value-Semantic Properties
If T is a value-semantic type,
a, b, and c are objects of type T, and
d is an object of some other type D, then
247
2. Understanding Value Semantics
Value-Semantic Properties
If T is a value-semantic type,
a, b, and c are objects of type T, and
d is an object of some other type D, then
a == b a and b have the same value
(assuming an associated operator== exists).
248
2. Understanding Value Semantics
Value-Semantic Properties
If T is a value-semantic type,
a, b, and c are objects of type T, and
d is an object of some other type D, then
a == b a and b have the same value
(assuming an associated operator== exists).
249
2. Understanding Value Semantics
Value-Semantic Properties
If T is a value-semantic type,
a, b, and c are objects of type T, and
d is an object of some other type D, then
a == b a and b have the same value
(assuming an associated operator== exists).
250
2. Understanding Value Semantics
Value-Semantic Properties
If T is a value-semantic type,
a, b, and c are objects of type T, and
d is an object of some other type D, then
a == b a and b have the same value
(assuming an associated operator== exists).
251
2. Understanding Value Semantics
Value-Semantic Properties
If T is a value-semantic type,
a, b, and c are objects of type T, and
d is an object of some other type D, then
a == b a and b have the same value
(assuming an associated operator== exists).
The value of a is independent of any external
object or state; any change to a must be
accomplished via a’s (public) interface.
252
2. Understanding Value Semantics
Value-Semantic Properties
Suppose a “value-semantic” object refers to
another autonomous object in memory:
class ElemRef {
Record *d_record_p;
int elementIndex;
public:
// …
};
253
2. Understanding Value Semantics
Value-Semantic Properties
Suppose a “value-semantic” object refers to
another autonomous object in memory:
class ElemPtr {
Record *d_record_p;
int d_elementIndex;
public:
// …
};
254
2. Understanding Value Semantics
Value-Semantic Properties
Suppose a “value-semantic” object refers to
another autonomous object in memory:
class ElemPtr {
Record *d_record_p;
int d_elementIndex;
public:
// …
};
255
2. Understanding Value Semantics
Value-Semantic Properties
Suppose a “value-semantic” object refers to
another autonomous object in memory:
class ElemPtr {
Record *d_record_p;
int d_elementIndex;
public:
// …
};
256
2. Understanding Value Semantics
Value-Semantic Properties
0x74a1254c:
0 1 2 3 4 5 6 7 8 9
x
0x002c5f20: y
z
0x74a1254c
Record
3
ElemPtr
257
2. Understanding Value Semantics
Value-Semantic Properties
0x74a1254c:
0 1 2 3 4 5 6 7 8 9
x
0x002c5f20: y
z
0x74a1254c
Record
3
ElemPtr
258
2. Understanding Value Semantics
Value-Semantic Properties
0x74a1254c:
0 1 2 3 4 5 6 7 8 9
x
0x002c5f20: y
z
0x74a1254c
Record
3
ElemPtr
259
2. Understanding Value Semantics
Value-Semantic Properties
bool operator==(const ElemPtr& lhs,
const ElemPtr& rhs);
260
2. Understanding Value Semantics
Value-Semantic Properties
bool operator==(const ElemPtr& lhs,
const ElemPtr& rhs);
// Two 'ElemPtr' objects have the
// same value if they …
261
2. Understanding Value Semantics
Value-Semantic Properties
bool operator==(const ElemPtr& lhs,
const ElemPtr& rhs);
// Two 'ElemPtr' objects have the
// same value if they (1) refer
// to the same 'Record' object
// (in the current process) …
262
2. Understanding Value Semantics
Value-Semantic Properties
bool operator==(const ElemPtr& lhs,
const ElemPtr& rhs);
// Two 'ElemPtr' objects have the
// same value if they (1) refer
// to the same 'Record' object
// (in the current process), and
// (2) have the same element
// index.
263
2. Understanding Value Semantics
Value-Semantic Properties
Record Record
objA objB
O O O O
2 3 3 3
264
2. Understanding Value Semantics
Value-Semantic Properties
??
Record
objA == Record
objB
O O O O
2 3 3 3
265
2. Understanding Value Semantics
Value-Semantic Properties
Record Record
objA objB
O O O O
2 3 3 3
266
2. Understanding Value Semantics
Value-Semantic Properties
Record Record
objA objB
O O O O
2 3 3 3
267
2. Understanding Value Semantics
Value-Semantic Properties
Record Record
objA objB
O O O O
2 3 3 3
268
2. Understanding Value Semantics
Value-Semantic Properties
Record Record
objA objB
O
2
O
3 == O
3
O
3
269
2. Understanding Value Semantics
Value-Semantic Properties
Record Record
objA objB
O
2
O
3 == O
3
O
3
270
2. Understanding Value Semantics
Value-Semantic Properties
Record
Record
objA
objB
O
2
O
3 == O
3
O
3
271
2. Understanding Value Semantics
Value-Semantic Properties
Record
Record
objA
objB
O
2
O
3 == O
3
O
3
272
2. Understanding Value Semantics
Value-Semantic Properties
Record
Record
objA
objB
O
2
O
3 == O
3
O
3
273
2. Understanding Value Semantics
Value-Semantic Properties
Record
Record
objA
objB
O
2
O
3 == O
3
O
3
275
2. Understanding Value Semantics
“Value Types” having Value Semantics
278
2. Understanding Value Semantics
Value-Semantic Properties
Recall that two distinct objects a and b of
type T that have the same value might not
exhibit “the same” observable behavior.
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
3. (absent any exceptions or undefined behavior)
279
2. Understanding Value Semantics
Value-Semantic Properties
Recall that two distinct objects a and b of
type T that have the same value might not
exhibit “the same” observable behavior.
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
3. (absent any exceptions or undefined behavior)
280
2. Understanding Value Semantics
Value-Semantic Properties
Recall that two distinct objects a and b of
type T that have the same value might not
exhibit “the same” observable behavior.
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
3. (absent any exceptions or undefined behavior)
281
2. Understanding Value Semantics
Value-Semantic Properties
Recall that two distinct objects a and b of
type T that have the same value might not
exhibit “the same” observable behavior.
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
282
2. Understanding Value Semantics
Value-Semantic Properties
Recall that two distinct objects a and b of
type T that have the same value might not
exhibit “the same” observable behavior.
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
3. (absent any exceptions or undefined behavior)
283
2. Understanding Value Semantics
Value-Semantic Properties
Recall that two distinct objects a and b of
type T that have the same value might not
exhibit “the same” observable behavior.
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
3. (absent any exceptions or undefined behavior)
4. both objects will again have the same value!
284
2. Understanding Value Semantics
Value-Semantic Properties
There is a lot more to this story!
Note that two distinct objects a and b of
type T that have the same value might not
exhibit “the same” observable behavior.
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
3. (absent any exceptions or undefined behavior)
4. both objects will again have the same value!
285
2. Understanding Value Semantics
Value-Semantic Properties
That is…
if (a == b) {
op1(a); op1(b); assert(a == b);
op2(a); op2(b); assert(a == b);
op3(a); op3(b); assert(a == b);
op4(a); op4(b); assert(a == b);
.. .. ...
. .
}
286
2. Understanding Value Semantics
Note that this is
Value-Semantic Properties not a test case,
but rather a
requirements
That is… specification.
if (a == b) {
op1(a); op1(b); assert(a == b);
op2(a); op2(b); assert(a == b);
op3(a); op3(b); assert(a == b);
op4(a); op4(b); assert(a == b);
.. .. ...
. .
}
287
2. Understanding Value Semantics
Value-Semantic Properties
QUESTION:
Suppose we have a “home grown” ordered-set
type that can be initialized to a sequence of
elements in either increasing or decreasing order:
template <class T>
class OrderedSet {
// …
OrderedSet(bool decreasingFlag = false);
// …
};
288
2. Understanding Value Semantics
Value-Semantic Properties
QUESTION:
Suppose we have a “home grown” ordered-set
type that can be initialized to a sequence of
elements in either increasing or decreasing order:
template <class T>
class OrderedSet {
// …
OrderedSet(bool decreasingFlag = false);
// …
};
289
2. Understanding Value Semantics
Value-Semantic Properties
QUESTION:
Suppose we have a “home grown” ordered-set
type that can be initialized to a sequence of
elements in either increasing or decreasing order:
template <class T>
class OrderedSet {
// …
OrderedSet(bool decreasingFlag = false);
// …
};
However
1. If a and b initially have the same value, and
2. the same operation is applied to each object, then
^salient
3. (absent any exceptions or undefined behavior)
4. both objects will again have the same value!
293
2. Understanding Value Semantics
Value-Semantic Properties
QUESTION:
What makes two unordered containers represent
the same value?
Think about a bag
of Halloween
candy.
294
2. Understanding Value Semantics
Value-Semantic Properties
Note that this essential property applies only to
objects of the same type:
int x = 5; int y = 5; assert(x == y);
x *= x; y *= y; assert(x == y);
x *= x; y *= y; assert(x == y);
x *= x; y *= y; assert(x == y);
.. .. ..
. . .
295
2. Understanding Value Semantics
Value-Semantic Properties
Note that this essential property applies only to
objects of the same type:
int x = 5; short y = 5; assert(x == y);
x *= x; y *= y; assert(x == y);
x *= x; y *= y; assert(x == y);
x *= x; y *= y; assert(x == y);
.. .. ..
. . .
Undefined Behavior!
296
How do we
design proper
value types?
297
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Rational {
int d_numerator;
int d_denominator;
public:
//
int numerator() const;
int denominator() const;
};
// …
bool operator==(const Rational& lhs,
const Rational& rhs);
298
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
numerator()/denominator()
as the salient attribute?
numerator()/denominator()
as the salient attribute?
numerator()/denominator()
as the salient attribute?
numerator()/denominator()
as the salient attribute?
numerator()/denominator()
as the salient attribute?
303
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
numerator()/denominator()
as the salient attribute?
304
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
numerator()/denominator()
as the salient attribute?
numerator()/denominator()
as the salient attribute?
Guideline
If two objects have the same
value then the values of each
observable attribute that
contributes to value should
respectively compare equal.
309
When should
we omit valid
value syntax?
310
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
3 2
0
311
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Graph
Node Edge
graph
312
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Graph
Node Edge
graph
313
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Graph
Node Edge
graph
314
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Graph
Node
NodeIterator
graph
315
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Graph
Node
graph
316
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Graph {
// …
public:
// …
int numNodes() const;
const Node& node(int index) const;
};
// …
Graph
Node 0 Node 1 Node 2 Node 3 Node 4
317
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Node {
// …
public:
// …
int nodeIndex() const;
int numAdjacentNodes() const;
Node& adjacentNode(int index) const;
};
Graph
Node 0 Node 1 Node 2 Node 3 Node 4
318
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Node {
// … Really should be
public: declared const but
// …
there’s no room!
int nodeIndex() const;
int numAdjacentNodes() const;
Node& adjacentNode(int index) const;
};
Graph
Node 0 Node 1 Node 2 Node 3 Node 4
319
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Node {
// …
public:
// … 2
int nodeIndex() const;
int numAdjacentNodes() const;
Node& adjacentNode(int index) const;
};
Graph
Node 0 Node 1 Node 2 Node 3 Node 4
320
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Node {
// …
public:
// … 2
Node 0
and
int nodeIndex() const; 2
Node 4 int numAdjacentNodes() const;
Node& adjacentNode(int index) const;
};
Graph
Node 0 Node 1 Node 2 Node 3 Node 4
321
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Graph {
// …
public:
// …
int numNodes() const;
a const Node& node(int index) const;
a };
// …
bool operator==(const Graph& lhs,
cccccccccccc cconst Graph& rhs);
322
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Graph {
// …
public:
// …
int numNodes() const;
a const Node& node(int index) const;
a };
// …
bool operator==(const Graph& lhs,
cccccccccccc cconst Graph& rhs);
cc // Two 'Graph' objects have the same
cc // value if …???
323
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
324
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
• Number of nodes.
325
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
• Number of nodes.
• Number of edges.
326
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
• Number of nodes.
• Number of edges.
• Number of nodes adjacent to each node.
327
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
• Number of nodes.
• Number of edges.
• Number of nodes adjacent to each node.
328
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
• Number of nodes.
• Number of edges.
• Number of nodes adjacent to each node.
• Specific nodes adjacent to each node.
329
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
• Number of nodes.
• Number of edges.
• Number of nodes adjacent to each node.
• Specific nodes adjacent to each node.
330
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
bool operator==(const Graph& lhs,
cccccccccccc const Graph& rhs);
cc// Two 'Graph' objects have the same
c// value if
331
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
bool operator==(const Graph& lhs,
cccccccccccc const Graph& rhs);
cc// Two 'Graph' objects have the same
c// value if they have the same number of
// nodes 'N' and,
332
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
bool operator==(const Graph& lhs,
cccccccccccc const Graph& rhs);
cc// Two 'Graph' objects have the same
c// value if they have the same number of
// nodes 'N' and, for each node index 'i'
// '(0 <= i < N)',
333
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
bool operator==(const Graph& lhs,
cccccccccccc const Graph& rhs);
cc// Two 'Graph' objects have the same
c// value if they have the same number of
// nodes 'N' and, for each node index 'i'
// '(0 <= i < N)', the nodes adjacent to
// node 'i' in 'lhs' have the same
// indices as those of the nodes
// adjacent to node 'i' in 'rhs'.
334
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Node {
// …
public:
// …
int nodeIndex() const;
int numAdjacentNodes() const;
Node& adjacentNode(int index) const;
};
335
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
class Node {
// …
Maintained in
public: sorted order?
// …
int nodeIndex() const;
int numAdjacentNodes() const;
Node& adjacentNode(int index) const;
};
337
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Unordered Edges Node Edge
Ordered Edges
4
0: 4 1 3 0: 1 3 4
1: 3 2 3 2
1: 2 3
2: 0 4 0 2: 0 4
3: 3:
4: 3 4: 3
1
?
O[operator==]
338
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Unordered Edges Node Edge
Ordered Edges
4
0: 4 1 3 0: 1 3 4
1: 3 2 3 2
1: 2 3
2: 0 4 0 2: 0 4
3: 3:
4: 3 4: 3
1
?
O[N + E2] O[operator==]
339
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Unordered Edges Node Edge
Ordered Edges
4
0: 4 1 3 0: 1 3 4
1: 3 2 3 2
1: 2 3
2: 0 4 0 2: 0 4
3: 3:
4: 3 4: 3
1
?
O[N + E2] O[operator==] O[N + E]
340
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Unordered Edges Node Edge
Ordered Edges
4
0: 4 1 3 0: 1 3 4
1: 3 2 3 2
1: 2 3
2: 0 4 0 2: 0 4
3: 3:
4: 3 4: 3
1
?
O[N + E2] O[operator==] O[N + E]
?
O[N + E2] O[operator==] O[N + E]
343
2. Understanding Value Semantics
Value-Semantic Properties
Observation
Observation
Value Syntax: Not all or nothing!
344
2. Understanding Value Semantics
Value-Semantic Properties
Observation
Value Syntax: Not all or nothing!
345
2. Understanding Value Semantics
Value-Semantic Properties
Observation
Value Syntax: Not all or nothing!
An std::unordered_set<int> is a value-
semantic type, except that – until 2010 – it did
not provide an operator==.
346
2. Understanding Value Semantics
Value-Semantic Properties
Observation
Value Syntax: Not all or nothing!
An std::unordered_set<int> is a value-
semantic type, except that – until 2010 – it did
not provide an operator==.
347
2. Understanding Value Semantics
Value-Semantic Properties
Observation
Value Syntax: Not all or nothing!
An std::unordered_set<int> is a value-
semantic type, except that – until 2010 – it did
not provide an operator==.
348
2. Understanding Value Semantics
Value-Semantic Properties
Observation
Value Syntax: Not all or nothing!
An std::unordered_set<int> is a value-
semantic type, except that – until 2010 – it did
not provide an operator==.
349
2. Understanding Value Semantics
Value-Semantic Properties
Observation
Value Syntax: Not all or nothing!
An std::unordered_set<int> is a value-
semantic type, except that – until 2010 – it did
not provide an operator==.
350
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
351
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
352
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
Specific nodes adjacent to each node.
353
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
Specific nodes adjacent to each node.
X Not adjacent-node (i.e., edge) order.
354
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
Specific nodes adjacent to each node.
X Not adjacent-node (i.e., edge) order.
What about node indices?
(I.e., the numbering of the nodes)
355
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
bool operator==(const Graph& lhs,
cccccccccccc const Graph& rhs);
cc// Two 'Graph' objects have the same
c// value if they have the same number of
// nodes 'N' and there exists a renumbering
// of the nodes in 'rhs' such that, for
// each node-index 'i' '(0 <= i < N)',
// the nodes adjacent to node 'i' in 'lhs'
// have the same indices as those of the
// nodes adjacent to node 'i' in 'rhs'.
356
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
4
3 2
0
357
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Node
Index 3 4
3 2
0
358
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Node
Index 3 4
3 2
0
1
1 4
2
359
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Node
Index 3 4
3 2
0
3
== 1
1 4
2
360
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Node
Index 3 4
3 2 1
0
3
== 1
1 4
2 4
2
0 3
361
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Node
Index 3 4
3 2 1
0
3
== 1
==
1 4
2 4
2
0 3
362
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
Node
Index 3 4
3 2 1
0
3
== 1
==
1 4
4
2
Should
operator==
2
0 mean 3
isomorphic? 363
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
In graph theory, an isomorphism of graphs* G and H is a bijection ƒ
between the vertex sets of G and H such that any two vertices u and v
of G are adjacent in G if and only if ƒ(u) and ƒ(v) are adjacent in H.
An isomorphism
Graph G Graph H
between G and H
ƒ(a) = 1
ƒ(b) = 6
ƒ(c) = 8
ƒ(d) = 3
ƒ(g) = 5
ƒ(h) = 2
ƒ(i) = 4
ƒ(j) = 7
*http://en.wikipedia.org/wiki/Graph_isomorphism
364
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
365
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
366
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
367
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
372
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
Specific nodes adjacent to each node.
373
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
Specific nodes adjacent to each node.
And, as a practical matter,
Numbering of the nodes.
374
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
Specific nodes adjacent to each node.
And, as a practical matter,
Numbering of the nodes.
375
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
What are the salient attributes of Graph?
Number of nodes.
Specific nodes adjacent to each node.
And, as a practical matter,
Numbering of the nodes.
376
2. Understanding Value Semantics
Discussion
Why would we ever
omit valid value
syntax when there
is only one obvious
notion of value?
377
2. Understanding Value Semantics
Discussion
Why would we ever
omit valid value
syntax when there
is only one obvious
notion of value?
378
2. Understanding Value Semantics
Discussion
Why would we ever
omit valid value
syntax when there
is only one obvious
notion of value?
379
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
380
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
When selecting salient attributes, avoid
subjective (domain-specific) interpretation:
381
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
When selecting salient attributes, avoid
subjective (domain-specific) interpretation:
Fractions may be equivalent, but not the same.
382
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
When selecting salient attributes, avoid
subjective (domain-specific) interpretation:
Fractions may be equivalent, but not the same.
Graphs may be isomorphic, yet distinct.
383
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
When selecting salient attributes, avoid
subjective (domain-specific) interpretation:
Fractions may be equivalent, but not the same.
Graphs may be isomorphic, yet distinct.
Triangles may be similar and still differ.
384
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
Relegate any “subjective interpretations” of equality
to named functions!
385
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
Relegate any “subjective interpretations” of equality
to named functions – ideally, in higher-level components:
386
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
Relegate any “subjective interpretations” of equality
to named functions – ideally, in higher-level components:
struct MyUtil {
static bool areEquivalent(const Rational& a)-
-------------------- const Rational& b);
static bool areIsomorphic(const Graph& g1,---
-------------------- const Graph& g2);
static bool areSimilar(const Triangle& x,----
----------------- const Triangle& y);
};
387
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
Relegate any “subjective interpretations” of equality
to named functions – ideally, in higher-level components:
struct MyUtil {
static bool areEquivalent(const Rational& a)-
-------------------- const Rational& b);
static bool areIsomorphic(const Graph& g1,---
-------------------- const Graph& g2);
static bool areSimilar(const Triangle& x,----
----------------- const Triangle& y);
};
388
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
Relegate any “subjective interpretations” of equality
to named functions – ideally, in higher-level components:
struct MyUtil {
static bool areEquivalent(const Rational& a)-
-------------------- const Rational& b);
static bool areIsomorphic(const Graph& g1,---
-------------------- const Graph& g2);
static bool areSimilar(const Triangle& x,----
----------------- const Triangle& y);
};
389
2. Understanding Value Semantics
Value-Semantic Properties
Selecting Salient Attributes
(Summary So Far)
Relegate any “subjective interpretations” of equality
to named functions – ideally, in higher-level components:
struct MyUtil {
static bool areEquivalent(const Rational& a)-
-------------------- const Rational& b);
static bool areIsomorphic(const Graph& g1,---
-------------------- const Graph& g2);
static bool areSimilar(const Triangle& x,----
----------------- const Triangle& y);
};
390
2. Understanding Value Semantics
Value-Semantic Properties
391
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
“…objects are identical…”
“…objects are equal…”
“…objects are equivalent…”
“…create a copy of…”
392
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
“…objects are identical…”
“…objects are equal…”
“…objects are equivalent…”
“…create a copy of…”
393
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
“…objects are identical…”
“…objects are equal…”
“…objects are equivalent…”
“…create a copy of…”
394
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
“…objects are identical…”
“…objects are equal…”
“…objects are equivalent…”
“…create a copy of…”
395
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
“…objects are identical…”
(identity)
396
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
“…objects are identical…”
(identity)
397
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
(value)
398
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
(value)
“…(objects) have the same value…”
399
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
(value)
“…(objects) have the same value…”
“…(objects) refer to the same value…”
400
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same…”
(value)
“…(objects) have the same value…”
“…(objects) refer to the same value…”
“…(objects) represent the same value…”
401
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
“…objects are equal…”
(equality)
402
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
“…objects are equal…”
(equality)
“…(objects) compare equal…”
403
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
“…objects are equal…”
(equality)
“…(objects) compare equal…”
“…(homogeneous) operator== returns true…”
404
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
“…objects are equal…”
(equality)
“…(objects) compare equal…”
“…(homogeneous) operator== returns true…”
405
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
“…objects are equal…”
(equality)
“…(objects) compare equal…”
“…(homogeneous) operator== returns true…”
406
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
aaa (equivalent)
407
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
aaa (equivalent)
In separate named functions:
408
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
aaa (equivalent)
In separate named functions:
“…fractions are equivalent…”
409
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
aaa (equivalent)
In separate named functions:
“…fractions are equivalent…”
“…graphs are isomorphic…”
410
2. Understanding Value Semantics
Collateral Benefit: Terminology
“…objects are the same...”
aaa (equivalent)
In separate named functions:
“…fractions are equivalent…”
“…graphs are isomorphic…”
“…triangles are similar…”
411
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential Property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
412
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential Property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
413
3. Two Important, Instructional Case Studies
Regular Expressions
Important Design Questions:
• What is a Regular Expression?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
414
3. Two Important, Instructional Case Studies
Regular Expressions
Important Design Questions:
• What is a Regular Expression?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
415
3. Two Important, Instructional Case Studies
Regular Expressions
What is a Regular Expression?
416
3. Two Important, Instructional Case Studies
Regular Expressions
What is a Regular Expression?
A Regular Expression describes a
language that can be accepted by a
Finite-State Machine (FSM).
417
3. Two Important, Instructional Case Studies
Regular Expressions
What is a Regular Expression?
A Regular Expression describes a
language that can be accepted by a
Finite-State Machine (FSM).
E.g.,
(1|0)+ describes binary numbers.
418
3. Two Important, Instructional Case Studies
Regular Expressions
Important Design Questions:
• What is a Regular Expression?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
419
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
420
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
A Regular-Expression class imbued
with the value of a regular expression
can be used to determine whether (or
not) arbitrary string tokens are
members of the language that the
regular-expression value denotes.
421
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language; accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
422
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Class Methods
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
423
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Creators
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
424
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Creators
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
425
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Creators
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
426
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Creators
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
427
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Manipulators
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
Whatever the value is.
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
428
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Manipulators
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other); What is the value?
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
429
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Manipulators
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other); Why both?
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
430
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
Accessors
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language: Accepts nothing.
RegEx(const char *regEx);
a.k.a.
RegEx(const RegEx& other);
“accept”
~RegEx(); or
RegEx& operator=(const RegEx& rhs); “matching”
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
431
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language; accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx();
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
432
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language; accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx(); Just one!
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
433
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language; accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other);
~RegEx(); Just one!
RegEx& operator=(const RegEx& rhs);
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
434
3. Two Important, Instructional Case Studies
Regular Expressions
Why create a separate class for it?
class RegEx {
// …
public:
static bool isValid(const char *regEx);
RegEx(); // Empty language; accepts nothing.
RegEx(const char *regEx);
RegEx(const RegEx& other); Let’s think
~RegEx(); Just one!
RegEx& operator=(const RegEx& rhs); about this!
void setValue(const char *regEx);
int setValueIfValid(const char *regEx);
bool isMember(const char *token) const;
};
435
3. Two Important, Instructional Case Studies
Regular Expressions
Important Design Questions:
• What is a Regular Expression?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
436
3. Two Important, Instructional Case Studies
Regular Expressions
Does/should it represent a value?
437
3. Two Important, Instructional Case Studies
Regular Expressions
Does/should it represent a value?
Is a RegEx class a value type, or a
mechanism?
438
3. Two Important, Instructional Case Studies
Regular Expressions
Does/should it represent a value?
Is a RegEx class a value type, or a
mechanism?
I.e., is there an obvious notion of
what it means for two RegEx
objects to have the same value?
439
3. Two Important, Instructional Case Studies
Regular Expressions
Does/should it represent a value?
Is a RegEx class a value type, or a
mechanism?
I.e., is there an obvious notion of
what it means for two RegEx
objects to have the same value?
440
3. Two Important, Instructional Case Studies
Regular Expressions
Important Design Questions:
• What is a Regular Expression?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
441
3. Two Important, Instructional Case Studies
Regular Expressions
How should its value be defined?
1. The string used to create it.
442
3. Two Important, Instructional Case Studies
Regular Expressions
How should its value be defined?
1. The string used to create it.
2. The language it accepts.
443
3. Two Important, Instructional Case Studies
Regular Expressions
How should its value be defined?
1. The string used to create it.
2. The language it accepts.
453
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
I.e., Should our RegEx class
support all of the value-semantic
syntax of a regular class?
Question: How expensive would
operator== be to implement?
454
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
455
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
456
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
457
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[1]?
458
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[1]?
459
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
460
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
461
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
462
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
463
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
464
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
465
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
466
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
467
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
468
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
469
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
470
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
471
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
472
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
NP complete 473
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
NP Complete
P-SPACE 474
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
NP Complete
P-SPACE
P-SPACE Complete
475
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
NP Complete
P-SPACE
P-SPACE Complete
476
Undecidable
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
NP Complete
P-SPACE
P-SPACE Complete
477
Undecidable
3. Two Important, Instructional Case Studies
Regular Expressions
Over an alphabet Σ, given one DFA having states S={si} (of which
A⊆S are accepting) and transition function δ:S×Σ→S, and another
DFA having states T={tj} (of which B⊆T are accepting) and
transition function ζ:T×Σ→T, one can "easily" construct a DFA
with states U=S×T (Cartesian product) and transition function
η((si, tj), σ) = (δ(si, σ), ζ(tj, σ)), where σ e Σ. Then the two original
DFAs are equivalent iff the only states reachable in this Cartesian-
product DFA are a subset of (A×B)∪((S∖A)×(T∖B)) — i.e., it's
impossible to reach a state that is accepting in one of the original
DFAs, but not in the other. Once one has translated the regular
expressions to DFAs, the naive time complexity is O[|Σ||S||T|],
and the space complexity is O[|S||T||Σ|].
478
3. Two Important, Instructional Case Studies
Regular Expressions
Should we avoid value types
Should such a class be regular? where equality comparison
is expensive?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
NP Complete
P-SPACE
P-SPACE Complete
479
Undecidable
3. Two Important, Instructional Case Studies
Regular Expressions
Should such a class be regular?
Question: How expensive would operator== be to implement?
O[log N]
O[sqrt N]
O[N]
O[N * log N]
O[N * sqrt N]
O[N^2]
O[N^2 * log N]
Polynomial
NP
NP Complete
P-SPACE
P-SPACE Complete
480
Undecidable
3. Two Important, Instructional Case Studies
Regular Expressions
Discussion?
481
3. Two Important, Instructional Case Studies
Priority Queues
Important Design Questions:
• What is a Priority Queue?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
482
3. Two Important, Instructional Case Studies
Priority Queues
Important Design Questions:
• What is a Priority Queue?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
483
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue?
484
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue?
A priority queue is a (generic) container that
provides constant-time access to its top
priority element – defined by a user-
supplied priority function (or functor) – as
well as supporting logarithmic-time pushes
and pops of queue-element values.
485
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue?
A priority queue
Salient is a (generic) container that
provides constant-time access to its top
Operations
priority element – defined by a user-
supplied priority function (or functor) – as
well as supporting logarithmic-time pushes
and pops of queue-element values.
486
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue?
Example Queue Element:
class LabeledPoint {
std::string d_label;
int d_x;
int d_y;
public:
// … (Regular Type)
const std::string& label() const { return d_label };
int x() const { return d_x; };
int y() const { return d_y; };
};
3 99 99 80 assert(q.top() == 2 );
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 490
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 Different Priorities,
Different Values
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 491
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 Different Priorities,
Different Values
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 492
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 Same Priority,
Different Values
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 493
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 Same Priority,
Same Value
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 494
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 Same Priority,
Different Values
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 495
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 q.push( 2 );
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 496
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 2 Swap with
parent. q.push( 2 );
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 2 …
0 1 2 3 497
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 2 q.push( 2 );
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 2 …
0 1 2 3 498
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 80 q.push( 2 );
Array-Based Heap: 2 3 30 4 2 31 31 99 99 80 80 …
0 1 2 3 499
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 80 q.push( 2 );
Array-Based Heap: 2 3 30 4 2 31 31 99 99 80 80 …
0 1 2 3 500
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 80 q.push( 2 );
Array-Based Heap: 2 2 30 4 3 31 31 99 99 80 80 …
0 1 2 3 501
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 80 q.push( 2 );
Array-Based Heap: 2 2 30 4 3 31 31 99 99 80 80 …
0 1 2 3 502
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 80 q.push( 2 );
Array-Based Heap: 2 2 30 4 3 31 31 99 99 80 80 …
0 1 2 3 503
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 80 q.pop();
Array-Based Heap: 2 2 30 4 3 31 31 99 99 80 80 …
0 1 2 3 504
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 80 q.pop();
Array-Based Heap: 2 2 30 4 3 31 31 99 99 80 80 …
0 1 2 3 505
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0
calculated priority.
3 99 99 80 80 q.pop();
Array-Based Heap: 2 30 4 3 31 31 99 99 80 80 …
0 1 2 3 506
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
Swap with the
If equally urgent, element having the labeled with its
0 choose the left child. 80 more urgent priority.
calculated priority.
3 99 99 80 q.pop();
Array-Based Heap: 80 2 30 4 3 31 31 99 99 80 …
0 1 2 3 507
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 80 calculated priority.
3 99 99 80 q.pop();
Array-Based Heap: 80 2 30 4 3 31 31 99 99 80 …
0 1 2 3 508
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 q.pop();
Array-Based Heap: 2 80 30 4 3 31 31 99 99 80 …
0 1 2 3 509
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 q.pop();
Array-Based Heap: 2 80 30 4 3 31 31 99 99 80 …
0 1 2 3 510
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 q.pop();
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 511
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 q.pop();
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 512
3. Two Important, Instructional Case Studies
Priority Queues
What is a Priority Queue? Each element is
labeled with its
0 2 calculated priority.
3 99 99 80 q.pop();
Array-Based Heap: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 513
3. Two Important, Instructional Case Studies
Priority Queues
Important Design Questions:
• What is a Priority Queue?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
514
3. Two Important, Instructional Case Studies
Priority Queues
Why create a separate class for it?
515
3. Two Important, Instructional Case Studies
Priority Queues
Why create a separate class for it?
A Priority Queue is a useful data
structure for dispensing value-
semantic (as well as other types of)
objects according to a user-specified
priority order.
516
3. Two Important, Instructional Case Studies
Priority Queues
Important Design Questions:
• What is a Priority Queue?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
517
3. Two Important, Instructional Case Studies
Priority Queues
Does/should it represent a value?
518
3. Two Important, Instructional Case Studies
Priority Queues
Does/should it represent a value?
Is a PriorityQueue class a value
type, or a mechanism?
519
3. Two Important, Instructional Case Studies
Priority Queues
Does/should it represent a value?
Is a PriorityQueue class a value
type, or a mechanism?
I.e., is there an obvious notion of what it
means for two PriorityQueue
objects to have the same value?
520
3. Two Important, Instructional Case Studies
Priority Queues
Does/should it represent a value?
Is a PriorityQueue class a value
type, or a mechanism?
I.e., is there an obvious notion of what it
means for two PriorityQueue
objects to have the same value?
521
3. Two Important, Instructional Case Studies
Priority Queues
Does/should it represent a value?
Is a PriorityQueue class a value
type, or a mechanism?
I.e., is there an obvious notion of what it
means for two PriorityQueue
objects to have the same value?
522
3. Two Important, Instructional Case Studies
Priority Queues
Important Design Questions:
• What is a Priority Queue?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
523
3. Two Important, Instructional Case Studies
Priority Queues
How should its value be defined?
524
3. Two Important, Instructional Case Studies
Priority Queues
How should its value be defined?
525
3. Two Important, Instructional Case Studies
Priority Queues
How should its value be defined?
526
3. Two Important, Instructional Case Studies
Priority Queues
How should its value be defined?
Two objects of class PriorityQueue
have the same value iff there does not
exist a distinguishing sequence among
all of its salient operations:
1. top
2. push
3. pop 527
3. Two Important, Instructional Case Studies
Priority Queues
Important Design Questions:
• What is a Priority Queue?
• Why create a separate class for it?
• Does/should it represent a value?
• How should its value be defined?
• Should such a class be regular?
528
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
I.e., should our PriorityQueue
class support all of the value-
semantic syntax of a regular class?
529
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
I.e., should our PriorityQueue
class support all of the value-
semantic syntax of a regular class?
Question: How expensive would
operator== be to implement?
530
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
531
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Necessary:
533
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Necessary:
- Same number of elements.
534
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Necessary:
- Same number of elements.
- Same numbers of respective element values.
535
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Necessary:
- Same number of elements.
- Same numbers of respective element values.
Sufficient:
536
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Necessary:
- Same number of elements.
- Same numbers of respective element values.
Sufficient:
- Same underlying linear heap order.
537
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Necessary:
- Same number of elements.
- Same numbers of respective element values.
Sufficient:
- Same underlying linear heap order.
BUT IS THIS NECESSARY OR NOT??
538
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
0 1 2 3 539
Array-Based Heap 2: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 539
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
0 1 2 3 540
Array-Based Heap 2: 2 3 30 4 80 31 31 99 99 80 …
0 1 2 3 540
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
But so do these: 1
2 4
Array-Based Heap 1: 1 2 4 3 3
3 3
0 1 2
3 2
Array-Based Heap 2: 1 3 2 3 4
3 4
0 1 2 541
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
542
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
543
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
549
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
550
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
551
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Priority Two
552
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
Priority Two
553
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
Priority Two
554
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
Priority Two
555
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
h
Priority Two
556
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
h
Priority Two
557
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
h
Priority Two
558
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
h
Priority Two
559
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
Priority One
Element Index i
h
Priority Two
N N
Priority One
Element Index i
h
Priority Two
N N
N N
Priority One
Priority Two
Priority One
Priority Two
565
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
566
3. Two Important, Instructional Case Studies
Priority Queues
Should such a class be regular?
Question: How expensive would operator== be to implement?
567
3. Two Important, Instructional Case Studies
Priority Queues
Discussion?
568
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
569
Outline
1. Introduction and Background
Components, Physical Design, and Class Categories
2. Understanding Value Semantics (and Syntax)
Most importantly, the Essential property of Value
3. Two Important, Instructional Case Studies
Specifically, Regular Expressions and Priority Queues
4. Conclusion
What must be remembered when designing value types
570
4. Conclusion
What to Remember about VSTs
571
4. Conclusion
What to Remember about VSTs
So what are the take-aways?
572
4. Conclusion
What to Remember about VSTs
So what are the take-aways?
Some types naturally represent a value.
573
4. Conclusion
What to Remember about VSTs
So what are the take-aways?
Some types naturally represent a value.
Ideally, each value type will have regular syntax.
574
4. Conclusion
What to Remember about VSTs
So what are the take-aways?
Some types naturally represent a value.
Ideally, each value type will have regular syntax.
Moreover, all operations on value types should
follow proper value semantics:
575
4. Conclusion
What to Remember about VSTs
So what are the take-aways?
Some types naturally represent a value.
Ideally, each value type will have regular syntax.
Moreover, all operations on value types should
follow proper value semantics:
Value derives only from autonomous object state,
but not all object state need contribute to value.
576
4. Conclusion
What to Remember about VSTs
So what are the take-aways?
Some types naturally represent a value.
Ideally, each value type will have regular syntax.
Moreover, all operations on value types should
follow proper value semantics:
Value derives only from autonomous object state,
but not all object state need contribute to value.
Adhere to the Essential Property of Value.
577
4. Conclusion
What to Remember about VSTs
So what are the take-aways?
Some types naturally represent a value.
Ideally, each value type will have regular syntax.
Moreover, all operations on value types should
follow proper value semantics:
Value derives only from autonomous object state,
but not all object state need contribute to value.
Adhere to the Essential Property of Value.
Behave as if each value has a canonical internal
representation.
578
4. Conclusion
What to Remember about VSTs
Two objects of a given value-
semantic type have the same
value iff there does not exist a
distinguishing sequence among
all of its salient operations.
579
4. Conclusion
What to Remember about VSTs
The key take-away:
580
4. Conclusion
What to Remember about VSTs
The key take-away:
What makes a value-type proper
has essentially nothing to do with
syntax…
581
4. Conclusion
What to Remember about VSTs
The key take-away:
What makes a value-type proper
has essentially nothing to do with
syntax; it has everything to do with
semantics:
582
4. Conclusion
What to Remember about VSTs
The key take-away:
What makes a value-type proper
has essentially nothing to do with
syntax; it has everything to do with
semantics: A class that respects the
Essential Property of Value is value-
semantic…
583
4. Conclusion
What to Remember about VSTs
The key take-away:
What makes a value-type proper
has essentially nothing to do with
syntax; it has everything to do with
semantics: A class that respects the
Essential Property of Value is value-
semantic; otherwise, it is not!
584
For More Information
• Find our open-source distribution at:
http://www.openbloomberg.com/bde
• Moderator: kpfleming@bloomberg.net
• How to contribute? See our site.
• All comments and criticisms welcome...
• I can be reached at jlakos@bloomberg.net