gpt4 book ai didi

java - 如何为方法的所有错误或空参数设置默认值?

转载 作者:搜寻专家 更新时间:2023-10-31 19:58:50 25 4
gpt4 key购买 nike

目前我有这段代码(我不喜欢它):

private RenderedImage getChartImage (GanttChartModel model, String title,
Integer width, Integer height,
String xAxisLabel, String yAxisLabel,
Boolean showLegend) {
if (title == null) {
title = "";
}
if (xAxisLabel == null) {
xAxisLabel = "";
}
if (yAxisLabel == null) {
yAxisLabel = "";
}
if (showLegend == null) {
showLegend = true;
}
if (width == null) {
width = DEFAULT_WIDTH;
}
if (height == null) {
height = DEFAULT_HEIGHT;
}
...
}

我该如何改进它?

我有一些关于引入一个对象的想法,该对象将包含所有这些参数作为字段,然后也许可以应用构建器模式。但仍然没有明确的愿景如何实现,我不确定是否值得这样做。还有其他想法吗?

最佳答案

一个方法有这么多参数绝对是一种代码味道。我会说一个 Chart 对象正在等待诞生。这是一个基本大纲:

 private RenderImage getChartImage(Chart chart) { 
//etc.
}
private static class Chart {
private GanttChartModel model;
private String title = "";
//etc, initializing each field with its default value.
private static class Builder {
private Chart chart;
public Builder(GanttChartModel model) {
chart = new Chart();
chart.model = model;
}
public setTitle(String title) {
if (title != null) {
chart.title = title;
}
}
}
}

其他选项包括在方法上使用基元而不是对象来指示不允许 null,尽管这不一定会使它变得更好。另一种选择是一堆重载方法,但考虑到这里的参数类型,这并没有真正起作用,因为我知道您想使任何参数成为可选参数,而不是让第一个参数是必需的,而随后的参数是可选的。

关于java - 如何为方法的所有错误或空参数设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2744806/

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