sonar规则适用未理解到位.docx

上传人:b****6 文档编号:5871240 上传时间:2023-01-01 格式:DOCX 页数:25 大小:30.56KB
下载 相关 举报
sonar规则适用未理解到位.docx_第1页
第1页 / 共25页
sonar规则适用未理解到位.docx_第2页
第2页 / 共25页
sonar规则适用未理解到位.docx_第3页
第3页 / 共25页
sonar规则适用未理解到位.docx_第4页
第4页 / 共25页
sonar规则适用未理解到位.docx_第5页
第5页 / 共25页
点击查看更多>>
下载资源
资源描述

sonar规则适用未理解到位.docx

《sonar规则适用未理解到位.docx》由会员分享,可在线阅读,更多相关《sonar规则适用未理解到位.docx(25页珍藏版)》请在冰豆网上搜索。

sonar规则适用未理解到位.docx

sonar规则适用未理解到位

1.".equals()"shouldnotbeusedtotestthevaluesof"Atomic"classes

AtomicInteger,and AtomicLong extend Number,butthey'redistinctfrom Integer and Long andshouldbehandleddifferently. AtomicInteger and AtomicLong aredesignedtosupportlock-free,thread-safeprogrammingonsinglevariables.Assuch,anAtomicInteger willonlyeverbe"equal"toitself.Instead,youshould .get() thevalueandmakecomparisonsonit.

Thisappliestoalltheatomic,seeming-primitivewrapperclasses:

 AtomicInteger, AtomicLong,and AtomicBoolean.

NoncompliantCodeExample

AtomicIntegeraInt1=newAtomicInteger(0);

AtomicIntegeraInt2=newAtomicInteger(0);

if(aInt1.equals(aInt2)){...}//Noncompliant

CompliantSolution

AtomicIntegeraInt1=newAtomicInteger(0);

AtomicIntegeraInt2=newAtomicInteger(0);

if(aInt1.get()==aInt2.get()){...}

".equals()"不应该用来测试"Atomic"类型的等值比较。

 

3."BigDecimal(double)"shouldnotbeused

Becauseoffloatingpointimprecision,you'reunlikelytogetthevalueyouexpectfromthe BigDecimal(double) constructor.

From theJavaDocs:

Theresultsofthisconstructorcanbesomewhatunpredictable.OnemightassumethatwritingnewBigDecimal(0.1)inJavacreatesaBigDecimalwhichisexactlyequalto0.1(anunscaledvalueof1,withascaleof1),butitisactuallyequalto0.1000000000000000055511151231257827021181583404541015625.Thisisbecause0.1cannotberepresentedexactlyasadouble(or,forthatmatter,asabinaryfractionofanyfinitelength).Thus,thevaluethatisbeingpassedintotheconstructorisnotexactlyequalto0.1,appearancesnotwithstanding.

Instead,youshoulduse BigDecimal.valueOf,whichusesastringunderthecoverstoeliminatefloatingpointroundingerrors.

NoncompliantCodeExample

doubled=1.1;

BigDecimalbd1=newBigDecimal(d);//Noncompliant;seecommentabove

BigDecimalbd2=newBigDecimal(1.1);//Noncompliant;sameresult

CompliantSolution

doubled=1.1;

BigDecimalbd1=BigDecimal.valueOf(d);

BigDecimalbd2=BigDecimal.valueOf(1.1);

See

CERT,NUM10-J -DonotconstructBigDecimalobjectsfromfloating-pointliterals

数值正确使用

7."compareTo"resultsshouldnotbecheckedforspecificvalues

Whilemost compareTo methodsreturn-1,0,or1,somedonot,andtestingtheresultofa compareTo againstaspecificvalueotherthan0couldresultinfalsenegatives.

NoncompliantCodeExample

if(myCpareTo(arg)==-1){//Noncompliant

//...

}

CompliantSolution

if(myCpareTo(arg)<0){

//...

}

"compareTo"不应该与具体的值做检查。

8."compareTo"shouldnotreturn"Integer.MIN_VALUE"

Itisthesign,ratherthanthemagnitudeofthevaluereturnedfrom compareTo thatmatters.Returning Integer.MIN_VALUE doesnotconveyahigherdegreeofinequality,anddoingsocancauseerrorsbecausethereturnvalueof compareTo issometimesinversed,withtheexpectationthatnegativevaluesbecomepositive.However,inversing Integer.MIN_VALUE yields Integer.MIN_VALUE ratherthan Integer.MAX_VALUE.

NoncompliantCodeExample

publicintcompareTo(MyClass){

if(condition){

returnInteger.MIN_VALUE;//Noncompliant

}

CompliantSolution

publicintcompareTo(MyClass){

if(condition){

return-1;

}

状态值不应该用数值类型的边界值。

10."DateUtils.truncate"fromApacheCommonsLanglibraryshouldnotbeused

Theuseofthe Instant classintroducedinJava8totruncateadatecanbesignificantlyfasterthanthe DateUtils classfromCommonsLang.

NoncompliantCodeExample

publicDatetrunc(Datedate){

returnDateUtils.truncate(date,Calendar.SECOND);//Noncompliant

}

CompliantSolution

publicDatetrunc(Datedate){

Instantinstant=date.toInstant();

instant=instant.truncatedTo(ChronoUnit.SECONDS);

returnDate.from(instant);

}

"DateUtils.truncate"正确使用,《不建议使用》 

从效率上考虑的。

12."Double.longBitsToDouble"shouldnotbeusedfor"int"

Double.longBitsToDouble expectsa64-bit, long argument.Passitasmallervalue,suchasan int andthemathematicalconversionintoa double simplywon'tworkasanticipatedbecausethelayoutofthebitswillbeinterpretedincorrectly,asifachildweretryingtouseanadult'sgloves.

NoncompliantCodeExample

inti=42;

doubled=Double.longBitsToDouble(i);//Noncompliant

Double.longBitsToDouble()方法不建议被使用

13."entrySet()"shouldbeiteratedwhenboththekeyandvalueareneeded

Whenonlythekeysfromamapareneededinaloop,iteratingthe keySet makessense.Butwhenboththekeyandthevalueareneeded,it'smoreefficienttoiteratethe entrySet,whichwillgiveaccesstoboththekeyandvalue,instead.

NoncompliantCodeExample

publicvoiddoSomethingWithMap(Mapmap){

for(Stringkey:

map.keySet()){//Noncompliant

Objectvalue=map.get(key);

//...

}

}

CompliantSolution

publicvoiddoSomethingWithMap(Mapmap){

for(Map.Entryentry:

map.entrySet()){

Stringkey=entry.getKey();

Objectvalue=entry.getValue();

//...

}

}

“entryset()”应该是迭代时,键和值是必要的

keySet是键的集合,Set里面的类型即key的类型

entrySet是键-值对的集合,Set里面的类型是Map.Entry

14."equals"methodsshouldbesymmetricandworkforsubclasses

Akeyfacetofthe equals contractisthatif a.equals(b) then b.equals(a),i.e.thattherelationshipissymmetric.

Using instanceof breaksthecontractwhentherearesubclasses,becausewhilethechildisan instanceof theparent,theparentisnotan intanceof thechild.Forinstance,assumethat RaspberryextendsFruit andaddssomefields(requiringanewimplementationof equals):

Fruitfruit=newFruit();

Raspberryraspberry=newRaspberry();

if(raspberryinstanceofFruit){...}//true

if(fruitinstanceofRaspberry){...}//false

Ifsimilar instanceof checkswereusedintheclasses' equals methods,thesymmetryprinciplewouldbebroken:

raspberry.equals(fruit);//false

fruit.equals(raspberry);//true

Additionally,non final classesshouldn'tuseahardcodedclassnameinthe equals methodbecausedoingsobreaksthemethodforsubclasses.Instead,makethecomparisondynamic.

Further,comparingtoanunrelatedclasstypebreaksthecontractforthatunrelatedtype,becausewhile thisClass.equals(unrelatedClass) canreturntrue, unrelatedClass.equals(thisClass) willnot.

NoncompliantCodeExample

publicclassFruitextendsFood{

privateSeasonripe;

publicbooleanequals(Objectobj){

if(obj==this){

returntrue;

}

if(Fruit.class==obj.getClass()){//Noncompliant;brokenforchildclasses

returnripe.equals(((Fruit)obj).getRipe());

}

if(objinstanceofFruit){//Noncompliant;brokenforchildclasses

returnripe.equals(((Fruit)obj).getRipe());

}

elseif(objinstanceofSeason){//Noncompliant;symmetrybrokenforSeasonclass

//...

}

//...

CompliantSolution

publicclassFruitextendsFood{

privateSeasonripe;

publicbooleanequals(Objectobj){

if(obj==this){

returntrue;

}

if(this.getClass()==obj.getClass()){

returnripe.equals(((Fruit)obj).getRipe());

}

returnfalse;

}

"equals"子类也需要重写,equals一个重要属性是,如果a.equals(b)然后b.equals(A),即是对称的关系。

建议使用此规则。

16."equals(Objectobj)"shouldbeoverriddenalongwiththe"compareTo(Tobj)"method

AccordingtotheJava CpareTo(To) documentation:

Itisstronglyrecommended,butnotstrictlyrequiredthat (pareTo(y)==0)==(x.equals(y)).Generallyspeaking,anyclassthatimplementstheComparableinterfaceandviolatesthisconditionshouldclearlyindicatethisfact.Therecommendedlanguageis"Note:

thisclasshasanaturalorderingthatisinconsistentwithequals."

Ifthisruleisviolated,weirdandunpredictablefailurescanoccur.Forexample,inJava5the PriorityQueue.remove() methodreliedon compareTo(),butsinceJava6itrelieson equals().

NoncompliantCodeExample

publicclassFooimplementsComparable{

@Override

publicintcompareTo(Foofoo){/*...*/}//Noncompliantastheequals(Objectobj)methodisnotoverridden

}

CompliantSolution

publicclassFooimplementsComparable{

@Override

publicintcompareTo(Foofoo){/*...*/}//Compliant

@Override

publicbooleanequals(Objectobj){/*...*/}

}

使用"compareTo(Tobj)"时"equals(Objectobj)也应该重写

17."equals(Objectobj)"shouldtestargumenttype

BecausetheequalsmethodtakesagenericObjectasaparameter,anytypeofobjectmaybepassedtoit.Themethodshouldnotassumeitwillonlybeusedtotestobjectsofitsclasstype.Itmustinsteadchecktheparameter'stype.

NoncompliantCodeExample

publicbooleanequals(Objectobj){

MyClassmc=(MyClass)obj;//Noncompliant

//...

}

CompliantSolution

publicbooleanequals(Objectobj){

if(obj==null)

returnfalse;

if(this.getClass()!

=obj.getClass())

returnfalse;

MyClassmc=(MyClass)obj;

//...

}

"equals(Objectobj)"应该是检验参数类型是否为Object。

23."hashCode"and"toString"shouldnotbecalledonarrayinstances

WhilehashCodeandtoStringareavailableonarrays,theyarelargelyuseless.hashCodereturnsthearray's"identityhashcode",andtoStringreturnsnearlythesamevalue.Neithermethod'soutputactuallyreflectsthearray'scontents.Instead,youshouldpassthearraytotherelevantstaticArraysmethod.

NoncompliantCodeExample

publicstaticvoidmain(String[]args)

{

StringargStr=args.toString();//Noncompliant

intargHash=args.hashCode();//Noncompliant

CompliantSolution

publicstaticvoidmain(String[]args)

{

StringargStr=Arrays.toString(args);

intargHash=Arrays.hashCode(args);

"hashCode"and"toString"不应该被数组实例调用。

27."instanceof"operatorsthatalwaysreturn"true"or"false"shouldberemoved

instanceofoperatorsthatalwaysreturntrueorfalseareeitheruselessortheresultofamisunderstandingwhichcouldleadtounexpectedbehaviorinproduction.

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 自然科学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1