-
Notifications
You must be signed in to change notification settings - Fork 0
/
softwareOneText.txt
4263 lines (3455 loc) · 185 KB
/
softwareOneText.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
SOFTWARE ONE LECTURES
- Lecture 1 (Course Introduction):
CSE 2221 Software I: Software Components
Restated Learning Outcomes
• Theme 1: software engineering concepts – Be familiar with sound software engineering principles for component-based object-oriented software design
Software Engineering Concepts
• Component-based software engineering
• System thinking
• Mathematical modeling
• Design-by-contract
• Client vs. implementer view
• Object-oriented software building blocks
• Components and their relationships
• Discipline
• Single-point control over change
• Adherence to conventions
Restated Learning Outcomes
• Theme 2: Java programming language
• Be competent with Java programming
Java Programming Language
• Core syntax and features
• Variables, types, values, operators, expressions, control flow (selection, iteration)
• Reference vs. value types
• Interfaces, classes, methods, objects
• Inheritance, polymorphism
• Generics, exceptions
• Libraries
• Input/output, Java’s Swing for GUIs
• Collections (e.g., List, Map, Queue, Set, …)
Restated Learning Outcomes
• Theme 3: industry-standard tools
• Be familiar with the use of industrial-strength software development tools
Industry-Standard Tools
• Eclipse
• Industrial-strength open-source IDE
• Many (free) plug-ins/extensions, including Checkstyle and SpotBugs
• JUnit
• Industry-standard library for unit-testing software components
• Javadoc
• Industry-standard documentation utility for Java programs
Restated Learning Outcomes
• Theme 4: professional best practices
• Be familiar with Java programming “best practices”
Professional Best Practices
• Problem
• Complex language mechanisms make it easy to produce code that is wrong, brittle, inextensible, and hard to maintain
• Solution
• Discipline that helps (but does not guarantee) that developers write better code
• Examples
• Naming conventions, coding conventions
• Design-by-contract and programming-to-the- interface
Prerequisites
• Previous programming experience – Syntax, compilation, execution
• Variables, types, expressions
• Control flow (if, if-else, while, etc.)
• Procedures/functions/methods
• Math maturity (introductory calculus)
• Ability/willingness to learn on your own
• Goal: develop “life-long learning” capabilities
9 May 2023 OSU CSE 10
Resources
• Class meetings
• Ask questions!
• Answer questions!
• Instructor and grader
• Make sure they know you by name
• Visit during office hours or make appointment – Ask questions!
• Answer questions!
• Course web site
• http://web.cse.ohio-state.edu/software/
• All materials and links
• Class website on Carmen
• http://carmen.osu.edu/
• Announcements
• Assignment submissions
• Grades
• Additional materials
• MS Teams CSE 2221 team for this semester
• multiple channels for questions and discussions about course material and assignments
• Online Java tutorials
• http://docs.oracle.com/javase/tutorial/index.html • Online OSU CSE components API – http://cse.osu.edu/software/common/doc/
• Online Java libraries API
• http://docs.oracle.com/javase/8/docs/api/
• Many other Java resources available on the web!
• Many Java books available for free to OSU students via O’Reilly Online Learning
• https://learning.oreilly.com/home/
• Recommended books
• C.S. Horstmann, Java for Everyone, John Wiley and Sons, 2013 https://library.ohio-state.edu/record=b8347056~S7
• J. Bloch, Effective Java, 3nd ed., Prentice Hall, 2018 https://library.ohio-state.edu/record=b9496067~S7
- Lecture 2 (Java Overview):
Java Overview
What is Java?
• Programming language developed in early 1990s by Sun Microsystems (now part of Oracle)
• Based on C/C++
• Similar syntax, control, data structures
• Imperative, object-oriented
• Originally designed for interactive television, found its initial success in Internet applications
• Now viewed as a general-purpose programming language
• Currently enjoys widespread acceptance
Java: Compilation
• The Java compiler checks the source code of a program in a .java file; if and only if there are no compile-time errors, it generates bytecode for that program and saves it in a .class file
• Eclipse has its own Java compiler that continually and incrementally compiles source code even as it is being edited; a compile-time error is seen immediately and bytecode is available immediately if no errors
• A batch-style compiler called javac is part of the Java Development Kit (JDK)
Java: Execution
• The Java Virtual Machine is a virtual computer
• The JVM is just like any other program that runs on real physical hardware (e.g., an Intel chip) and operating system (e.g., Linux, Mac OS X, Windows)
• The “launcher” of the JVM for your computer and OS loads the JVM and your program’s .class file(s), and the JVM then executes your program by interpreting the bytecode that is loaded
• A launcher called java and the JVM are part of the Java Runtime Environment (JRE) for your computer and OS
Java End-to-End
• Java source code (a text file)
• Java compiler generates bytecode from (legal, though not necessarily “correct”) program source code.
• Java bytecode (a “binary” file)
• MyProg.java MyProg.class Launcher loads JVM and your bytecode, which JVM executes by interpreting it.
• Same bytecode can be run on other hardware/OS with its own JVM.
Significance of JVM
• Portability
• Java slogan: “Write once, run anywhere”
• JVM is ubiquitous
• Universality
• Program source code need not be in Java
• Performance
• Extra layer comes at (surprisingly small) penalty in performance
- Lecture 3 (Output, Strings, Input):
Output, Strings, Input
Simplest Java Program?
* public class HelloWorld { public static void main(String[] argos) { System.out.println(“Hello World!”);
* Public class declares this code to be a software component for which bytecode should be generated by the compiler; HelloWorld is the name of the class
* public static void is required here when you want a class to include a “main” program that can be executed by the JVM (and it must be called main)
* String[] argos means that main expects the JVM to hand it an array of Strings (called command-line arguments) when it is executed
* System.out is an object you may use to give output to the user; println is a method of that object that you may call (invoke) to output something on its own line
* “Hello World!” is a character string to be output to the user
Another Version
-----
import components.simplewriter.SimpleWriter;
import components.simplewriter.SimpleWriter1L;
public final class HelloWorld {
private HelloWorld {
}
public static void main (String[] args) {
SimpleWriter out = new SimpleWriter1L();
out.println(“Hello World!”);
out.close();
}
}
-----
* import indicates you want to use a component in your code; components is a package containing OSU CSE components; its simplewriter package offers a few advantages over using built-in System.out
* public means anyone can use this class
* final means no one can incrementally change this class by using inheritance
* private HelloWorld() means the HelloWorld class does not define a type, i.e., no one can create an object from the class HelloWorld because it is a utility class
* SimpleWriter is the type of a newly declared variable; out is the name of that variable
* new creates a new object to which the variable is a reference; SimpleWriter1L is the class whose code should be used when any method of out is called
* out has a println method too, nearly identical to that of System.out
* out has a close method as well, and you need to call it when you are done using out
Output: SimpleWriter
* The OSU CSE components provide a simple way to provide output to a user via the console or a file
-----
SimpleWriter consoleOut = new SimpleWriter1L();
SimpleWriter fileOut = new SimpleWriter1L(“foo.txt”);
-----
Output Examples
-----
consoleOut.print(“Prompt: “);
consoleOut.println();
fileOut.println(“A line.”);
-----
Closing Output
* When you are done writing output to a SimpleWriter stream, you must close the stream:
-----
consoleOut.close();
fileOut.close();
-----
Character Strings
* Java has special features to deal with character strings
* Examples
-----
SimpleWriter fileOut = new SimpleWriter1L(“foo.txt”);
fileOut.print(“Hi, Mr. Foo.”);
-----
* Java has special features to deal with character strings
* Example
* “foo.txt” is a character string
* “Hi, Mr. Foo.” is a character string
* This intro is just the tip of the iceberg!
Character-String Literals
* Character-string constants, also called String literals, are enclosed in double-quotes, e.g.: “Hello World!”
* Character strings can be concatenated (joined together to create new character strings) using the + operator, e.g.: “Hello “ + “World!”
String Variables
* You may declare a String variable, and assign an initial character-string value to it, as follows: String cheer = “Go”;
* You may assign any other character-string value to the same variable later, e.g.: cheer = cheer + “ Bucks!”;
Input: SimpleReader
* The OSU CSE components provide a simple way to get input from a user via the keyboard or a file
-----
SimpleReader keyboardIn = new SimpleReader1L();
SimpleReader fileIn = new SimpleReader1L(:foo.txt”);
-----
Input Examples
-----
String line = keyboardIn.nextLine();
line = fileIn.nextLine();
-----
* The nextLine() method, which reads up through and including the next line separator, is really the only method you need to read input from the keyboard and text files.
Closing Input
* When you are done reading input from a SimpleReader stream, you must close the stream:
-----
keyboardIn.close();
fileIn.close();
-----
Resources
* Java Tutorials (“Hello World” program)
* http://docs.oracle.com/javase/tutorial/getStarted/application/index.html
* OSU CSE components API (SimpleWriter, SimpleReader)
* http://cse.osu.edu/software/common/doc/
- Lecture 4 (Variables, Types, Values):
Variables, Types, Values
Variables
* A variable is the name of a “location” that “stores” a value of a particular type
* We might say the variable “has” that value
* We might say the variable “has” that type or “is of” that type
Types
* A type is the name of the set of all possible values that a variable might have
* Examples:
* A variable of type String might have values like “foo”, “Hello World”, etc.
* A variable of type int might have values like -1.18,etc
* A variable of type double might have values like 3.1416, 10.0, etc
Program vs. Mathematical Variables
* A program variable has a particular value at any one time during program execution, and that value (generally) may change at other times
* A mathematical variable stands for an arbitrary but fixed value
* A program type has a corresponding mathematical type that models it
* When reasoning about a program variable of a given program type, treat its value at any given time as of it were a mathematical variable of the corresponding mathematical type.
* Mathematical Models
* Program Type
* String
* Mathematical Type: string of character
* boolean
* Mathematical Type: boolean
* char
* Mathematical Type: character
* int
* Mathematical Type: integer (-2147483648 through 2147483648)
* double
* Mathematical Type: real (about plus or minus 10 ^(plus or minus 308), 15 significant digits)
* String is built-in to Java; boolean, char, int, and double are among the 8 primitive (and also built-in) types of Java
* All these mathematical types are “built-in” to mathematics
Declaring a Variable
* When you declare a program variable, you both provide a name for a location to store its value, and indicate its program type
* Recall: the program type determines the mathematical type, which in turn determines the possible values the variable can have
* The standard Java convention for naming variables is to use camel case: start with a lowercase letter and only capitalize the first letter of each following word, e.g., myLuckyNumber
Initializing a Variable
* To initialize a variable, you assign it a value
* Recall: the program type determines the mathematical type, which in turn determines the possible values the variable can have
Literals
* A data value appearing, literally, in a program is called a literal
-----
String fileName = “foo.txt”
boolean found = false;
char win = ‘W’;
int j = 13;
double ht = 9.27;
-----
* “foo.txt” is a String literal; written as characters between double-quote marks: “...”
* false is a boolean literal; must either be true or false.
* ‘W’ is a char literal; normally written as a single character between single-quote marks: ‘...’
* 13 is an int literal; normally written (as in mathematics) as a decimal constant
* 9.27 is a double literal; normally written (as in mathematics) as a decimal constant with a decimal point
Forms of Literals
* Program Type
* String
* Literal examples
* “I\’m’”
* “at OSU”
* boolean
* Literal examples
* true
* false
* char
* Literal examples
* ‘A’
* ‘\t’
* ‘\”’
* ‘\u03c0’
* int
* Literal examples
* 29
* -13
* 035
* 0x1a
* double
* Literal examples
* 18.
* 18.0
* 8E-4
* 6.022E23
Constants
* A variable whose value is initialized and never changed is called a constant
-----
final int myLuckyNumber = 13;
final double avogadro - 6.022E23;
-----
* The keyword final indicates to the compiler your intent that a variable is actually a constant
* When constants are declared inside a method, the standard Java convention is to use camel case just like for variables.
* When constants are declared at the class level, the standard Java convention is to use all uppercase letters and to separate the words with ’_’.
Resources
* Java for Everyone, Chapter 2
* https://library.ohio-state.edu/record=b8347056%7ES7
- Lecture 5 (Operators, Expressions, Statements, Control Flow)
Operators, Expressions, Statements, Control Flow
Operators
* An operator is a symbol (or combination of a couple symbols) that is used with variables and values to simplify how you write certain program expressions
* Usually, operators are designed to mimic mathematical notation - but do not be fooled into confusing programming and mathematics!
Most Common Operators
* String
* +
* boolean
* !
* ||
* &&
* ==
* !=
* char
* <
* >
* <=
* >=
* ==
* !=
* int
* ++
* --
* +
* -
* *
* /
* %
* <
* >
* <=
* >=
* ==
* !=
* double
* +
* -
* *
* /
* <
* >
* Best Practice: do not use == or != with Strings, but rather the equals method
* Operators for or (||) and and(&&) use short-circuit evaluation
* Best Practice: be careful with the remainder (%) operator: the second operand must be positive; this is, unfortunately, not “clock arithmetic”
* Best practice: do not check doubles for equality
Expressions
* An expression is a “syntactically well-formed and meaningful fragment” (roughly analogous to a word in natural language)
* Meaningful?
* It has a value (of some type, of course)
Some Expressions
* Examples of code fragments that are expressions:
* i
* j + 7
* “Hello” + “World!”
* keyboardIn.nextLine()
* n == 0
* new SimpleWriter1L()
* This fragment creates a new object type SimpleWriter1L, and its value is a reference to that object
Statements
* A statement is a “smallest complete unit of execution” (roughly analogous to a sentence in natural language)
* A simple statement is terminated with a semicolon ‘;’
Simple Statements
* Some examples of simple statements
* i = 12;
* j += 7;
* This is the same as j = j + 7;
* SimpleWriter fileOut = new SimpleWriter1L(“foo.txt”);
* fileout.print(“Hi, Mr. Foo”);
Assignment Statement
* Assignment statement form;
* variable = expression;
* Copies the value of the expression on the right side of the assignment operator = to the variable on the left side
* The = in Java code does not mean “equals” like in math!
Compound Statements / Blocks
* Any sequence of zero or more statements enclosed in {...} is a block
* Example:
-----
{
String s = in.nextLine();
out.println(“s = “ + s);
}
-----
* The scope of variable s is just the block in which it is declares
* There is no semicolon after a block.
Control Flow
* Conditional or selection statements
* if
* if-else
* if-else-if
* switch
* Loop or iteration statements
* while
* for
* do-while
* if statement
-----
if (test) {
then_block
}
-----
* Any boolean expression may go in the test area
* Best Practice: even a single statement here should be in a block.
* if-else statement
-----
if (test) {
then_block
} else {
else_block
}
-----
* Best Practice: Even a single statement here should be in a block
* if-else-if statement
-----
if (test_1) {
then_block_1
} else if (test_2) {
then_block_2
} else {
else_block
}
-----
* The else if part may be repeated
* while statement
-----
while (test) {
while_block
}
-----
Best Practices for boolean
* If you want to say this, e.g., in an if or while condition:
* b == true
* Say this instead:
* b
* b == false
* Say this instead:
* !b
Resources
* Java for Everyone, Chapter 3
* Java for Everyone, Chapter 4
* https://library.ohio-state.edu/record=b8347056%7ES7
- Lecture 6 (Monte Carlo Estimation)
Monte Carlo Estimation
Monte Carlo Methods
• Class of computational methods that use random sampling to estimate results – Named after the famous Monte Carlo Casino
- Lecture 7 (Static Methods)
Static Methods
Static Method
• A static method (class method) is a block of code with a name, using which it can be called (invoked) to perform its computation
• The method “takes over” execution when it is called, until it returns to the calling program at the point it was called
• Also known as a routine, subroutine, operation, function, or procedure
Anatomy of a Static Method
-----
private static int distance( int a, int b) {
int d = b – a;
return d;
}
-----
• The method header includes the method's return type, its name, and its parameter list. The method name and the parameter types comprise the method signature.
• The method body consists of the block of code that is executed when the method is called.
• private limits the places from which this static method may be called: only from within this class; public here would allow it to be called from other classes, too.
• int means the method provides a value of this type to the caller when it returns; void here would mean the method provides no value at all.
• distance is the name of this static method, which is used when calling it.
• int a is the first formal parameter of the method, whose initial value is supplied at the point of the call; int b is the second formal parameter method is a statement that hands control back to the caller if a value is returned by the method, then an expression after return provides this value.
Return Statements
• Every path of execution through a method that returns a value must end in a return statement with an expression of the return type of the method
• A method that does not return a value may have return statement(s) without any such expression; but by default, it returns to the caller anyway when the method body completes execution
Resources
• Java for Everyone, Chapter 5
– https://library.ohio-state.edu/record=b8347056~S7 18 January 2021 OSU CSE 13
- Lecture 8 (Parameter Passing)
Parameter Passing
Connecting Caller and Callee
• When you call a method, how are the arguments connected to the formal parameters?
• When the called method body returns, how are results communicated back to the code that called the method?
Example: GCD
• Suppose we have a static method gcd that computes and returns the greatest common divisor (GCD) of two ints:
-----
public static int gcd(int i, int j) { ...
}
-----
• For example:
– GCD(24,80) = 8
– GCD(24,24) = 24
How Calls Work In Java
-----
public static int gcd(int i, int j) {
int k = 1;
...
return k;
}
...
int a, b;
...
int c = gcd(a, b);
-----
• This is the method gcd that is being called; i and j are its formal parameters.
• This is a fragment of the calling program; a and b are the arguments to this call of gcd.
• Suppose the solid red arrow indicates where program flow-of control has taken us so far.
Connecting Caller and Callee
• When you call a method, how are the arguments connected to the formal parameters?
• The argument values are copied into the formal parameters to initialize them
• When the called method body returns, how are results communicated back to the code that called the method?
• Only the returned value is copied back to the caller; the formal parameters are simply “lost”
Names for This?
• Parameter-passing mechanism of Java: – May be termed call-by-copying because argument values are copied into formal parameters
• May be termed call-by-value because argument values are copied into formal parameters
• There are other ways it might have been done (and is done in some languages)
- Lecture 9 (Arrays)
Arrays
Array
• 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
Compare to Mathematics
• This is entirely parallel to the use of subscripted variables in mathematics, e.g., x0, x1, …
• Just as x0 is pronounced “x-sub-0” in mathematics, a[0] is usually pronounced “a-sub-0” in a Java program
• Consider, similarly, xi+2 and a[i+2] 24 January 2021 OSU CSE 3
• In mathematics, a group of related variables x0, x1, …, xn-1 is called a vector x of length n
• In Java, a group of variables a[0], a[1], …, a[n-1] is called an array a of length n
Declaring an Array
int[] a;
• The [] in this declaration indicates there will be some number of variables named a[0], a[1], … But, how many?
Declaring and Creating an Array
int[] a = new int[4];
• This many! Here, 4 is called the length of the array, and it is the value of another variable introduced by this declaration: a.length
Declaring and Initializing an Array
int[] a = { 6, 18, 9, –10 };
• Here again, we have:
• a.length = 4
• But now the 4 array elements have different initial values:
• a[0] = 6
• a[1] = 18, etc.
Array Indexing with Constants
• You may write an int constant (literal) c between […] as in a[c], so long as its value satisfies:
• 0 ≤ c < a.length
• Example:
• int[] a = new int[4];
• a[3] = 17;
Array Indexing in General
• You may write an int-valued expression exp between […] as in a[exp], so long as its value satisfies:
• 0 ≤ exp < a.length
• Example:
• int[] a = new int[4];
• a[a.length – 1] = 17;
• After this code is executed, we have: a[3] = 17
Resources
• Java Tutorials
– http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html • Java for Everyone, Chapter 6 – https://library.ohio-state.edu/record=b8347056~S724 January 2021 OSU CSE 21
- Lecture 10 (Design-by-Contract)
Design-by-Contract
Systems Thinking
• A system is any part of anything that you want to think about as an indivisible unit • An interface is a description of the “boundary” between a system and everything else, that also describes how to think about that system as a unit
• A subsystem (component) is a system that is used inside, i.e., as a part of, another system — a relative notion!
Example: Ice/Water Dispenser
• Select water, crushed ice, or cubed ice. Place a glass against the pad and push.
People’s Roles wrt Systems
• A client is a person (or a role played by some agent) viewing a system “from the outside” as an indivisible unit
• An implementer is a person (or a role played by some agent) viewing a system “from the inside” as an assembly of subsystems/components
Describing Behavior: Part 1
• One side of the coin: information hiding is a technique for describing system behavior in which you intentionally leave out “internal implementation details” of the system
Describing Behavior: Part 2
• Other side of the coin (and a necessary consequence of information hiding): abstraction is a technique in which you create a valid cover story to counteract the effects of hiding some internal implementation details
• Presumably the hidden information is relevant to the system behavior, so even if you hide it you still need to account for its presence!
Overview of Design-by-Contract
• Also known as programming-to-the interface
• Articulated clearly only in the 1980s • Design-by-contract has become the standard policy governing “separation of concerns” across modern software engineering
• This is how software components are really used…
Recall: Mathematical Models
• Each variable in the program has a type
• Examples: int, double, …
• Each program type has a mathematical type that models it: you should think of any variable of that program type as having a value from its mathematical model’s mathematical space/domain
• Examples (respectively): integer, real, …
Informal Models
• Models are not always formal mathematical models like integers, real numbers, etc., but can be based on informal concepts from other situations
• Example of an anthropomorphic description of behavior:
• “This TV remembers the last channel you watched.”
• More examples to come…
Structure of a Method Contract
• Each method has:
• A precondition (requires clause) that characterizes the responsibility of the program that calls (uses) that method (client code)
• A postcondition (ensures clause) that characterizes the responsibility of the program that implements that method (implementation code in the method body)
Meaning of a Method Contract
• If its precondition is true when a method is called, then the method will terminate — return to the calling program — and the postcondition will be true when it does return
• If its precondition is not true when a method is called, then the method may do anything (including not terminate)
Responsibilities and Rewards
• Responsibility: Making sure the precondition is true when a method is called is the responsibility of the client
• Reward: The client may assume the postcondition is true when the method returns
• Responsibility: Making sure the postcondition is true when a method returns is the responsibility of the implementer
• Reward: The implementer may assume the precondition is true when the method is called
Recall: Static (Class) Methods
• A static method (class method) is one that:
• Has zero or more formal parameters of various types — placeholders for the arguments that appear in the call between (…)
• Returns a value of a particular return type to the calling program; or, returns nothing, denoted by a return type of void
Example of a Contract
-----
/**
* ...
* @param x number to take the square root of * @param epsilon allowed relative error
* @return the approximate square root of x * @requires
* x > 0 and epsilon > 0
* @ensures <pre>
* sqrt >= 0 and
* [sqrt is within relative error epsilon * of the actual square root of x]
* </pre>
*/
private static double sqrt(double x, double epsilon)
-----
• A Java comment that starts is called a Javadoc comment; it goes before the method header.
• The Javadoc tag @param is needed for each formal parameter; you describe the parameter’s role in the method.
• The Javadoc tag @return is needed if the method returns a value; you describe the returned value.
• The Javadoc tag @requires introduces the precondition for the sqrt method.
• The Javadoc tag @ensures introduces the postcondition for the sqrt method.
• Javadoc comments may contain HTML-like tags; e.g., <pre> ... </pre> means spacing and line-breaks are retained in generated documentation
Javadoc
• The standard documentation technique for Java is called Javadoc
• You place special Javadoc comments enclosed in /** … */ in your code, and the javadoc tool generates nicely formatted web-based documentation from them
APIs
• The resulting documentation is known as the API (application programming interface) for the Java code to which the Javadoc tags are attached
• The API for the OSU CSE components is at:
• http://web.cse.ohio-state.edu/software/common/doc/ 26 January 2021 OSU CSE 19
• The word interface has two related but distinct meanings:
• a unit of Java code that contains Javadoc comments used to produce documentation
• the resulting documentation
Abbreviated Javadoc
• For this course:
• Any actual code you ee in *.java files will have the full Javadoc comments, as above
• Some code you see in these slides will not have the Javadoc tags @param, @return, and formatting tags <pre>; plus, "keywords" in the Javadoc and mathematics will be bold-faced for easy reading
• This allows you to focus on the contract content: this requires and ensures clauses themselves
Example Contract (Abbreviated)
-----
/**
* ...
* @requires
* x > 0 and epsilon > 0
* @ensures
* sqrt >= 0 and
* [sqrt is within relative error epsilon * of the actual square root of x] */
private static double sqrt(double x, double epsilon)
-----
• @requires This is the precondition, indicating that the arguments passed in for the formal parameters x and epsilon both must be positive before a client may call sqrt.
• @ensures This is the postcondition, indicating that the return value
• The first part of the postcondition here is written in mathematical notation; it is not program code! The second part - inside [...] - is written in English
Using a Method Contract
• A static method’s contract refers to its formal parameters, and (only if it returns a value, not void) to the name of the method (which stands for the return value)
• To determine whether the precondition and postcondition are true for a particular client call:
• The model values of the arguments are substituted for the respective formal parameters
• The model value of the result returned by the method is substituted for the method name
A Partly Informal Contract
-----
/**
* ...
* @requires
* x > 0 and epsilon > 0
* @ensures
* sqrt >= 0 and
* [sqrt is within relative error epsilon * of the actual square root of x] */
private static double sqrt(double x, double epsilon)
-----
A Formal Contract
-----
/**
* ...
* @requires
* x > 0 and epsilon > 0
* @ensures
* sqrt >= 0 and
* |sqrt - x^(1/2)| / x^(1/2) <= epsilon */
private static double sqrt(double x, double epsilon)
-----
• We can, in this formal setting, easily substitute 4.0 for x, 0.01 for epsilon, and either 2.0 or 1.9996 for sqrt … and is the postcondition true in either case? Yes!
A Method Body
-----
private static double sqrt(double x, double epsilon) {
assert x > 0.0 : "Violation of: x > 0";
assert epsilon > 0.0 : "Violation of: epsilon > 0";
// rest of body: compute the square root
}
-----
• The assert statement in Java checks whether a condition (an assertion) is true; if it is not, it stops execution and reports the message after the colon.
• But why are there assert statements in this method body to check what the implementer is supposed to assume?
Checking a Precondition
• During software development, it is a best practice to check assumptions with assert when it is easy to do so
• This checking can be turned on and off (on by using the “-ea” argument to the JVM)
• When turned off, assert is documentation • Preconditions generally are easy to check; postconditions generally are not easy to check
A Misconception
• A common misconception is that using assert statements to check
preconditions contradicts design-by contract principles
• It does not, because the advice is not to deliver software with assertion-checking turned on, but rather to develop software with assertion-checking turned on — to help catch your mistakes, not the client’s!
Resources
• Wikipedia: Design by Contract
– http://en.wikipedia.org/wiki/Design_by_contract 26 January 2021 OSU CSE 45
- Lecture 11 (Trees)
Trees
A New Math Type: tree
• A ubiquitous concept in computing is that of a tree
• Often we are interested in a binary tree, a special case of a tree in which each node has at most two children
• An informal introduction (“node”?, “children”?) follows, using pictures rather than any new mathematical notation
Recursive Structure
• A tree is made up of:
• A root node
• A string of zero or more child nodes of the root, each of which is the root of its own tree
• Since a tree may contain other trees, its structure is recursive
• Note: the following explanation of trees is adequate for present purposes but is not technically complete; details later…
Resources
• Wikipedia: Tree structure
– http://en.wikipedia.org/wiki/Tree_structure
31 January 2023 OSU CSE 24
- Lecture 12 (XML Documents)
XML Documents
eXtensible Markup Language
• A textual document format used all over the web is XML
• Used to represent hierarchically organized data for “ease of use” both by humans and computers
• Had its origins in SGML (Standard Generalized Markup Language) from the 1980s
• Became a standard in the late 1990s
Example XML Document/File
-----
<?xml version="1.0" encoding="UTF-8"?>
<book printISBN="978-1-118-06331-6" webISBN="1-118063-31-7" pubDate="Dec 20 2011">
<author>Cay Horstmann</author>
<title>
Java for Everyone: Late Objects
</title>
...
</book>
-----
• An XML declaration is the first line of well formed XML file.
• <author>Cay Horstmann> is an author element.
• <author> is a start tag for an author element.
• </author> is an end tag for that author element
• The content for this author element is everything between its start and end tags.
• If the author element had no content, then you might find this: <author></author>
• Or you might find a single self-closing tag like this: <author />
• <title>Java for Everyone: Late objects</title> is a title element
• The book element contains the title and author elements.
• printISBN is the name of an attribute of the book element
• 978-1-118-06331-6 is the value of the printISBN attribute.
Recursive Structure
• An XML document (without the XML declaration in the first line) is made up of:
• A top-level element
• A string of zero or more child elements of the top-level element, each of which is exactly like the top-level element of an XML document
• Notice the similarity to a tree: the structure of an XML document is also recursive
• Information it represents is hierarchical
Resources
• Big Java, Section 23.1 (but not the rest of Chapter 23)
– https://library.ohio-state.edu/record=b9476806~S7 • Wikipedia: XML
– http://en.wikipedia.org/wiki/XML
5 May 2016 OSU CSE 18
- Lecture 13 (XMLTree Model)
XMLTree Model
XMLTree
• The XMLTree component family allows you to create, and navigate through, a tree whose structure mirrors that of an XML file
• The file from which the tree is created may come from your computer or from the web – You need not worry about parsing the file (recognizing tags, matching start-end tags, identifying attributes, etc.), as this is done for you by XMLTree
• The attribute name-value pairs of an element/tag are in the tree node of that element/tag.
• The children of the top-level element/tag are the children of the root of the tree.
• The first child node of the root is known as "child 0" because children are numbered from 0.
• The second child node of the root is known as "child 1".
• The third child node of the root is known as "child 2".
• The content of an element/tag is in a child node of the node for that element/tag; the content node itself has no tag.
… And So On!
• The same rules apply at all levels of the XML file and of the XMLTree object that is created from it
Key Properties/Invariants
• Every node in the tree represents either a tag (e.g., <author>) or the text content (e.g., "Cay Horstman") of an element
• Every node in the tree has a label String that is either the tag name (e.g., "author") or the text content itself (e.g., "Cay Horstman")
• Only tag nodes can have zero or more attribute name-value pairs, each of which is a String (e.g., "pubDate" → "Dec 20 2011")
Resources
• OSU CSE Components API: XMLTree – http://web.cse.ohio-state.edu/software/common/doc/
13 September 2022 OSU CSE 26
- Lecture 14 (XMLTree Methods)
XMLTree Methods
Methods for XMLTree
• All the methods for XMLTree are instance methods, i.e., you call them as follows - t.methodName(arguments) - where t is an initialized variable of type XMLTree
Methods for XMLTree
• All the methods for XMLTree are instance methods, i.e., you call them as follows: t.methodName(arguments) where t is an initialized variable of type XMLTree
• t is called the receiver of the call; for all instance methods, the corresponding distinguished formal parameter implicitly has the name this.
Implementations of XMLTree
• There are two different classes that implement the XMLTree interface contract, and you may use either one: XMLTree1 or XMLTree2
• This choice is made when you initialize a variable of type XMLTree, where you must use the name of one of these implementation classes as the name of the constructor
• The behavior of an XMLTree does not depend on which use the name of one of these implementation you choose; this is a implementation classes as the name of the constructor key benefit of design-by-contract!
Interface and Implementing Classes
• XMLTree1 implements XMLTree
• XMLTree2 implements XMLTree
• The interface XMLTree has method signatures and contracts for methods.
• The class XMLTree1 has method bodies, and so does XMLTree2
• The method bodies in XMLTree1 implement the method contracts in XMLTree
• The method bodies in XMLTree2 implement the method contracts in XMLTree
Mathematical Model
• The value of an XMLTree variable is modeled as a tree of nodes whose labels are explained in the previous set of slides
• Note that this model is described informally, though it could be formalized into mathematical notation
Constructors
• There are two constructors for each implementation class
• The name of the constructor is the name of the implementation class
• Constructors differ only in their parameters
• For XMLTree, we will use only the constructor that takes one String parameter, either:
• The name of an XML file on your computer