gpt4 book ai didi

java - 重载构造函数的设计是否正确?

转载 作者:行者123 更新时间:2023-12-01 17:26:12 24 4
gpt4 key购买 nike

假设我有课

public class MyMainClass {
SomeGlobalStateObject someGlobalStateObjectInstance;

public MyMainClass(SomrDep1 someDep1, SomeDep2 someDep2){
this(someDep1); // call the other constructor so that I can initialize, the base layer is the same
someGlobalStateObjectInstance.setGlobalVariable("someVar", someDep2); // I have overriden setGlobalVariable for "someVar", seems like a smell.
}

public MyMainClass(SomeDep1 someDep1){
someGlobalStateObjectInstance = new someGlobalStateObjectInstance();
someGlobalStateObjectInstance.setGlobalVariable("someVar", null); // The null in the second param is a key part of my problem. Assume this must be done, I cant remove this line for this constructor.
// do lots of other things with someGlobalStateObjectInstance.
}

}

以上是该类当前的设计。您可以假设我必须在构造函数中创建someGlobalStateObjectInstance,并且它不能作为依赖项本身传递。

这是我现在的主要问题。如您所见,我首先在第二个构造函数中调用 someGlobalStateObjectInstance.setGlobalVariable("someVar", null); ,然后在第一个构造函数中再次使用 someGlobalStateObjectInstance.setGlobalVariable("someVar"重写, someDep2);.

这是代码异味吗?它不必要地设置一个变量,然后在第一个构造函数中重写。我想知道如何最好地解决这个问题以避免所有代码异味。

最佳答案

那就换个方式吧

public MyMainClass(SomrDep1 someDep1, SomeDep2 someDep2){
//this(someDep1);
someGlobalStateObjectInstance = new someGlobalStateObjectInstance();
someGlobalStateObjectInstance.setGlobalVariable("someVar", someDep2);
}

public MyMainClass(SomeDep1 someDep1){
this(someDep1, null);
}

关于java - 重载构造函数的设计是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61206848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com