200 likes | 356 Views
Why is programming fun?. What delights may its practitioner expect as a reward? First is the sheer joy of making things Second is the pleasure of making things that are useful Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts
E N D
Why is programming fun? What delights may its practitioner expect as a reward? First is the sheer joy of making things Second is the pleasure of making things that are useful Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts Fourth is the joy of always learning Finally, there is the delight of working in such a tractable medium. The programmer, like the poet, works only slightly removed from pure thought-stuff. Fred Brooks
Building Programs and Classes • To develop a program: start small • Get a core working, and add to the core • Keep the program working, easier to find errors when you’re only working on small amount of new functionality • Grow a program incrementally rather than building a program all at once • Start with a prototype • Incomplete, but reasonable facsimile to the final project • Help debug design, ideas, code, … • Get feedback to stay on track in developing program • From users, from compiler, from friends, from yourself
Design Heuristics • Make each function or class you write as single-purpose as possible • Avoid functions that do more than one thing, such as reading numbers and calculating an average, standard deviation, maximal number, etc., • If source of numbers changes how do we do statistics? • If we want only the average, what do we do? • Classes should embody one concept, not several. The behavior/methods should be closely related • This heuristic is called Cohesion, we want functions and classes to be cohesive, doing one thing rather than several • Easier to re-use in multiple contexts
Design Heuristics continued • Functions and classes must interact to be useful • One function calls another • One class uses another, e.g., as the Dice.roll() function uses the class java.util.Random • Keep interactions minimal so that classes and functions don’t rely too heavily on each other, we want to be able to change one class or function (to make it more efficient, for example) without changing all the code that uses it • Some coupling is necessary for functions/classes to communicate, but keep coupling loose • Change class/function with minimal impact
Efficient Programming • Designing and building efficient programs efficiently requires knowledge and practice • Hopefully the programming language helps, it’s not intended to get in the way • Object-oriented concepts, and more general programming concepts help in developing programs • Knowledge of data structures and algorithms helps • Tools of the engineer/scientist programmer • A library or toolkit is essential, don’t reinvent the wheel • Someone must build the tools • Programming is not just art, not just science, not just engineering
Tradeoffs • Programming should be about tradeoffs: programming, structural, algorithmic • Programming: simple, elegant, quick to run/to program • Tension between simplicity and elegance? • Structural: how to structure data for efficiency • What issues in efficiency? Time, space, programmer-time • Algorithmic: similar to structural issues • How do we decide which choice to make, what tradeoffs are important?
Flexibility • About FPGAs compared to general computers • “The most common type of computing system is the general-purpose processor. Under this model, the hardware of the system is limited to merely a few basic tasks. By combining and building off of these operations, a general-purpose computer can perform a much larger number of operations than it was originally designed to handle. Which is why the general-purpose computer is so flexible. However this flexibility comes with a price. For any specific application, the general-purpose processor will perform poorly when compared to a custom hardware implementation” http://www.tomfry.com/thesis.doc
Toward understanding inheritance • Consider Yahtzee program • Several kinds of score-card entries: aboveline, fullhouse,… • What do we do to add a new kind, or change definition • Edit working program, add code to code that already works • Not haphazard, but dangerous: if it ain’t broke, don’t touch • The “open-closed” principle of program building/design • Programs/classes should be open for extension, but closed to modification (Bertrand Meyer and Robert Martin) • How do we change code without altering it? • This is a goal, in practice we modify some, but minimize • Inheritance lets us realize the principle (in theory)
Use interfaces, not implementations • See yahtzee program, ScoreEntry, DiceGroup • Subclasses: AboveLine, FullHouse, ThreeKind, … • Subclasses: CupOfDice and FixedDice (game and testing) • We have parent, base, or super-class for interface • Child or Subclassesextend the parent class (implement interface) • Pointer/reference to parent can also reference child object • I’m pointing at an animal (could be marsupial or bird) • Child/sub classes don’t have access to private data/functions, but the data are there (alternative: use protected) • See ScoreEntry for details
Inheritance and the Yahtzee program • Simple version of Yahtzee: all information in ScoreCard class • Adding new entries causes ScoreCard to be recompiled, may cause other classes using ScoreCard to be recompiled • Consequences of large-scale recompiling? What about building large programs (word, XP, etc.) • Changes made in several places to add new ScoreEntry • String for description, code for scoring, order of entries in ScoreCard • Code in different places, related, must be synchronized • Inheritance is an answer to problem of avoiding recompiling, facilitating testing, keeping related code together
Why inheritance? • Add new shapes easily without changing much code • Shape sp = new Circle(); • Shape sp2 = new Square(); • abstract base class (ABC) • Interface (method names) • Some code/fields provided • concrete subclass • implementation • provide a version of all abstract functions • “is-a” view of inheritance • Substitutable for, usable in all cases as-a shape mammal ScoreEntry FullHouse, LargeStraight User’s eye view: think and program with abstractions, realize different, but conforming implementations, don’t commit to something concrete until as late as possible
Guidelines for using inheritance • Create a base/super/parent class that specifies the behavior that will be implemented in subclasses • Some functions in base class may be abstract • Subclasses required to implement, or cannot create object • Consider using an interface if there’s no default behavior or state to provide • Inheritance models “is-a” relationship, a subclass is-a parent-class, can be used-as-a, is substitutable-for • Standard examples include animals and shapes • Square should NOT derive/inherit from rectangle • A square is NOT a rectangle in programming terms
See Student.java School.java • How do subclass objects call parent class code? • Use super(…) syntax, calls up the inheritance tree • In constructor, super(…) must be first line • What if Student.getName() is declared as public final? • Cannot override in subclasses • NOT in AP subset • What if no public getEnergy() or getName() • Must be accessed directly in subclasses, why? • Could make protected, not accessible to “general public” • But, to all classes in same package/directory
Inheritance (language independent) • First view: exploit common interfaces in programming • Streams in C++, Iterator in Java • Iterators in STL/C++ share interface by convention/templates • Implementation varies while interface stays the same • Second view: share code, factor code into parent class • Code in parent class shared by subclasses • Subclasses can override inherited method • Can subclasses override and call? • Polymorphism/late(runtime) binding (compare: static) • Actual function called determined when program runs, not when program is compiled
Inheritance Heuristics • A base/parent class is an interface • Subclasses implement the interface • Behavior changes in subclasses, but there’s commonality • The base/parent class can supply some default behavior • Derived classes can use, override, both • The base/parent class can have state • Protected: inherited and directly accessible • Private: inherited but not accessible directly • Abstract base classes are a good thing • Push common behavior as high up as possible in an inheritance hierarchy • If the subclasses aren’t used polymorphically (e.g., through a pointer to the base class) then the inheritance hierarchy is probably flawed
Problems with inheritance • Consider the student example and burrito eating • CosmicStudent is a subclass of DukeStudent • What behavior changes in the new subclass? • What about a UNCStudent eating cosmic cantina food? • Can we have CosmicDukeStudent and CosmicUNCStudent? • Problems with this approach? • Alternative to inheritance: use delegation (aka layering, composition) • Just like myEnergy is a state variable with different values, make myEater a state variable with different values • Delegate behavior to another object rather than implementing it directly
Delegation with school/student • If there's a class Eater, then what instance variable/field will a Student store to which eating behavior delegated? // in class Student public void eat() { myEater.doEat(); } • How is the eater instance variable initialized? • Could we adopt this approach for studying too? • When is this approach better/worse?
Visibility of methods/fields/classes • Methods/fields: public, private, protected, default/package • java.util is a package: related classes uses folder/directory • Packages are often “packaged” in a jar file (java archive) • Classes also have visibility • One public class per file, other classes in same file? • Nested classes can be part of an object, or static [class]
Top ten reasons to prefer JMBS (stolen from Julie Zelenski) 10 A graphical interface is a beautiful thing (even when the code is terrible?) 9 Requires using jar files, jam and jelly can’t be far behind 8 Everything is a pointer, no fish update problem 7 We can pretend this is a real simulation instead of fish swimming around and looking pretty 6 Printed narrative good for pulp-industry: Big-AP
Top ten MBS continued 5 Inheritance is easily motiviated (interfaces too) 4 Gender neutrality of Pat and Jamie leaves open speculation about outside-work relationship 3 Fish are cute 2 There is a main, but it’s not testable 1 Starts with only three classes: Fish, Environment, Simulation (and one isn’t even a class!)