我有以下代码,帮助我解释我在解耦概念上遇到的问题。
例如:
async getSomething(id: number): Promise<boolean> {
if(id === "111") {
return true;
}
else {
return false;
}
}
someFunc(): void {
let id="123";
if (getSomething(id)) {
console.log("do somthing special");
}
else {
console.log("sleep");
}
}从这个answer on other decoupling question
我们使用接口来解耦两个方法,但我很难想象这两个方法之间的交互是相互独立的。
例如:
export namespace Special {
export interface MagicDay {
isMagic: boolean;
}
}
...
async getSomething(id: number): Promise<Special.MagicDay> {
if(id === "111") {
// here what I think is different from before
// we create an object which we store our boolean
// so in some future we can the way we implement this function
// it is ok because we still have the **isMagic** that **someFunc** needs
return {isMagic: true};
}
else {
return {isMagic: false};
}
}
someFunc(): void {
let id="123";
let someDay = getSomething(id);
// different is now
// we receive an object
// so what happens in the backend we don't need to worry about it
// as long as we have the **isMagic** returns here
// but what makes this decoupling which we still need the value from
// get something
if (someDay.isMagic) {
console.log("do somthing special");
}
else {
console.log("sleep");
}
}我在上面的代码中对我认为最麻烦的地方做了评论。
我读过这个article about why we should use decoupling,我确实理解为什么,但是当涉及到实现时,我被这个想法困扰着,因为我一直在想,解耦是如何使一个独立于其他独立的,但我们仍然需要输入才能使其工作?
提前谢谢。
发布于 2018-06-05 00:07:52
this answer中的要点不一定适用于TypeScript,因为TS使用structural typing。database: Database不一定非得是Database的实例才能符合Database类型。它们还不是紧密耦合的。只要Database和IDatabase类型相同,就不需要IDatabase。
MagicDay接口不会将这段代码解耦。boolean类型刚刚被{ isMagic: boolean }类型替换。如果一个方法和另一个方法属于同一个类,那么将它们从另一个方法中分离出来是没有意义的。解耦不相关的功能是可能的:
type TGetSomething = (id: number) => Promise<boolean>;
const getSomething: TGetSomething = async (id: number) => {
if(id === "111") {
return true;
}
else {
return false;
}
}
function async someFunc(callback: TGetSomething): Promise<void> {
let id="123";
if (await callback(id)) {
console.log("do somthing special");
}
else {
console.log("sleep");
}
}
someFunc(getSomething);如果这些函数实际上是方法,那么应该在类级别执行解耦。在前面提到的资源中,解耦主要指的是OOP原则。
https://stackoverflow.com/questions/50681947
复制相似问题