gpt4 book ai didi

java - 我可以让process每个bean成员的代码更漂亮吗?

转载 作者:行者123 更新时间:2023-12-01 09:06:02 25 4
gpt4 key购买 nike

我有一个类:Data,一个类:Alarm。 我必须统计数据然后使用npoi输出excel。Alarm可能为空。现在是我的代码:

 while (it.hasNext()){       
Data t = it.next();
row = sheet.createRow(index++);
Alarm a=alarms.get(t.getDeviceid().trim());
cell = row.createCell(0);
if(a==null||inRange(t.getNoise(),a.getNoiselow(),a.getNoiseup()))
cell.setCellStyle(styleNormal);
else
cell.setCellStyle(styleError);
cell.setCellValue((double)t.getNoise());
cell = row.createCell(1);
if(a==null||inRange(t.getPm(),a.getPmlow(),a.getPmup()))
cell.setCellStyle(styleNormal);
else
cell.setCellStyle(styleError);
cell.setCellValue((double)t.getPm());
cell = row.createCell(2);
if(a==null||inRange(t.getPressure(),a.getPressurelow(),a.getPressureup()))
cell.setCellStyle(styleNormal);
else
cell.setCellStyle(styleError);
cell.setCellValue((double)t.getPressure());
....

我重复每个 bean 属性......我可以改进这样的代码吗?

最佳答案

最简单的开始方法:查找重复代码并将其放入方法中。

  cell = row.createCell(0);
if(a==null||inRange(t.getNoise(),a.getNoiselow(),a.getNoiseup()))
cell.setCellStyle(styleNormal);
else
cell.setCellStyle(styleError);
cell.setCellValue((double)t.getNoise());

您可以将以上代码放入方法中,并在 while 循环中调用:

 private void setCell(Row row, Data data, int cellIndex)
{
cell = row.createCell(cellIndex);
Alarm a=alarms.get(data.getDeviceid().trim());
if(a==null||inRange(data, a, cellIndex))
cell.setCellStyle(styleNormal);
else
cell.setCellStyle(styleError);

// You can also do as below if you can read it easily!!
// cell.setCellStyle(a==null||inRange(data, a, cellIndex)?styleNormal:styleError);

// This switch-case should also be moved to separate method.
// Leaving that to you.
switch(cellIndex)
{
case 0: cell.setCellValue((double)data.getNoise()); break;
case 1: cell.setCellValue((double)t.getPm()); break;
...
...
default: /*set default value and break or throw InvalidCellIndex exception*/
}
}

private boolean inRange(Date data, Alarm a, int cellIndex)
{
switch(cellIndex)
{
case 0: return inRange(data.getNoise(),a.getNoiselow(),a.getNoiseup();
case 1: return inRange(data.getPm(),a.getPmlow(),a.getPmup();
...
...
default: /* throw InvalidCellIndex exception*/
}
}

关于java - 我可以让process每个bean成员的代码更漂亮吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278607/

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