SonarLint:代码气味:不应声明局部变量,然后立即返回或抛出

Posted

技术标签:

【中文标题】SonarLint:代码气味:不应声明局部变量,然后立即返回或抛出【英文标题】:SonarLint : Code Smell : Local variables should not be declared and then immediately returned or thrown 【发布时间】:2022-01-18 16:53:16 【问题描述】:

使用 SonarLint 分析我的代码后,我得到以下异味代码:“不应声明局部变量然后立即返回或抛出”。

即使这没有阻塞并且组件运行良好。

我认为有更好的方法可以在函数中发布 return,但我不知道如何,如果有人知道诀窍的话。

这是我的组件:

const ColumnModalEvent = (currency: any) => 
  const columnsEventModal: Column[] = [

  Header: () => <I18nWrapper translateKey="movement.type.fieldName" />,
  accessor: 'type',
  disableSortBy: true,
  Cell: ( value ) => (
    <I18nWrapper translateKey=value prefix="movement.type" />
  ),
,

  Header: () => (
    <I18nWrapper translateKey="movement.uniqueReference.fieldNameShort" />
  ),
  accessor: 'uniqueRef',
,

  Header: () => <I18nWrapper translateKey="movement.documentDate" />,
  accessor: 'createdDate',
  className: 'text-end',
  headerClassName: 'text-end',
  Cell: ( value ) => <DateFormater dateToFomat=value />,
,
];

 return columnsEventModal;
 ;

 export default ColumnModalEvent;

【问题讨论】:

【参考方案1】:

只是为了代码简介,将第一行从

const columnsEventModal=  Column[] = [...]
return columnsEventModal;

到线

return [...]

因为你在插入和返回语句之间没有做任何事情,Sonar 不明白你为什么要分配一个变量

【讨论】:

添加到这一点,为了保持你的类型检查,我还会在函数中添加一个返回类型 - const ColumnModalEvent = (currency: any): Column[] =&gt; ... 和/或在返回时使用as,即return [...] as Column[]; 我相信你是对的,我也会这样做,但我不知道反应,我只是喜欢声纳

以上是关于SonarLint:代码气味:不应声明局部变量,然后立即返回或抛出的主要内容,如果未能解决你的问题,请参考以下文章

Sonarlint 哨兵值假阳性

全局变量和局部变量的区别

局部内部类访问它所在方法的局部变量时,要求该局部变量必须声明为final的原因

linux——shell编程基础

全局变量局部变量闭包详解

在python程序中,一个源代码文件中,在函数体中声明的变量(包括函数参数)称?