SlideShare une entreprise Scribd logo
1  sur  51
Object-Oriented
Lesson Zero
2017/01/09
Taka Wang
Programming Paradims
• Procedural/Structured Programming
• COBOL, FORTRAN, BASIC, PASCAL, C…
• Object-Oriented Programming
• Smalltalk, C++, C#, Java…
• Functional Programming
• F#, Scala, OCaml, Erlang…
Class and Object
• class object
• Class
(Instance)
• Object
(Class) (Object)
Behavior State
Class and Object
Constructor
class CoOrds
{
public int x, y;
// Default constructor:
public CoOrds()
{
x = 0;
y = 0;
}
// A constructor with two arguments:
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
// Override the ToString method:
public override string ToString()
{
return (String.Format("({0},{1})", x, y));
}
}
class MainClass
{
static void Main()
{
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);
// Display the results using the
// overriden ToString method:
Console.WriteLine("CoOrds #1 at {0}", p1);
Console.WriteLine("CoOrds #2 at {0}", p2);
Console.ReadKey();
}
}
/* Output:
CoOrds #1 at (0,0)
CoOrds #2 at (5,3)
*/
Instantiation
constructors
• Inheritance
• Encapsulation
• Polymorphism
Inheritance
“Because inheritance exposes a subclass
to details of its parent's implementation,
it's often said that "inheritance breaks
encapsulation”
Gang of Four, Design Patterns (Chapter 1)
“Favor Composition over inheritance”
Gang of Four, Design Patterns
“Use of classical inheritance is always
optional; every problem that it solves can
be solved another way.”
Sandi Metz
Inheritance Hell
This is why you need Composition over Inheritance
Diamond Problem in C++
int main(void) {
D d(10);
d.set(20);
cout << d.get() << endl;
return 0;
}
class A{
public:
A (int x) : m_x(x) {}
int m_x;
};
class B : public A {
public:
B (int x) : A(x) {}
void set(int x) {
this -> m_x = x;
}
};
class C : public A {
public:
C (int x) : A(x) {}
int get(void) {
return this -> m_x;
}
};
class D : public B,public C {
public:
D (int x) : B(x),C(x) {}
};
Diamond Problem in C++
int main(void) {
D d(10);
d.set(20);
cout << d.get() << endl;
return 0;
}
class A{
public:
A (int x) : m_x(x) {}
int m_x;
};
class B : public A {
public:
B (int x) : A(x) {}
void set(int x) {
this -> m_x = x;
}
};
class C : public A {
public:
C (int x) : A(x) {}
int get(void) {
return this -> m_x;
}
};
class D : public B,public C {
public:
D (int x) : B(x),C(x) {}
};
D
B
A
C
A
HOME_SEARCH_BAR
- textField
+ search()
+ init()
( )
HOME_SEARCH_BAR
- textField
+ search()
+ init()
PAGE_SEARCH_BAR
- overlay
+ prompt()
( )
HOME_SEARCH_BAR
- textField
+ search()
+ init()
PAGE_SEARCH_BAR
- overlay
+ prompt()
LOCAL_SEARCH_BAR
+ search()
( )
HOME_SEARCH_BAR
- textField
+ search()
+ init()
PAGE_SEARCH_BAR
- overlay
+ prompt()
LOCAL_SEARCH_BAR
+ search()
HOME_SEARCH_BAR
- textField
+ search()
+ init()
+ initWithStyle()
( )
Animal
Cat
Cat
Animal
animal
Inheritance Composition
is-a
has-a
Favor Composition over inheritance
Encapsulation
•
• /
• Encapsulation
• public
• protected
• internal (Assembly)
• private
C# - Encapsulation
C# Example
class Rectangle
{
//member variables
private double length;
private double width;
public void Acceptdetails()
{
Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
Override and Overload
• Overload ( )
• (class) (Parameter)
(Method)
• Override ( )
• extends( ) method
• Overriding argument, parameter, method name, return type
(function signature)
Java - Overloading ( ) Overriding ( )
C# Example
class A
{
public virtual void Y()
{
// Used when C is referenced through A.
Console.WriteLine("A.Y");
}
}
class B : A
{
public override void Y()
{
// Used when B is referenced through A.
Console.WriteLine("B.Y");
}
}
class Program
{
public static void Main()
{
ShowString();
ShowString("Category");
}
static void ShowString()
{
ShowString("Popular");
}
static void ShowString(string value)
{
Console.WriteLine(value);
}
}
override overload
Polymorphism
• Polymorphism means that the sender of a stimulus does not need to
know the receiving instance’s class. The receiving instance can
belonging to an arbitrary class.
• If an instance sends a stimulus to another instance, but does not
have to be aware of which class the receiving instance belongs to,
we say that we have polymorphism.
Object-Oriented Software Engineering: A Use Case Driven Approach
Polymorphism
public class Shape
{
public int X { get; private set; }
public int Y { get; private set; }
public int Height { get; set; }
public int Width { get; set; }
// Virtual method
public virtual void Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}
class Circle : Shape
{
public override void Draw()
{
// Code to draw a circle...
Console.WriteLine("Drawing a circle");
base.Draw();
}
}
class Rectangle : Shape
{
public override void Draw()
{
// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}
static void Main(string[] args)
{
System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>();
shapes.Add(new Rectangle());
shapes.Add(new Circle());
foreach (Shape s in shapes)
{
s.Draw();
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
package main
import "fmt"
type Human interface {
myStereotype() string
}
type Man struct {
}
func (m Man) myStereotype() string {
return "I'm going fishing."
}
type Woman struct {
}
func (m Woman) myStereotype() string {
return "I'm going shopping."
}
func main() {
m := new (Man)
w := new (Woman)
//an array of Humans - we don't know whether Man or Woman
hArr := [...]Human{m, w} //array of 2 Humans. One is the type Man, one is the type Woman.
for n, _ := range (hArr) {
//appears as human type, but behavior changes depending on actual instance
fmt.Println("I'm a human, and my stereotype is: ", hArr[n].myStereotype())
}
}
“ When I see a bird that walks like a duck and
swims like a duck and quacks like a duck, I
call that bird a duck.”
Indiana poet James Whitcomb Riley
Duck typing
• can work the same as polymorphism, but without inheritance
• Polymorphism (in the context of object-oriented programming) means a subclass can
override a method of the base class. This means a method of a class can do different
things in subclasses. For example: a class Animal can have a method talk() and the
subclasses Dog and Cat of Animal can let the method talk() make different sounds.
• Duck typing means code will simply accept any object that has a particular method.
Let's say we have the following code: animal.quack(). If the given object animal has
the method we want to call then we're good (no additional type requirements needed).
It does not matter whether animal is actually a Duck or a different animal which also
happens to quack. That's why it is called duck typing: if it looks like a duck (e.g., it has
a method called quack() then we can act as if that object is a duck).
What is the difference between polymorphism and duck typing?
• Interface:
• An Interface is a special type of class that only provides a
specification (not an implementation) for its abstract members.
• Abstract classes:
• The main purpose of an abstract class is to define a common
interface for its subclasses.
Interface
• An interface defines the signature operations of an entity, it also sets
the communication boundary between two entities, in this case two
pieces of software. It generally refers to an abstraction that an asset
provides of itself to the outside.
• The main idea of an interface is to separate functions from
implementations.
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/interface.html
Delegation
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html
Delegation is like inheritance done manually through object composition.
public interface ISoundBehaviour {
public void makeSound();
}
public class MeowSound implements ISoundBehaviour {
public void makeSound() {
System.out.println("Meow");
}
}
public class RoarSound implements ISoundBehaviour {
public void makeSound() {
System.out.println("Roar!");
}
}
public class Cat {
private ISoundBehaviour sound = new MeowSound();
public void makeSound() {
this.sound.makeSound();
}
public void setSoundBehaviour(ISoundBehaviour newsound) {
this.sound = newsound;
}
}
public class Main {
public static void main(String args[]) {
Cat c = new Cat();
// Delegation
c.makeSound(); // Output: Meow
// now to change the sound it makes
ISoundBehaviour newsound = new RoarSound();
c.setSoundBehaviour(newsound);
// Delegation
c.makeSound(); // Output: Roar!
}
}
composition
strategy pattern
SOLID
• Single Responsibility Principle (SRP): There should never be more than one reason for a class
to change.
• Open Closed Principle (OCP): Software entities like classes, modules and functions should be
open for extension but closed for modifications.
• Liskov Substitution Principle (LSP): Inheritance should ensure that any property proved about
supertype objects also holds for subtype objects.
• Interface Segregation Principle (ISP): Clients should not be forced to depend upon interfaces
that they don't use.
• Dependency Inversion Principle (DIP): High-level modules should not depend on low-level
modules. Both should depend on abstractions. Abstractions should not depend on details.
Details should depend on abstractions.
http://www.slideshare.net/deonpmeyer/object-oriented-concepts-and-principles
http://www.slideshare.net/deonpmeyer/object-oriented-concepts-and-principles
http://www.slideshare.net/deonpmeyer/object-oriented-concepts-and-principles
http://www.slideshare.net/deonpmeyer/object-oriented-concepts-and-principles
http://www.slideshare.net/deonpmeyer/object-oriented-concepts-and-principles
Program to an interface, not an implementation
Hollywood Principle
public class ObjA
{
private ObjB obj = new ObjB();
public void SomeAction()
{
obj.Work();
}
}
public class ObjB
{
public void Work()
{
Console.WriteLine("objB Work");
}
}
public class ObjA
{
private ObjC obj = new ObjC();
public void SomeAction()
{
obj.Action();
}
}
public class ObjC
{
public void Action()
{
Console.WriteLine("objC Work");
}
}
public class ObjA
{
private ObjB obj = new ObjB();
public void SomeAction()
{
obj.Work();
}
}
public class ObjB
{
public void Work()
{
Console.WriteLine("objB Work");
}
}
public class ObjA
{
private ObjC obj = new ObjC();
public void SomeAction()
{
obj.Action();
}
}
public class ObjC
{
public void Action()
{
Console.WriteLine("objC Work");
}
}
public interface IObj
{
void DoWork();
}
public class ObjA
{
private IObj obj = new ObjB();
public void SomeAction()
{
obj.DoWork();
}
}
public class ObjB : IObj
{
public void DoWork()
{
Console.WriteLine("objB Work");
}
}
public class ObjC : IObj
{
public void DoWork()
{
Console.WriteLine("objC Work");
}
}
public class ObjA
{
private IObj obj;
public void ObjA(IObj obj)
{
this.obj = obj;
}
public void SomeAction()
{
obj.DoWork();
}
}
public class ObjA
{
private IObj obj;
public IObj Obj
{
get
{
return this.obj;
}
set
{
this.obj = value;
}
}
public void SomeAction()
{
if (this.obj == null)
{
throw new ArgumentNullException("obj", "obj is null");
}
obj.DoWork();
}
}
public class ObjA
{
public void SomeAction(IObj obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj", "obj is null");
}
obj.DoWork();
}
}
Inversion of Control (IoC)
(via Dependency Injection )
constructor injection
method injection
property injection
Law of Demeter (LoD)
• aka. Principle of Least Knowledge ( )
• Only talk to your immediate friends.
• Don't talk to strangers.
•
•
public class LawOfDemeterInJava
{
private Topping cheeseTopping;
/**
* Good examples of following the Law of Demeter.
*/
public void goodExamples(Pizza pizza)
{
Foo foo = new Foo();
// (1) it's okay to call our own methods
doSomething();
// (2) it's okay to call methods on objects passed in to our method
int price = pizza.getPrice();
// (3) it's okay to call methods on any objects we create
cheeseTopping = new CheeseTopping();
float weight = cheeseTopping.getWeightUsed();
// (4) any directly held component objects
foo.doBar();
}
private void doSomething()
{
// do something here ...
}
}
http://alvinalexander.com/java/java-law-of-demeter-java-examples
Facade Mediator
Design Patterns
• Favor Composition over inheritance
• Program to an interface, not an implementation
• High Cohesion & Low/Loose coupling
1. Passes all tests
2. Expresses Intent (Self-document)
1. idea per method / class
2. Names of variables / methods / classes reveal intent
3. Methods & classes are understandable from their public
interface
3. No Duplicates (DRY)
4. Has no superfluous parts
1. Minimal methods / classes / modules
2. Only add what you need right now (YAGNI)
Xp Simplicity Rules - Kent Beck
Always implement things when you actually need
them, never when you just foresee that you need
them.
YAGNI (YouArentGonnaNeedIt)
“ The first time you do something, you just do it.
The second time you do something similar, you wince at
the duplication, but you do the duplicate thing anyway.
The third time you do something similar, you refactor.”
The Rule of Three - Don Roberts
3 Is A Magic Number
♪ Sign, sign, everywhere a sign
Blockin' out the scenery, breakin' my mind
Do this, don't do that, can't you read the sign ♪
Five Man Electrical Band - Signs
Sometimes data is just data and functions are
just functions.
Rob Pike
• Understanding Object Oriented Programming
•
• Rob Pike's comment
References
• Object-Oriented Software Engineering: A Use Case Driven Approach
• Refactoring: Improving the Design of Existing Code
• Object Oriented Concepts and Principles
• Go
•
• Kent Beck
•

Contenu connexe

Tendances

Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
The 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryThe 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryguestebd714
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence APIIlio Catallo
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVPHarshith Keni
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementAnil Bapat
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Esoteric LINQ and Structural Madness
Esoteric LINQ and Structural MadnessEsoteric LINQ and Structural Madness
Esoteric LINQ and Structural MadnessChris Eargle
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS ImplimentationUsman Mehmood
 
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of TonguesChoose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of TonguesCHOOSE
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template PatternJonathan Simon
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 

Tendances (20)

Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Classes and Inheritance
Classes and InheritanceClasses and Inheritance
Classes and Inheritance
 
The 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryThe 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summary
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVP
 
Java Generics
Java GenericsJava Generics
Java Generics
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Esoteric LINQ and Structural Madness
Esoteric LINQ and Structural MadnessEsoteric LINQ and Structural Madness
Esoteric LINQ and Structural Madness
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of TonguesChoose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 

En vedette

豆瓣数据架构实践
豆瓣数据架构实践豆瓣数据架构实践
豆瓣数据架构实践Xupeng Yun
 
美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现
美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现
美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现美团点评技术团队
 
Code style 2014-07-18-pub
Code style 2014-07-18-pubCode style 2014-07-18-pub
Code style 2014-07-18-pubpersia cai
 
Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Anil Madhavapeddy
 
Camomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlCamomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlYamagata Yoriyuki
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Anil Madhavapeddy
 
美团技术沙龙04 - 高性能服务器架构设计和调优
美团技术沙龙04 - 高性能服务器架构设计和调优美团技术沙龙04 - 高性能服务器架构设计和调优
美团技术沙龙04 - 高性能服务器架构设计和调优美团点评技术团队
 
中等创业公司后端技术选型
中等创业公司后端技术选型中等创业公司后端技术选型
中等创业公司后端技术选型wang hongjiang
 
PubCrawl Mobile Application
PubCrawl Mobile ApplicationPubCrawl Mobile Application
PubCrawl Mobile ApplicationDaniel Heinlein
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellMichel Rijnders
 
Qlync RD 第三屆讀書會候選清單
Qlync RD 第三屆讀書會候選清單Qlync RD 第三屆讀書會候選清單
Qlync RD 第三屆讀書會候選清單Li-Wei Yao
 
Design Pattern Explained CH1
Design Pattern Explained CH1Design Pattern Explained CH1
Design Pattern Explained CH1Jamie (Taka) Wang
 
被遺忘的資訊洩漏 / Information Leakage in Taiwan
被遺忘的資訊洩漏 / Information Leakage in Taiwan被遺忘的資訊洩漏 / Information Leakage in Taiwan
被遺忘的資訊洩漏 / Information Leakage in TaiwanShaolin Hsu
 

En vedette (20)

豆瓣数据架构实践
豆瓣数据架构实践豆瓣数据架构实践
豆瓣数据架构实践
 
美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现
美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现
美团点评技术沙龙09 - 一个用户行为分析产品的设计与实现
 
Code style 2014-07-18-pub
Code style 2014-07-18-pubCode style 2014-07-18-pub
Code style 2014-07-18-pub
 
Ocaml
OcamlOcaml
Ocaml
 
Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Camomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlCamomile : A Unicode library for OCaml
Camomile : A Unicode library for OCaml
 
Haskell - Functional Programming
Haskell - Functional ProgrammingHaskell - Functional Programming
Haskell - Functional Programming
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)
 
美团技术沙龙04 - 高性能服务器架构设计和调优
美团技术沙龙04 - 高性能服务器架构设计和调优美团技术沙龙04 - 高性能服务器架构设计和调优
美团技术沙龙04 - 高性能服务器架构设计和调优
 
中等创业公司后端技术选型
中等创业公司后端技术选型中等创业公司后端技术选型
中等创业公司后端技术选型
 
PubCrawl Mobile Application
PubCrawl Mobile ApplicationPubCrawl Mobile Application
PubCrawl Mobile Application
 
MTA database brochure
MTA database brochureMTA database brochure
MTA database brochure
 
追思投影片
追思投影片追思投影片
追思投影片
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 
Qlync RD 第三屆讀書會候選清單
Qlync RD 第三屆讀書會候選清單Qlync RD 第三屆讀書會候選清單
Qlync RD 第三屆讀書會候選清單
 
計算数学
計算数学計算数学
計算数学
 
Design Pattern Explained CH1
Design Pattern Explained CH1Design Pattern Explained CH1
Design Pattern Explained CH1
 
被遺忘的資訊洩漏 / Information Leakage in Taiwan
被遺忘的資訊洩漏 / Information Leakage in Taiwan被遺忘的資訊洩漏 / Information Leakage in Taiwan
被遺忘的資訊洩漏 / Information Leakage in Taiwan
 

Similaire à Object-oriented Basics

Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.pptMikeAdva
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsMohammad Shaker
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already KnowKevlin Henney
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30myrajendra
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programmingDavid Giard
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)PROIDEA
 

Similaire à Object-oriented Basics (20)

L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Java
JavaJava
Java
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Oops concept
Oops conceptOops concept
Oops concept
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
core java
core javacore java
core java
 

Plus de Jamie (Taka) Wang

Plus de Jamie (Taka) Wang (20)

20200606_insight_Ignition
20200606_insight_Ignition20200606_insight_Ignition
20200606_insight_Ignition
 
20200727_Insight workstation
20200727_Insight workstation20200727_Insight workstation
20200727_Insight workstation
 
20200723_insight_release_plan
20200723_insight_release_plan20200723_insight_release_plan
20200723_insight_release_plan
 
20210105_量產技轉
20210105_量產技轉20210105_量產技轉
20210105_量產技轉
 
20200808自營電商平台策略討論
20200808自營電商平台策略討論20200808自營電商平台策略討論
20200808自營電商平台策略討論
 
20200427_hardware
20200427_hardware20200427_hardware
20200427_hardware
 
20200429_ec
20200429_ec20200429_ec
20200429_ec
 
20200607_insight_sync
20200607_insight_sync20200607_insight_sync
20200607_insight_sync
 
20220113_product_day
20220113_product_day20220113_product_day
20220113_product_day
 
20200429_software
20200429_software20200429_software
20200429_software
 
20200602_insight_business
20200602_insight_business20200602_insight_business
20200602_insight_business
 
20200408_gen11_sequence_diagram
20200408_gen11_sequence_diagram20200408_gen11_sequence_diagram
20200408_gen11_sequence_diagram
 
20190827_activity_diagram
20190827_activity_diagram20190827_activity_diagram
20190827_activity_diagram
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
20161220 - microservice
20161220 - microservice20161220 - microservice
20161220 - microservice
 
20160217 - Overview of Vortex Intelligent Data Sharing Platform
20160217 - Overview of Vortex Intelligent Data Sharing Platform20160217 - Overview of Vortex Intelligent Data Sharing Platform
20160217 - Overview of Vortex Intelligent Data Sharing Platform
 
20151111 - IoT Sync Up
20151111 - IoT Sync Up20151111 - IoT Sync Up
20151111 - IoT Sync Up
 
20151207 - iot strategy
20151207 - iot strategy20151207 - iot strategy
20151207 - iot strategy
 
20141210 - Microservice Container
20141210 - Microservice Container20141210 - Microservice Container
20141210 - Microservice Container
 
20161027 - edge part2
20161027 - edge part220161027 - edge part2
20161027 - edge part2
 

Dernier

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 

Dernier (20)

FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 

Object-oriented Basics

  • 2. Programming Paradims • Procedural/Structured Programming • COBOL, FORTRAN, BASIC, PASCAL, C… • Object-Oriented Programming • Smalltalk, C++, C#, Java… • Functional Programming • F#, Scala, OCaml, Erlang…
  • 3. Class and Object • class object • Class (Instance) • Object (Class) (Object) Behavior State
  • 5. Constructor class CoOrds { public int x, y; // Default constructor: public CoOrds() { x = 0; y = 0; } // A constructor with two arguments: public CoOrds(int x, int y) { this.x = x; this.y = y; } // Override the ToString method: public override string ToString() { return (String.Format("({0},{1})", x, y)); } } class MainClass { static void Main() { CoOrds p1 = new CoOrds(); CoOrds p2 = new CoOrds(5, 3); // Display the results using the // overriden ToString method: Console.WriteLine("CoOrds #1 at {0}", p1); Console.WriteLine("CoOrds #2 at {0}", p2); Console.ReadKey(); } } /* Output: CoOrds #1 at (0,0) CoOrds #2 at (5,3) */ Instantiation constructors
  • 8. “Because inheritance exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks encapsulation” Gang of Four, Design Patterns (Chapter 1)
  • 9. “Favor Composition over inheritance” Gang of Four, Design Patterns
  • 10. “Use of classical inheritance is always optional; every problem that it solves can be solved another way.” Sandi Metz
  • 11. Inheritance Hell This is why you need Composition over Inheritance
  • 12. Diamond Problem in C++ int main(void) { D d(10); d.set(20); cout << d.get() << endl; return 0; } class A{ public: A (int x) : m_x(x) {} int m_x; }; class B : public A { public: B (int x) : A(x) {} void set(int x) { this -> m_x = x; } }; class C : public A { public: C (int x) : A(x) {} int get(void) { return this -> m_x; } }; class D : public B,public C { public: D (int x) : B(x),C(x) {} };
  • 13. Diamond Problem in C++ int main(void) { D d(10); d.set(20); cout << d.get() << endl; return 0; } class A{ public: A (int x) : m_x(x) {} int m_x; }; class B : public A { public: B (int x) : A(x) {} void set(int x) { this -> m_x = x; } }; class C : public A { public: C (int x) : A(x) {} int get(void) { return this -> m_x; } }; class D : public B,public C { public: D (int x) : B(x),C(x) {} }; D B A C A
  • 15. HOME_SEARCH_BAR - textField + search() + init() PAGE_SEARCH_BAR - overlay + prompt() ( )
  • 16. HOME_SEARCH_BAR - textField + search() + init() PAGE_SEARCH_BAR - overlay + prompt() LOCAL_SEARCH_BAR + search() ( )
  • 17. HOME_SEARCH_BAR - textField + search() + init() PAGE_SEARCH_BAR - overlay + prompt() LOCAL_SEARCH_BAR + search() HOME_SEARCH_BAR - textField + search() + init() + initWithStyle() ( )
  • 19. Encapsulation • • / • Encapsulation • public • protected • internal (Assembly) • private C# - Encapsulation
  • 20. C# Example class Rectangle { //member variables private double length; private double width; public void Acceptdetails() { Console.WriteLine("Enter Length: "); length = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter Width: "); width = Convert.ToDouble(Console.ReadLine()); } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } }
  • 21. Override and Overload • Overload ( ) • (class) (Parameter) (Method) • Override ( ) • extends( ) method • Overriding argument, parameter, method name, return type (function signature) Java - Overloading ( ) Overriding ( )
  • 22. C# Example class A { public virtual void Y() { // Used when C is referenced through A. Console.WriteLine("A.Y"); } } class B : A { public override void Y() { // Used when B is referenced through A. Console.WriteLine("B.Y"); } } class Program { public static void Main() { ShowString(); ShowString("Category"); } static void ShowString() { ShowString("Popular"); } static void ShowString(string value) { Console.WriteLine(value); } } override overload
  • 23. Polymorphism • Polymorphism means that the sender of a stimulus does not need to know the receiving instance’s class. The receiving instance can belonging to an arbitrary class. • If an instance sends a stimulus to another instance, but does not have to be aware of which class the receiving instance belongs to, we say that we have polymorphism. Object-Oriented Software Engineering: A Use Case Driven Approach
  • 24. Polymorphism public class Shape { public int X { get; private set; } public int Y { get; private set; } public int Height { get; set; } public int Width { get; set; } // Virtual method public virtual void Draw() { Console.WriteLine("Performing base class drawing tasks"); } } class Circle : Shape { public override void Draw() { // Code to draw a circle... Console.WriteLine("Drawing a circle"); base.Draw(); } } class Rectangle : Shape { public override void Draw() { // Code to draw a rectangle... Console.WriteLine("Drawing a rectangle"); base.Draw(); } } static void Main(string[] args) { System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>(); shapes.Add(new Rectangle()); shapes.Add(new Circle()); foreach (Shape s in shapes) { s.Draw(); } Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
  • 25. package main import "fmt" type Human interface { myStereotype() string } type Man struct { } func (m Man) myStereotype() string { return "I'm going fishing." } type Woman struct { } func (m Woman) myStereotype() string { return "I'm going shopping." } func main() { m := new (Man) w := new (Woman) //an array of Humans - we don't know whether Man or Woman hArr := [...]Human{m, w} //array of 2 Humans. One is the type Man, one is the type Woman. for n, _ := range (hArr) { //appears as human type, but behavior changes depending on actual instance fmt.Println("I'm a human, and my stereotype is: ", hArr[n].myStereotype()) } }
  • 26. “ When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.” Indiana poet James Whitcomb Riley
  • 27. Duck typing • can work the same as polymorphism, but without inheritance • Polymorphism (in the context of object-oriented programming) means a subclass can override a method of the base class. This means a method of a class can do different things in subclasses. For example: a class Animal can have a method talk() and the subclasses Dog and Cat of Animal can let the method talk() make different sounds. • Duck typing means code will simply accept any object that has a particular method. Let's say we have the following code: animal.quack(). If the given object animal has the method we want to call then we're good (no additional type requirements needed). It does not matter whether animal is actually a Duck or a different animal which also happens to quack. That's why it is called duck typing: if it looks like a duck (e.g., it has a method called quack() then we can act as if that object is a duck). What is the difference between polymorphism and duck typing?
  • 28. • Interface: • An Interface is a special type of class that only provides a specification (not an implementation) for its abstract members. • Abstract classes: • The main purpose of an abstract class is to define a common interface for its subclasses.
  • 29. Interface • An interface defines the signature operations of an entity, it also sets the communication boundary between two entities, in this case two pieces of software. It generally refers to an abstraction that an asset provides of itself to the outside. • The main idea of an interface is to separate functions from implementations. http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/interface.html
  • 31. public interface ISoundBehaviour { public void makeSound(); } public class MeowSound implements ISoundBehaviour { public void makeSound() { System.out.println("Meow"); } } public class RoarSound implements ISoundBehaviour { public void makeSound() { System.out.println("Roar!"); } } public class Cat { private ISoundBehaviour sound = new MeowSound(); public void makeSound() { this.sound.makeSound(); } public void setSoundBehaviour(ISoundBehaviour newsound) { this.sound = newsound; } } public class Main { public static void main(String args[]) { Cat c = new Cat(); // Delegation c.makeSound(); // Output: Meow // now to change the sound it makes ISoundBehaviour newsound = new RoarSound(); c.setSoundBehaviour(newsound); // Delegation c.makeSound(); // Output: Roar! } } composition strategy pattern
  • 32. SOLID • Single Responsibility Principle (SRP): There should never be more than one reason for a class to change. • Open Closed Principle (OCP): Software entities like classes, modules and functions should be open for extension but closed for modifications. • Liskov Substitution Principle (LSP): Inheritance should ensure that any property proved about supertype objects also holds for subtype objects. • Interface Segregation Principle (ISP): Clients should not be forced to depend upon interfaces that they don't use. • Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
  • 38. Program to an interface, not an implementation
  • 40. public class ObjA { private ObjB obj = new ObjB(); public void SomeAction() { obj.Work(); } } public class ObjB { public void Work() { Console.WriteLine("objB Work"); } } public class ObjA { private ObjC obj = new ObjC(); public void SomeAction() { obj.Action(); } } public class ObjC { public void Action() { Console.WriteLine("objC Work"); } }
  • 41. public class ObjA { private ObjB obj = new ObjB(); public void SomeAction() { obj.Work(); } } public class ObjB { public void Work() { Console.WriteLine("objB Work"); } } public class ObjA { private ObjC obj = new ObjC(); public void SomeAction() { obj.Action(); } } public class ObjC { public void Action() { Console.WriteLine("objC Work"); } } public interface IObj { void DoWork(); } public class ObjA { private IObj obj = new ObjB(); public void SomeAction() { obj.DoWork(); } } public class ObjB : IObj { public void DoWork() { Console.WriteLine("objB Work"); } } public class ObjC : IObj { public void DoWork() { Console.WriteLine("objC Work"); } }
  • 42. public class ObjA { private IObj obj; public void ObjA(IObj obj) { this.obj = obj; } public void SomeAction() { obj.DoWork(); } } public class ObjA { private IObj obj; public IObj Obj { get { return this.obj; } set { this.obj = value; } } public void SomeAction() { if (this.obj == null) { throw new ArgumentNullException("obj", "obj is null"); } obj.DoWork(); } } public class ObjA { public void SomeAction(IObj obj) { if (obj == null) { throw new ArgumentNullException("obj", "obj is null"); } obj.DoWork(); } } Inversion of Control (IoC) (via Dependency Injection ) constructor injection method injection property injection
  • 43. Law of Demeter (LoD) • aka. Principle of Least Knowledge ( ) • Only talk to your immediate friends. • Don't talk to strangers. • •
  • 44. public class LawOfDemeterInJava { private Topping cheeseTopping; /** * Good examples of following the Law of Demeter. */ public void goodExamples(Pizza pizza) { Foo foo = new Foo(); // (1) it's okay to call our own methods doSomething(); // (2) it's okay to call methods on objects passed in to our method int price = pizza.getPrice(); // (3) it's okay to call methods on any objects we create cheeseTopping = new CheeseTopping(); float weight = cheeseTopping.getWeightUsed(); // (4) any directly held component objects foo.doBar(); } private void doSomething() { // do something here ... } } http://alvinalexander.com/java/java-law-of-demeter-java-examples Facade Mediator
  • 45. Design Patterns • Favor Composition over inheritance • Program to an interface, not an implementation • High Cohesion & Low/Loose coupling
  • 46. 1. Passes all tests 2. Expresses Intent (Self-document) 1. idea per method / class 2. Names of variables / methods / classes reveal intent 3. Methods & classes are understandable from their public interface 3. No Duplicates (DRY) 4. Has no superfluous parts 1. Minimal methods / classes / modules 2. Only add what you need right now (YAGNI) Xp Simplicity Rules - Kent Beck
  • 47. Always implement things when you actually need them, never when you just foresee that you need them. YAGNI (YouArentGonnaNeedIt)
  • 48. “ The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.” The Rule of Three - Don Roberts 3 Is A Magic Number
  • 49. ♪ Sign, sign, everywhere a sign Blockin' out the scenery, breakin' my mind Do this, don't do that, can't you read the sign ♪ Five Man Electrical Band - Signs
  • 50. Sometimes data is just data and functions are just functions. Rob Pike • Understanding Object Oriented Programming • • Rob Pike's comment
  • 51. References • Object-Oriented Software Engineering: A Use Case Driven Approach • Refactoring: Improving the Design of Existing Code • Object Oriented Concepts and Principles • Go • • Kent Beck •