如何重构此方法以将其认知复杂性从 21 降低到允许的 15?


/** @param  e */
private void doActionForUldProfileRecordGrid(ListSelectionEvent e)
{
Object source = e.getSource();
if ((uldProfileTab.getRecordsGrid() != null) && (source == uldProfileTab.getRecordsGrid().getSelectionModel()))
{
try
{
if (uldProfileTab.getRecordsGrid() != null)
{
UldProfileRec data = (UldProfileRec) getDataVector().elementAt(uldProfileTab.getRecordsGrid()
.getActiveRow());
if ((data != null) && Str.isNotEmpty(data.contourGroup))
{
ContourGroup contourGroup = ContourGroupServiceCallUtil.getContourGroup(data.contourGroup);
if ((uldProfileTab.getRecordsGrid().getActiveRow()
== (uldProfileTab.getRecordsGrid().getRowCount() - 1)))
{
data = new UldProfileRec();
getDataVector().addElement(data);
}
if (contourGroup != null)
{
data.setBaseWeight(contourGroup.defaultWeight());
data.setBaseVolume(contourGroup.defaultVolume());
data.deck(contourGroup.getDeckDescription());
}
}
if (data != null)
{
setWeightVolume(data, data.position());
}
}
}
catch (VerifyException ve)
{
LOGGER.warn(ve.getLocalizedMessage(), ve);
}
} // end if
}

您应该重构代码并将孤立的逻辑分离到单独的较小方法中,这将在两个方面为您提供帮助:

  1. 它将使代码更加模块化和可维护。
  2. 较小的方法更容易测试,并减少将来引入错误的可能性。

而且,作为副产品,这些方法的认知复杂性也将降低。

例如:

从这种方法:

private void doActionForUldProfileRecordGrid(ListSelectionEvent e)
{
Object source = e.getSource();
if ((uldProfileTab.getRecordsGrid() != null) && (source == uldProfileTab.getRecordsGrid().getSelectionModel()))
{
try
{
if (uldProfileTab.getRecordsGrid() != null)
{
UldProfileRec data = (UldProfileRec) getDataVector().elementAt(uldProfileTab.getRecordsGrid()
.getActiveRow());
if ((data != null) && Str.isNotEmpty(data.contourGroup))
{
**ContourGroup contourGroup = ContourGroupServiceCallUtil.getContourGroup(data.contourGroup);
if ((uldProfileTab.getRecordsGrid().getActiveRow()
== (uldProfileTab.getRecordsGrid().getRowCount() - 1)))
{
data = new UldProfileRec();
getDataVector().addElement(data);
}
if (contourGroup != null)
{
data.setBaseWeight(contourGroup.defaultWeight());
data.setBaseVolume(contourGroup.defaultVolume());
data.deck(contourGroup.getDeckDescription());
}**
}
if (data != null)
{
setWeightVolume(data, data.position());
}
}
}
catch (VerifyException ve)
{
LOGGER.warn(ve.getLocalizedMessage(), ve);
}
} // end if

您可以重构突出显示的部分,也可以将其移动到单独的方法中。