always evaluate to false some subsequent code is never executed

拿Sonarqube扫码老代码,是一场历练!大多数情况下,sonarqube都能提出合理的修改建议,只是有的时候,验证不出sonarqube指出的问题。来来来,看一个今天抓到的“粒子”!

————sonarqube 提示开始———–

Change this condition so that it does not always evaluate to ‘false’; some subsequent code is never executed.

Conditional expressions which are always true or false can lead to dead code. Such code is always buggy and should never be used in production.

Noncompliant Code Example

a = false;if (a) // Noncompliant{  DoSomething(); // never executed}if (!a || b) // Noncompliant; "!a" is always "true", "b" is never evaluated{  DoSomething();}else{  DoSomethingElse(); // never executed}
  • Exceptions

  • This rule will not raise an issue in either of these cases:
  • When the condition is a single const bool
const bool debug = false;//...if (debug){  // Print something}
  • When the condition is the literal true or false.

In these cases it is obvious the code is as intended.

See

  • MISRA C:2004, 13.7 – Boolean operations whose results are invariant shall not be permitted.
  • MISRA C:2012, 14.3 – Controlling expressions shall not be invariant
  • MITRE, CWE-570 – Expression is Always False
  • MITRE, CWE-571 – Expression is Always True
  • CERT, MSC12-C. – Detect and remove code that has no effect or is never executed

————sonarqube 提示结束———–

怪怪的

sonarqube有图有真像,差点就相信了,赶紧做个小实验验证一下Sonarqube的提示。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;namespace TestStringIsNullOrEmpty{    class Program    {        static void Main(string[] args)        {           // Console.WriteLine(String.Format("null {0}", CheckEmail(null)));            Console.WriteLine(String.Format("空 {0}", CheckEmail("")));            Console.WriteLine(String.Format("hello@yue.ma {0}", CheckEmail("hello@yue.ma")));            Console.ReadLine();        }        public static bool CheckEmail(string email)        {            string[] emailList = email.Split(';');            if (emailList.Length > 1)            {                return false;            }            if (string.IsNullOrEmpty(email))            {                return false;            }            return true;        }    }}

结果:

Falsehello@yue.ma True

传null会报错,进不到string.IsNullOrEmpty(email),但是传空字符的时候,抵达了string.IsNullOrEmpty(email),传正常邮箱地址,也抵达了string.IsNullOrEmpty(email),false,true都有返回。

实验结果:

sonarqube开了个玩笑!写代码,写出好代码,sonarqube是一个不错的助手工具,然而,还得结合实际情况再考虑清楚,目前至少发现sonarqube几个不适当的提示了!关注公众号,查收更多sonarqube代码检查小知识经验!

点评:有选择性的忽略sonarqube建议,不要被sonarqube带沟里!你平时会注意这个细节么?欢迎留言写出你的感受!

此条目发表在未分类分类目录。将固定链接加入收藏夹。

发表评论

邮箱地址不会被公开。 必填项已用*标注