Quick Review of Object-Oriented Programming in Go

Similar documents
Last Time: Objects and Abstraction. If it walks like a circle, swims like a circle, and quacks like a circle...!

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

Module 10 Inheritance, Virtual Functions, and Polymorphism

Object Oriented Programming in C#

Introduzione a Go e RPC in Go

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Name: Class: Date: 2. I have four vertices. I have four right angles and all my sides are the same length.

Programovací jazyky F# a OCaml. Chapter 3. Composing primitive types into data

Object-Oriented Programming Concepts

More C++ : Vectors, Classes, Inheritance, Templates

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Java Object Oriented Design. CSC207 Fall 2014

ame Date Class Practice A 11. What is another name for a regular quadrilateral with four right angles?

What is a Programming Paradigm

Erlang and Go (CS262a, Berkeley Fall 2016) Philipp Moritz

Clean Classes. Christopher Simpkins Chris Simpkins (Georgia Tech) CS 2340 Objects and Design CS / 11

Name: Date: Period: Lab: Inscribed Quadrilaterals

MENSURATION-I (Area & Perimeter) In this chapter, we shall be dealing with plane figures of various shapes finding their sides, perimeters and

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from HW4

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Lines Plane A flat surface that has no thickness and extends forever.

Introduction to Computers and Java

Aim: How do we find the volume of a figure with a given base? Get Ready: The region R is bounded by the curves. y = x 2 + 1

Polygons - Part 1. Triangles

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed


Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Programming in the Large II: Objects and Classes (Part 2)

OBJECT ORIENTED PROGRAMMING

Object Design Guidelines

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Outline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism

1. Software Systems Complexity, OO Paradigm, UML

Geometry Vocabulary. acute angle-an angle measuring less than 90 degrees

Math 6, Unit 8 Notes: Geometric Relationships

An angle that has a measure less than a right angle.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

8. prove that triangle is a scalene triangle, right triangle, and/or an isosceles triangle. (evaluation)

Shapes. Reflection Symmetry. Exercise: Draw the lines of symmetry of the following shapes. Remember! J. Portelli

CS-202 Introduction to Object Oriented Programming

ITI Introduction to Computing II

Last Time: Rolling a Weighted Die

Practice Problems for Geometry from

OBJECT ORİENTATİON ENCAPSULATİON

Introduction to Object-Oriented Programming

Properties of Triangles

Definition: Convex polygon A convex polygon is a polygon in which the measure of each interior angle is less than 180º.

SENIOR HIGH MATH LEAGUE April 24, GROUP III Emphasis on GEOMETRY SECTION I: ONE POINT EACH

Spiral Back: Evaluate the following when x = -2 and y = 3 1) -4y x + (3+ x 2 ) Solve the following equations: 2) x 6 = -20 3) 2x 2 = -16 4)

Stanford CS193p. Developing Applications for ios. Spring CS193p. Spring 2016

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

ITI Introduction to Computing II

Structured Programming

Geometry: Semester 2 Practice Final Unofficial Worked Out Solutions by Earl Whitney

Object Oriented Programming 2015/16. Final Exam June 28, 2016

UNIT 6 Nets and Surface Area Overhead Slides

GM1.1 Consolidation Worksheet Answers

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011

Binghamton University. CS-211 Fall Object Orientation

CC Geometry H Do Now: Complete the following: Quadrilaterals

Digits. Value The numbers a digit. Standard Form. Expanded Form. The symbols used to show numbers: 0,1,2,3,4,5,6,7,8,9

Lesson 4.3 Ways of Proving that Quadrilaterals are Parallelograms

Object-Oriented Programming for Scientific Computing

MSO Lecture 1. Wouter Swierstra (adapted by HP) September 11, 2017

Closed shapes with straight sides

Yimin Math Centre. 6.1 Properties of geometrical figures Recognising plane shapes... 1

Mensuration: Basic Concepts and Important Formulas

Tokens, Expressions and Control Structures

5.1 Any Way You Slice It

Lecture #1. Introduction to Classes and Objects

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Module 01 Processing Recap

ECE 3574: Dynamic Polymorphism using Inheritance

Word Tutorial 4 Enhancing Page Layout and Design

(SSOL) Simple Shape Oriented Language

Introduction to Design Patterns

JAVA: A Primer. By: Amrita Rajagopal

Conditionals & Loops /

Contents. Lines, angles and polygons: Parallel lines and angles. Triangles. Quadrilaterals. Angles in polygons. Congruence.

Basic Object-Orientation

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

Geometry. Geometry is the study of shapes and sizes. The next few pages will review some basic geometry facts. Enjoy the short lesson on geometry.

index.pdf January 21,

3. Here is a stem and leaf plot of the Weights of students in East Junior High Algebra I Class

Object Model. Object Orientated Analysis and Design. Benjamin Kenwright

5th Grade Geometry

Programming, numerics and optimization

Triangle Geometry Isometric Triangles Lesson 1

Last class. -More on polymorphism -super -Introduction to interfaces

Module 01 Processing Recap. CS 106 Winter 2018

New Perspectives on Microsoft Word Module 4: Enhancing Page Layout and Design

Transcription:

Quick Review of Object-Oriented Programming in Go 02-201

Structs: Grouping Variables as Objects type Rectangle struct { x1 float64 y1 float64 width float64 height float64 type Circle struct { x1 float64 y1 float64 radius float64

Area Functions for Shapes? func Area(R Rectangle) float64 { return R.width * R.length func Area(C Circle) float64 { return math.pi * C.radius * C.radius

Area Functions for Shapes? func Area(R Rectangle) float64 { return R.width * R.length func Area(C Circle) float64 { return math.pi * C.radius * C.radius Error! Can t name two functions the same thing.

Workaround: Methods func (R Rectangle) Area() float64 { return R.width*R.length func (C Circle) Area() float64 { return R.radius * R.radius * math.pi Call these methods with R.Area() and C.Area() same setup that we used for accessing fields.

Pointers Help Us Change Fields Inside Method We couldn t access fields inside a method... func (C Circle) DoubleRadius() { C.radius = 2*C.radius Solution: Take a pointer to a Circle as the input. func (C *Circle) DoubleRadius() { C.radius = 2*C.radius // note double-meaning of *

Inheritance and Polymorphism 02-201

Rectangle Fields/Methods type Rectangle struct { x1,y1 float64 width, height float64 fillcolor color.color strokecolor color.color linewidth int Natural to create an object type for each shape: Circle Oval Triangle Star Square. These methods are needed for all shapes. func (r *Rectangle) Area() float64 func (r *Rectangle) MoveTo(x,y int) func (r *Rectangle) Resize(w,h int) func (r *Rectangle) Draw(d *DrawingCanvas) func (r *Rectangle) SetLineWidth(w int) func (r *Rectangle) ContainsPoint(x,y int)

Circle Fields/Methods type Circle struct { x0,y0 int radius int fillcolor color.color strokecolor color.color linewidth int Natural to create an object type for each shape: Circle Oval Triangle Star Square. These methods are needed for all shapes. func (c *Circle) Area() float64 func (c *Circle) MoveTo(x,y int) func (c *Circle) Resize(w,h int) func (c *Circle) Draw(d *DrawingCanvas) func (c *Circle) SetLineWidth(w int) func (c *Circle) ContainsPoint(x,y int)

Applying Canvas Methods to All Shapes type ShapeCanvas struct { width, height int backgroundcolor color.color shapes []???? But what type should go here???! func (c *ShapeCanvas) ShapeArea() float64{ sum := 0.0 for shape := range c.shapes { sum += shape.area() return sum

Solution: Interfaces type ShapeCanvas struct { width, height int backgroundcolor color.color shapes []Shape type Shape interface { Area() float64 MoveTo(x,y int) Resize(w,h int) Draw(c *DrawingCanvas) SetLineWidth(w int) The interface contains the methods shared by its types.

Solution: Interfaces type ShapeCanvas struct { width, height int backgroundcolor color.color shapes []Shape func (c *ShapeCanvas) ShapeArea() float64{ sum := 0.0 for shape := range c.shapes { sum += shape.area() return sum Note: We don t have to say that Circle/Square are Shapes!

interface{ As a Universal Type We also can use interface{ as a universal type. func main() float64{ var x interface{ // x can take any type! x = 3 fmt.println(x) x = AGT // no error here! fmt.println(x) Note: This is not a reason to ignore types.

interface{ As a Universal Type

Information-Hiding in Go When we examine the details of fmt.print(), we see 1300 lines of ugly, complicated functions.

Information-Hiding in Go When we examine the details of fmt.print(), we see 1300 lines of ugly, complicated functions. But do we need to know any of this in order to print an int?

Information-Hiding in Go When we call fmt.println( Hello world! )... this function calls within the fmt package fmt.fprintln(os.stdout, Hello world! )... which in turn calls p := newprinter() p.doprintf( Hello world!, true, true)...

Information-Hiding in Go which is very complicated... func (p *pp) doprint(a []interface{, addspace, addnewline bool) { prevstring := false for argnum := 0; argnum < len(a); argnum++ { p.fmt.clearflags() // always add spaces if we're doing Println arg := a[argnum] if argnum > 0 { isstring := arg!= nil && reflect.typeof(arg).kind() == reflect.string if addspace!isstring &&!prevstring { p.buf.writebyte(' ') prevstring = p.printarg(arg, 'v', 0) if addnewline { p.buf.writebyte('\n')

Information-Hiding in Go Not only do we not need to know exactly what this does... p := fmt.newprinter() p.doprintf( Hello world!, true, true)... but this gives us a compile error! // undefined: fmt.newprinter Think: Why would Go not allow us to access this function?

Public/Private Functions in Go 1. Public: accessible outside of the package (with import packagename ). Begin with upper case letter. 2. Private: accessible only to other functions within the package; can never be accessed with import packagename ). Begin with lower case letter. func UPGMA(mtx [][]float64) *Tree // can be accessed from outside package (public) func averagedist(mtx [][]float64, clusters []Cluster, i,j,k int) float64 // helper function for UPGMA (private)

Has vs. Is A struct has certain properties. A circle has a radius A Contact has a first name A Flight has a duration But how can we represent is? A circle is a shape A Contact is a person A City is a node in a network

Ordering Shapes Hierarchically Shapes Ellipses Triangles Stars Quadrilaterals Circles Equilateral Isosceles Parallelogram Rhombus Rectangle Square

Ordering Vehicles in a Video Game?

Previously: Interfaces type ShapeCanvas struct { width, height int backgroundcolor color.color shapes []Shape type Shape interface { Area() float64 MoveTo(x,y int) Resize(w,h int) Draw(c *DrawingCanvas) SetLineWidth(w int) But interfaces only allow objects to share methods...

One Possible Field-Sharing Solution type Automobile struct { width, height float64 topspeed float64 numoftires int type Car struct { auto Automobile numberofdoors int type Ferrari struct { car Car // other stuff that makes a Ferrari func main() { vroom := new(ferrrari) vroom.ctopspeed = 187.4 // error!

One Possible Field-Sharing Solution type Automobile struct { width, height float64 topspeed float64 numoftires int type Car struct { auto Automobile numberofdoors int type Ferrari struct { car Car // other stuff that makes a Ferrari func main() { vroom := new(ferrrari) vroom.car.auto.topspeed = 187.4 // ugly!

Better Idea: Anonymous Fields type Automobile struct { width, height float64 topspeed float64 numoftires int type Car struct { Automobile //a Car is an Automobile numberofdoors int type Ferrari struct { Car //a Ferrari is a Car // other stuff that makes a Ferrari func main() { vroom := new(ferrrari) vroom.topspeed = 187.4 // this works!

Better Idea: Anonymous Fields Furthermore, a Ferrari can be used in place of a Car or Automobile anywhere we like in functions. func (a *Automobile) Start() { // It would probably be more natural to use interfaces for most functions, though each car will drive differently. func main() { vroom := new(ferrari) vroom.start() // this works!

Another Example of Anonymous Fields type Parallelogram struct { x1, y1 float64 width, height float64 theta float64 type Rectangle struct { Parallelogram //anonymous field func (p *Parallelogram) Area() float64 { return p.width * p.height func main() { r := new(rectangle) r.width, r.height = 3.0, 5.0 //OK! fmt.println(r.area()) //OK! Prints 15

! Four Defining Principles of OOP Abstraction! Encapsulation! Object-! Oriented! Programming! Inheritance!! Polymorphism!

Abstraction If it walks like a circle, swims like a circle, and quacks like a circle...

Abstraction An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer. Courtesy: Gary Booch!

Abstraction The main example of abstraction in Go is with structs and methods. type Rectangle struct { x1,y1 float64 width, height float64 fillcolor color.color strokecolor color.color linewidth int func (r *Rectangle) Area() float64 func (r *Rectangle) MoveTo(x,y int) func (r *Rectangle) Resize(w,h int) func (r *Rectangle) Draw(d *DrawingCanvas) func (r *Rectangle) SetLineWidth(w int) func (r *Rectangle) ContainsPoint(x,y int)

Encapsulation Encapsulation: group together related things, and hide as many details as possible from the user. Examples in Go: Functions: to use fmt.printf() we only need to know what it takes and what it returns. Packages: Inside the fmt package is 1279 lines of code, but we only need to know public functions. Interfaces: I have a Shape, but I don t need to know what kind of shape in order to resize it.

Say something about HW6 Here

Note about HW6 This is why we are anal about the function requirements in HW6 In practice, the boss won t care about how you implement something. They just want the product to have certain properties.

Inheritance Inheritance: the ability for one class of objects to inherit the properties of another class. type Automobile struct { width, height float64 topspeed float64 numoftires int type Car struct { Automobile //a Car is an Automobile numberofdoors int type Ferrari struct { Car //a Ferrari is a Car // other stuff that makes a Ferrari

Polymorphism Polymorphism: the ability to have the same interface for presenting different objects. type Shape interface { Area() float64 MoveTo(x,y int) Resize(w,h int) func (C *Circle) Area() float64 { return math.pi * C.radius * C.radius func (R *Rectangle) Area() float64 { return R.width * R.length

Polymorphism This may seem heavily related to inheritance, so let me give a better example. x := Hello y := World! a := 3 b := 4 fmt.println(a+b, x+y) Strings and ints are unrelated, but Go can interpret the + symbol in different ways for both types.