作者dreamnook (亚龙)
看板Soft_Job
标题Re: [请益] 我这样解释OOP对吗?
时间Tue Nov 14 10:42:33 2017
当要教纯新人时
我大概会这样瞎扯
1. 封装 (encapsulation)
func step1(step1_params:step1_params_type) { /* do step1 */ }
func step2(step2_params:step2_params_type) { /* do step2 */ }
...
func give_me_f_result() -> result_type {
/* kind of encapsulation */
step1(params1)
step2(params2)
...
return result
}
啥? 你说这样不就只是个function call?
是,但你把他"包装"起来後
class IDontGiveADamn {
private step1(...) { ... }
...
public give_me_f_result() -> result_type { ... }
}
使用这个 IDontGiveADamn 的人就不用看到 step1 ~ stepN 的东西了
2. 继承 (inheritance)=> 原意其实为「扩展 (extend)」较恰当
纯这样解释应该就蛮够了,我猜原本的用意状况是这样
class CalculateStudentScore {
private func stuff_you_dont_care(...) { ... }
...
public func result() -> float { ... }
}
只要呼叫CalculateStudentScore.result()就可以取得成绩了
啊干,结果教务处跟你讲说评分太低,必须用square root*10
你改了
结果隔了1个月跟你讲说全部的人都sqrt*10太高了,要你再改另一个运算
你又改了
结果软体上路1周後教务处再跟你要上述三种不同的成绩
并且不能异动到当前版本
於是只好这样改
class UAsHoes private_extends CalculateStudentScore {
public func here_is_you_f_result() { ... }
}
这样你不用改动原本的code,还是可以提供给人渣,啊不,他人使用
3. 介面 (interface)/多型 (polymorphism)
印象中多型好像没有限定oop,我这边先用我的唬烂例子
class TellMeAboutSomeone {
private func steal_personal_data(person:Americano) { ... }
public func callme(person:Americano) { ... }
}
Ya, if you're an American, this class tell me your info (and steal it).
How about Chinese?
So you do this:
class TellMeAboutSomeone {
private func steal_personal_data(person:Americano) { ... }
public func callme(person:Americano) { ... }
private func steal_personal_data(person:Chinamen) { ... }
public func callme(person:Chinamen) { ... }
}
好,那我要法文呢?
Je crois que vous comprenez où le problème est (powered by Google Translate
为了把 TellMeAboutSomeone 简化,那就乾脆这麽做吧
class TellMeAboutSomeone {
private func steal_personal_data(person:IPerson) { ... }
private func callme(person: IPerson) { ... }
}
interface IPerson {
func secret_to_steal() -> Secret;
func spell_your_name() -> Name;
}
这样你就轻松啦,让想用你这个class的人去遵守规则并烦恼!
----
所以oop的好处到底在哪?
...我到现在的感觉还是个从"方便分类"出发的概念XD
当程式越写越大时,global function与variable命名会越痛苦
有点像是某个谣传说很久以前John是个菜市场名,喊声John一堆人会回头
所以就出现了姓氏来"方便分辨"
很多时候你也不需要知道这个人(物件)私底下到底在做什麽
你只是需要少数的资讯,更可能只是单一的结果(像是送信)
至於更专业的讲法,不要问我,我也讲了这是给新人的唬烂文
被唬住的人无论是放弃还是跟随码农这条不归路我都无所谓就是XD
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 211.20.17.50
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Soft_Job/M.1510627356.A.67A.html
1F:推 Vick753: 请问fun()->XX 是什麽意思阿 11/14 11:38
2F:→ dreamnook: 函式 某种语言的惯用法 用c来说是type funcName() 11/14 11:48