sonar规则适用未理解到位Word格式.docx
《sonar规则适用未理解到位Word格式.docx》由会员分享,可在线阅读,更多相关《sonar规则适用未理解到位Word格式.docx(25页珍藏版)》请在冰豆网上搜索。
AtomicBoolean.
NoncompliantCodeExample
AtomicIntegeraInt1=newAtomicInteger(0);
AtomicIntegeraInt2=newAtomicInteger(0);
if(aInt1.equals(aInt2)){...}//Noncompliant
CompliantSolution
if(aInt1.get()==aInt2.get()){...}
"
不应该用来测试"
类型的等值比较。
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.
doubled=1.1;
BigDecimalbd1=newBigDecimal(d);
//Noncompliant;
seecommentabove
BigDecimalbd2=newBigDecimal(1.1);
sameresult
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
againstaspecificvalueotherthan0couldresultinfalsenegatives.
if(myCpareTo(arg)==-1){//Noncompliant
//...
}
if(myCpareTo(arg)<
0){
不应该与具体的值做检查。
8."
shouldnotreturn"
Integer.MIN_VALUE"
Itisthesign,ratherthanthemagnitudeofthevaluereturnedfrom
thatmatters.Returning
Integer.MIN_VALUE
doesnotconveyahigherdegreeofinequality,anddoingsocancauseerrorsbecausethereturnvalueof
issometimesinversed,withtheexpectationthatnegativevaluesbecomepositive.However,inversing
yields
ratherthan
Integer.MAX_VALUE.
publicintcompareTo(MyClass){
if(condition){
returnInteger.MIN_VALUE;
//Noncompliant
}
return-1;
状态值不应该用数值类型的边界值。
10."
DateUtils.truncate"
fromApacheCommonsLanglibraryshouldnotbeused
Theuseofthe
Instant
classintroducedinJava8totruncateadatecanbesignificantlyfasterthanthe
DateUtils
classfromCommonsLang.
publicDatetrunc(Datedate){
returnDateUtils.truncate(date,Calendar.SECOND);
//Noncompliant
Instantinstant=date.toInstant();
instant=instant.truncatedTo(ChronoUnit.SECONDS);
returnDate.from(instant);
正确使用,《不建议使用》
从效率上考虑的。
12."
Double.longBitsToDouble"
shouldnotbeusedfor"
int"
Double.longBitsToDouble
expectsa64-bit,
long
argument.Passitasmallervalue,suchasan
int
andthemathematicalconversionintoa
double
simplywon'
tworkasanticipatedbecausethelayoutofthebitswillbeinterpretedincorrectly,asifachildweretryingtouseanadult'
sgloves.
inti=42;
doubled=Double.longBitsToDouble(i);
Double.longBitsToDouble()方法不建议被使用
13."
entrySet()"
shouldbeiteratedwhenboththekeyandvalueareneeded
Whenonlythekeysfromamapareneededinaloop,iteratingthe
keySet
makessense.Butwhenboththekeyandthevalueareneeded,it'
smoreefficienttoiteratethe
entrySet,whichwillgiveaccesstoboththekeyandvalue,instead.
publicvoiddoSomethingWithMap(Map<
String,Object>
map){
for(Stringkey:
map.keySet()){//Noncompliant
Objectvalue=map.get(key);
for(Map.Entry<
entry:
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
theparent,theparentisnotan
intanceof
thechild.Forinstance,assumethat
RaspberryextendsFruit
andaddssomefields(requiringanewimplementationof
equals):
Fruitfruit=newFruit();
Raspberryraspberry=newRaspberry();
if(raspberryinstanceofFruit){...}//true
if(fruitinstanceofRaspberry){...}//false
Ifsimilar
checkswereusedintheclasses'
methods,thesymmetryprinciplewouldbebroken:
raspberry.equals(fruit);
//false
fruit.equals(raspberry);
//true
Additionally,non
final
classesshouldn'
tuseahardcodedclassnameinthe
methodbecausedoingsobreaksthemethodforsubclasses.Instead,makethecomparisondynamic.
Further,comparingtoanunrelatedclasstypebreaksthecontractforthatunrelatedtype,becausewhile
thisClass.equals(unrelatedClass)
canreturntrue,
unrelatedClass.equals(thisClass)
willnot.
publicclassFruitextendsFood{
privateSeasonripe;
publicbooleanequals(Objectobj){
if(obj==this){
returntrue;
}
if(Fruit.class==obj.getClass()){//Noncompliant;
brokenforchildclasses
returnripe.equals(((Fruit)obj).getRipe());
if(objinstanceofFruit){//Noncompliant;
elseif(objinstanceofSeason){//Noncompliant;
symmetrybrokenforSeasonclass
//...
if(this.getClass()==obj.getClass()){
returnfalse;
子类也需要重写,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().
publicclassFooimplementsComparable<
Foo>
{
@Override
publicintcompareTo(Foofoo){/*...*/}//Noncompliantastheequals(Objectobj)methodisnotoverridden
publicintcompareTo(Foofoo){/*...*/}//Compliant
publicbooleanequals(Objectobj){/*...*/}
使用"
时"
equals(Objectobj)也应该重写
17."
shouldtestargumenttype
BecausetheequalsmethodtakesagenericObjectasaparameter,anytypeofobjectmaybepassedtoit.Themethodshouldnotassumeitwillonlybeusedtotestobjectsofitsclasstype.Itmustinsteadchecktheparameter'
stype.
publicbooleanequals(Objectobj){
MyClassmc=(MyClass)obj;
if(obj==null)
if(this.getClass()!
=obj.getClass())
应该是检验参数类型是否为Object。
23."
hashCode"
and"
toString"
shouldnotbecalledonarrayinstances
WhilehashCodeandtoStringareavailableonarrays,theyarelargelyuseless.hashCodereturnsthearray'
s"
identityhashcode"
andtoStringreturnsnearlythesamevalue.Neithermethod'
soutputactuallyreflectsthearray'
scontents.Instead,youshouldpassthearraytotherelevantstaticArraysmethod.
publicstaticvoidmain(String[]args)
{
StringargStr=args.toString();
intargHash=args.hashCode();
StringargStr=Arrays.toString(args);
intargHash=Arrays.hashCode(args);
不应该被数组实例调用。
27."
instanceof"
operatorsthatalwaysreturn"
true"
or"
false"
shouldberemoved
instanceofoperatorsthatalwaysreturntrueorfalseareeitheruselessortheresultofamisunderstandingwhichcouldleadtounexpectedbehaviorinproduction.