arrays and references · i call it my billion-dollar mistake. it was the invention of the null...
TRANSCRIPT
Arrays and References
19 February 2019 OSU CSE 1
The Original (Partial) Story• An array is a group of similar variables, all
of the same type, and with systematically related names that involve special syntax using […]
• Each array element, e.g., a[0], a[1], …, acts like a single variable of the type used in the declaration of array a
• The variable named a.length contains the number of array elements
19 February 2019 OSU CSE 2
a O a IT a alength I
int[] a = { 6, 18, 9, –10 };
19 February 2019 OSU CSE 3
The Original (Partial) Picture
6 18 9 -10
4
this is howwe pictured
arrays
The Full Story• In addition, you need to know:
– Arrays are reference types– The name of the array (e.g., a in the example)
is a reference to the entire collection of element variables a[0], a[1], …, anda.length
19 February 2019 OSU CSE 4
int[] a = { 6, 18, 9, –10 };
19 February 2019 OSU CSE 5
The Full Picture
6 18 9 -10
4
more likely pictured g Itala
Arrays Are Reference Types
• You should now be able to predict what happens when you do the following:– Assign one array to another using =– Pass an array as a parameter to a method– Return an array from a method– Compare two arrays for equality with ==– But... what does equals do?
19 February 2019 OSU CSE 6
D into b a
aiTb
pass private static void funcinto b E
funcla
a.iTb T
return fonchifreefloatingobjectif notassigned it
Eisame
array't array2
0 31122 04071 e comparingmemoryaddresses
aa
equals we will see
One of the Many Warts of Java
• The equals method for arrays does arguably the wrong thing: it compares reference values just like ==– You might expect it would compare arrays
“element-wise”, and the lengths of the arrays, but it does not
– Fortunately, SpotBugs flags the use of equals and explains it is equivalent to ==
19 February 2019 OSU CSE 7
What Can Be Done?
• You can try to write your own code to check whether two arrays are element-wise equal (but this is surprisingly hard to get right!)
• You can use code from the Java libraries in the package java.util– See the class Arrays– Use the static method Arrays.deepEquals
19 February 2019 OSU CSE 8
import java util Arrays
What Can Be Done?
• You can try to write your own code to check whether two arrays are element-wise equal (but this is surprisingly hard to get right!)
• You can use code from the Java libraries in the package java.util– See the class Arrays– Use the static method Arrays.deepEquals
19 February 2019 OSU CSE 9
This is the handiest package in the Java libraries for general-
purpose use; you should know about it.
Best Practices for Arrays
• Avoid them in industrial-strength software– OK in exercises intended to demonstrate the
basics of arrays (because there is so much Java code “in the wild” that uses arrays), and in simple throw-away programs
• Recommended alternatives:– Java libraries: java.util.List interface
with ArrayList implementation– OSU CSE components: Array, Sequence
19 February 2019 OSU CSE 10
minimumweight
obviously can't use in industry either
depends on situation
Sometimes a fixed length array is what you need
however often times a dynamic data structure is necessaryvariable length
Resources
• Java Tutorials– http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
• Java for Everyone, Section 6.1– http://proquest.safaribooksonline.com.proxy.lib.ohio-state.edu/book/-
/9781118063316/chapter-6-arrays-and-array-lists/250
• Java Libraries API: Arrays– http://docs.oracle.com/javase/8/docs/api/
• Effective Java, Item 25– http://proquest.safaribooksonline.com.proxy.lib.ohio-
state.edu/book/programming/java/9780137150021/chapter-5-generics/ch05
19 February 2019 OSU CSE 11
Contracts
7 January 2019 OSU CSE 1
Contract Details• Contracts in the APIs for OSU CSE
components include these important features:– Parameter modes– Two stipulations:
• Parameter names in requires and ensures clauses always stand for the object values, never the reference values, of the corresponding arguments to a method call
• Reference-type arguments are always non-null
7 January 2019 OSU CSE 2
whichwewill talk about
conditions
requires m 5 Cnn'sobjval 5
ie an object mustbedefined
Contract Details• Contracts in the APIs for OSU CSE
components include these important features:– Parameter modes– Two stipulations:
• Parameter names in requires and ensures clauses always stand for the object values, never the reference values, of the corresponding arguments to a method call
• Reference-type arguments are always non-null
7 January 2019 OSU CSE 3
These are local decisions that apply to OSU CSE components’ contracts; there are no industry standards (yet) that govern how
to write contracts.
i e restoresetc only existto OSUhowever companies can implement theirown togovernmethodcontracts
Parameter Modes• There are four parameter modes, each of
which indicates a possible way that a method might change the value of the corresponding argument
• Parameter modes help us in three ways:– They concisely summarize which arguments
might have their values modified by a call– They make requires/ensures clauses shorter – They allow us to perform “sanity checks” of
contracts against certain simple errors7 January 2019 OSU CSE 4
Iclears mus
shouldthis nn be 0 ensures m owhydidmynn value change
Parameter Modes• There are four parameter modes, each of
which indicates a possible way that a method might change the value of the corresponding argument
• Parameter modes help us in three ways:– They concisely summarize which arguments
might have their values modified by a call– They make requires/ensures clauses shorter – They allow us to perform “sanity checks” of
contracts against certain simple errors7 January 2019 OSU CSE 5
Modes are listed for the formal parameters, including this,
but actually apply to their corresponding arguments for a
call, including the receiver.
this is because of the connection with referencetypes
Restores Mode• Upon return from a method call, a
restores-mode parameter once again has its incoming value– Equivalent to adding, e.g., ... and x = #x
to the ensures clause– An old restores-mode parameter, e.g., #x,
should not appear in the ensures clause– This is the default parameter mode, so if a
parameter is not listed with some other mode then its mode is restores
7 January 2019 OSU CSE 6
DPM if a param is not in clearsetc assume it is restoredrestoresi samevalue out as in
Clears Mode• Upon return from a method call, a clears-
mode parameter has an initial value for its type, i.e., a value that an assignment of the no-argument constructor could give it– Equivalent to adding, e.g., ... and x = [an initial value for its type] to the ensures clause
– A clears-mode parameter, e.g., x, should not appear in the ensures clause except as #x
7 January 2019 OSU CSE 7
next slide possible a no ay constructor doesn't exist
because this obviously contradicts
Clears Mode• Upon return from a method call, a clears-
mode parameter has an initial value for its type, i.e., a value that an assignment of the no-argument constructor could give it– Equivalent to adding, e.g., ... and x = [an initial value for its type] to the ensures clause
– A clears-mode parameter, e.g., x, should not appear in the ensures clause except as #x
7 January 2019 OSU CSE 8
It’s possible there isn’t a no-argument constructor; see the
contract for the clear method in interface Standard for technical
details.
Examplevoid transferFrom(NaturalNumber n)
• Sets this to the incoming value of n, and resets n to an initial value.
• Replaces: this• Clears: n• Ensures:this = #n
7 January 2019 OSU CSE 9
replaces receiver
clears input argument
Replaces Mode• Upon return from a method call, a
replaces-mode parameter has a value that might be changed from its incoming value, but the method’s behavior does not depend on its incoming value– A replaces-mode parameter, e.g., x, should
not appear in the requires clause, and #xshould not appear in the ensures clause
7 January 2019 OSU CSE 10
Example
void copyFrom(NaturalNumber n)
• Copies n to this.• Replaces: this• Ensures:this = n
7 January 2019 OSU CSE 11
changesreceiver's object value
note doesn'tdependon this
Updates Mode• Upon return from a method call, an
updates-mode parameter has a value that might be changed from its incoming value, and the method’s behavior does depend on its incoming value
7 January 2019 OSU CSE 12
Updates Mode• Upon return from a method call, an
updates-mode parameter has a value that might be changed from its incoming value, and the method’s behavior does depend on its incoming value
7 January 2019 OSU CSE 13
In other words, both replaces and updates modes indicate that the parameter can change value. The difference is that for the former, the behavior of the method is independent of the
incoming value, while for the latter it isn't.
summarizes
differencebetweenreplaces
updates
Example
void add(NaturalNumber n)
• Adds n to this.• Updates: this• Ensures:this = #this + n
7 January 2019 OSU CSE 14
Uses old value of this
Parameters Stand for Object Values
• When a parameter name is used in a requires or ensures clause, with or without the # to indicate the incoming value, it stands for the object value of the corresponding argument
7 January 2019 OSU CSE 15
Example
void copyFrom(NaturalNumber n)
• Copies n to this.• Replaces: this• Ensures:this = n
7 January 2019 OSU CSE 16
Using the objectvalve of n
and replacing object value of this
Which Means It Does This...
7 January 2019 OSU CSE 17
Code Statem = 143k = 70
m.copyFrom(k);
m = 70k = 70
orM 70K 70
... Not This!
7 January 2019 OSU CSE 18
Code Statem = 143k = 70
m.copyFrom(k);
m, k ڵ 70M 70
K 70
... Not This!
7 January 2019 OSU CSE 19
Code Statem = 143k = 70
m.copyFrom(k);
m, k ڵ 70
What line of code would result in this outcome?
M K implies
M a DoK LT
Null References• In Java, any reference variable may be
given the special value null, meaning that it does not refer to any object at all:
String s = null;
7 January 2019 OSU CSE 20
Null References• In Java, any reference variable may be
given the special value null, meaning that it does not refer to any object at all:
String s = null;
7 January 2019 OSU CSE 21
This is special notation to replace the arrow when a
reference is null.
in circuits thisis ground
Best Practices for Null References
• It is not unusual to find such null references in Java code, even though it is often easy to avoid using them, and it is now considered a good idea to try to avoid making references null
• The most common cause of crashes in Java is NullPointerException, which means the code attempted to follow a null reference to the (non-existent) object to which it refers
7 January 2019 OSU CSE 22
String s nulloutprinth s ANullPointerEx
Best Practices for Null References
I call it my billion-dollar mistake. It was the invention of the null reference in 1965. ... I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
— Sir C.A.R. Hoare, 2009• Pretty much says it all...
7 January 2019 OSU CSE 23
QuickSort Algorithmnullreferences
don't use null
Non-Null References Required
• OSU CSE components’ contracts stipulate that no argument to any method may have a null reference value– Hence, there can be no question about what a
reference-type parameter stands for in a requires or ensures clause: the reference always points to an object, and the parameter stands for that object value
7 January 2019 OSU CSE 24
very important never have null in code
Resources• Null References: The Billion Dollar Mistake
– http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare
7 January 2019 OSU CSE 25
Repeated Arguments
7 January 2019 OSU CSE 1
Sources of Aliasing
• Aliased references for mutable types can cause trouble, so it is important to know how aliases might arise
• One way (which is easy to recognize and easy to record in a tracing table, using 䚐) is the simple assignment of one reference variable to another
• There are other sources of aliasing as well...
7 January 2019 OSU CSE 2
NaturalNumber n2 n1
Aliasing from Parameter Passing
• Because a formal parameter of a reference type is initialized by copying the corresponding argument’s reference value (which is tantamount to assignment of the argument to the formal parameter), parameter passing is another source of aliasing
7 January 2019 OSU CSE 3
private static void doSomething NaturalNumber n Epublicstaticvoidmain string args n1 n
NaturalNumber n1 new NaturalNumber1L s arealiases
doSomething n1
Example
• Consider this method:/**
* Adds 1 to the first number and 2 to the
* second.
* ...
* @updates x, y
* @ensures* x = #x + 1 and y = #y + 2
*/
private static void foo(NaturalNumber x,
NaturalNumber y) {...}
7 January 2019 OSU CSE 4
Example
• Consider this method:/**
* Adds 1 to the first number and 2 to the
* second.
* ...
* @updates x, y
* @ensures* x = #x + 1 and y = #y + 2
*/
private static void foo(NaturalNumber x,
NaturalNumber y) {...}
7 January 2019 OSU CSE 5
How would you implement this contract specification?
using increment
orNN 2 NN I then addfunction
Example: A Call
• Consider this call of the method:NaturalNumber a = new NaturalNumber2(10);
NaturalNumber b = new NaturalNumber2(319);
foo(a, b);
• How does this get executed, and what values result for a and b?
7 January 2019 OSU CSE 6
11 321
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
NaturalNumber b = new NaturalNumber2(319);
foo(a, b);
7 January 2019 OSU CSE 7
31910in main we have
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
NaturalNumber b = new NaturalNumber2(319);
foo(a, b);
7 January 2019 OSU CSE 8
10 319
foorefValcopied
main
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
NaturalNumber b = new NaturalNumber2(319);
foo(a, b);
7 January 2019 OSU CSE 9
10 319wehavethis
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
NaturalNumber b = new NaturalNumber2(319);
foo(a, b);
7 January 2019 OSU CSE 10
11 321afterdoingXH
y12
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
NaturalNumber b = new NaturalNumber2(319);
foo(a, b);
7 January 2019 OSU CSE 11
11 321
X yreferences disappear when method exits
Note: Harmless Aliasing
• Aliases are created, but since the method body for foo only has access to the variables x and y (i.e., the variables used as arguments in the client code, a and b, are not in scope while the body of foo is executing), these aliases cause no trouble for reasoning
7 January 2019 OSU CSE 12
reasoning being thinking about endresultof somestints
i e we can't simultaneously manipulate theobject values of Xia or yolbso we're still chilling
Example: A Different Call
• Now consider this call of the method:NaturalNumber a = new NaturalNumber2(10);
foo(a, a);
• How does this happen, and what value results for a?
7 January 2019 OSU CSE 13
a 13but didn't the ensures say
X X t I
y y 2
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
foo(a, a);
7 January 2019 OSU CSE 14
10
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
foo(a, a);
7 January 2019 OSU CSE 15
10
create ourparametersin foo
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
foo(a, a);
7 January 2019 OSU CSE 16
10
in foo
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
foo(a, a);
7 January 2019 OSU CSE 17
13
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
foo(a, a);
7 January 2019 OSU CSE 18
13
Can we really be sure the resulting value is 13?
Perhaps surprisingly, no!
the ensures parameter mode
How Calls Work In Javapublic static void foo(NaturalNumber x, NaturalNumber y) {...
}
NaturalNumber a = new NaturalNumber2(10);
foo(a, a);
7 January 2019 OSU CSE 19
13
Note: Harmful Aliasing
• Here, aliases are created between two variables that are in scope while the method body for foo is executing (i.e., the variables x and y), and these aliases do cause trouble for reasoning
• Who is at fault for this anomalous outcome?– The implementer of foo?– The client of foo?
7 January 2019 OSU CSE 20
in essence morethan I reference to an object valve in scope
I would argue both implementer no precondition
client being an idiot
What Outcome Was Expected?
7 January 2019 OSU CSE 21
Code State
a = 10
foo(a, a);
What Outcome Was Expected?
7 January 2019 OSU CSE 22
Code State
a = 10
foo(a, a);
Consult the contract for foo, substituting a for both
parameters x and y;it ensures:
a = 11 and a = 12
What Outcome Was Expected?
7 January 2019 OSU CSE 23
Code State
a = 10
foo(a, a);
a = 11a = 12
Can we really have this outcome?
Repeated Arguments
• In this case, it would be impossible for any implementation of foo to produce the outcome supposedly ensured according to its contract!
• The trouble arising from repeated arguments (i.e., a call like foo(a, a)) is not just in Java; it is a problem in any language with mutable types
7 January 2019 OSU CSE 24
a a as arguments
reference not really an issuewith primitives
The Receiver Is An Argument
• Note that the reference value of the receiver of a call (to an instance method) is copied to the formal parameter known as this
• Hence, there is a repeated argument if the receiver is also passed as another argument to such a call
• Example:n.add(n);
7 January 2019 OSU CSE 25
The Receiver Is An Argument
• Note that the reference value of the receiver of a call (to an instance method) is copied to the formal parameter known as this
• Hence, there is a repeated argument if the receiver is also passed as another argument to such a call
• Example:n.add(n);
7 January 2019 OSU CSE 26
Does this call double n, as you might expect from
using informal reasoning and “wishful naming” to predict the outcome?
The Receiver Is An Argument
• Note that the reference value of the receiver of a call (to an instance method) is copied to the formal parameter known as this
• Hence, there is a repeated argument if the receiver is also passed as another argument to such a call
• Example:n.add(n);
7 January 2019 OSU CSE 27
Why, given the contract for add, can this call simply
not be a good idea?
Unexpected behavior
turn off assertionsand
13 4110 H
s soI 10
Best Practice for Repeated Arguments
• Never pass any variable of a mutable reference type as an argument twice or more to a single method call– Remember that the receiver is an argument
• Checkstyle and SpotBugs do not warn you about this!
7 January 2019 OSU CSE 28