【问题标题】:Should I pass private state with params to functions or should functions use the private state?我应该将带有参数的私有状态传递给函数还是函数应该使用私有状态?
【发布时间】:2019-11-29 21:49:09
【问题描述】:

我有一个具有以下场景的 Angular 应用程序,尽管我相信这个场景也适用于其他框架/场景:

public export class FooComponent {
    private userId: number;

    constructor(private readonly authService: AuthService) { }

    ngOnInit() {
        this.userId = authService.GetUser().id;

        this.getDataByUserId(this.userId);    
    }

    private getDataByUserId(userId: number) { 
        // Load data using the param
    }

    public anotherFunction(fooId: number) {
       // Gets called by an event occurring or something
       // Perform an API Call

       // Now reload the data by using the private state variable.
       this.getDataByUserId(this.userId);
    }
}

getDataByUserId(userId: number)应该使用参数来接收userId,还是应该无参数只访问组件的private userId

在我看来,将变量作为参数传递的优缺点如下:

专业人士
- 更容易的单元测试;如果组件有点大,你可能不需要以特定的方式设置组件来工作,你只需要传递一个数字 - 如果您的组件的许多功能访问该变量并对其进行更改,您可能会遇到该变量处于无效状态的情况。

骗局
- 如果您不再以特定方式设置组件,因为您可以将值作为参数传递,则测试期间组件的“状态”可能无法反映生产场景期间的预期状态。由于您的测试不能反映真实的工作条件,因此它们可能被认为是易碎的。 - 如果你传递了错误的值,事情将会/可能会出错。

这里什么被认为是更好的选择?在哪里划清界限?

谢谢!

【问题讨论】:

    标签: angular architecture


    【解决方案1】:

    我认为这取决于getUserDataById 函数的真正用途。

    是否总是使用存储在组件状态中的userId 调用它(所以它是某种currentUserId)?那么最好创建一个不带参数的getCurrentUserData 方法,该方法总是从状态中获取用户ID 并对其进行测试。

    如果您在组件或应用程序的不同部分使用不同的用户 ID 源重用它,那么将其设为单独的函数并在不依赖组件状态的情况下对其进行测试似乎是合乎逻辑的。然后,当您测试 anotherFunction 时,您应该在需要时模拟 getUserDataById

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 2019-11-13
      • 2012-03-14
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      相关资源
      最近更新 更多