Java 如何为高度耦合的方法添加新参数?
我有一个Java类,其方法在我的应用程序API中高度耦合,如下所示:Java 如何为高度耦合的方法添加新参数?,java,refactoring,Java,Refactoring,我有一个Java类,其方法在我的应用程序API中高度耦合,如下所示: public class ProductModel { public static Product createProduct(ProductType productType, String comment) { return createProduct(productType, comment, null); } public static Product createProduct
public class ProductModel {
public static Product createProduct(ProductType productType, String comment) {
return createProduct(productType, comment, null);
}
public static Product createProduct(ProductType productType, String comment, Long sessionTrackingId) {
// Here now need sessionTrackingId Long
// But this method is never called
....
}
}
第一种方法在许多类中以及在我的API项目(业务)和我的应用程序项目(前端)中都被调用。第二个方法只是在同一个类ProductModel中调用的,但是现在我需要通过传递从应用程序项目(前端)获得的sessionTrackingId来进行重构以使用第二个方法
API是另一个类似于Java library.jar的项目,我需要将此参数传递给第二个方法
我该怎么做?也许在第一个方法的每次调用中都会向接口添加一个新的抽象类?我只需将第一个方法内联到它被调用的任何地方。现在,调用方都在调用第二个方法,第三个参数为null。查找被调用的所有地方,并用调用上下文中适当的内容替换null。我只需将第一个方法内联到它被调用的所有地方。现在,调用方都在调用第二个方法,第三个参数为null。查找所有被调用的地方,并用调用上下文中合适的内容替换null。此类内容属于facade领域。这是很好的实践。关键是在方法签名之间保留尽可能多的共同代码。 您对问题的描述有点难以解释,不清楚您是否真的在尝试添加标题中建议的第三个参数
我大体上同意卡尔的观点。您可以在默认不适用的参数时添加方法签名。请注意,“内联”在Java中不是开发人员的责任,而是JVM的责任。这种事情属于外观领域。这是很好的实践。关键是在方法签名之间保留尽可能多的共同代码。 您对问题的描述有点难以解释,不清楚您是否真的在尝试添加标题中建议的第三个参数
我大体上同意卡尔的观点。您可以在默认不适用的参数时添加方法签名。请注意,“内联”在Java中不是开发人员的责任,而是JVM的责任。由于此方法是高度耦合的,我使用singleton模式解决了此问题,并在会话启动时设置此值,然后在方法调用中使用它:
public class ProductModel {
public static Product createProduct(ProductType productType, String comment) {
return createProduct(productType, comment, Application.getSessionTrackingId());
}
public static Product createProduct(ProductType productType, String comment, Long sessionTrackingId) {
// Here now need sessionTrackingId Long
// But this method is never called
....
}
}
由于此方法是高度耦合的,因此我使用singleton模式解决了此问题,并在会话启动时设置此值,然后在方法调用中使用它:
public class ProductModel {
public static Product createProduct(ProductType productType, String comment) {
return createProduct(productType, comment, Application.getSessionTrackingId());
}
public static Product createProduct(ProductType productType, String comment, Long sessionTrackingId) {
// Here now need sessionTrackingId Long
// But this method is never called
....
}
}