File: codenarc-rules-unnecessary.html

package info (click to toggle)
codenarc 0.23-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 11,312 kB
  • sloc: java: 2,530; xml: 1,088; makefile: 21
file content (1073 lines) | stat: -rw-r--r-- 56,355 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- Generated by Apache Maven Doxia Site Renderer 1.4 at 18 Feb 2015 -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>CodeNarc - CodeNarc - Unnecessary Rules</title>
    <style type="text/css" media="all">
      @import url("./css/maven-base.css");
      @import url("./css/maven-theme.css");
      @import url("./css/site.css");
    </style>
    <link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
    <meta name="Date-Revision-yyyymmdd" content="20150218" />
    <meta http-equiv="Content-Language" content="en" />
                  
        </head>
  <body class="composite">
    <div id="banner">
                                              <a href="./" id="bannerLeft">
                                                <img src="images/codenarc-logo.png" alt="CodeNarc" />
                </a>
                              <a href="http://github.com/CodeNarc" id="bannerRight">
                                                <img src="images/forkme_right_red_aa0000.png" alt="Fork me on GitHub" />
                </a>
            <div class="clear">
        <hr/>
      </div>
    </div>
    <div id="breadcrumbs">
            
                    
                <div class="xleft">
        <span id="publishDate">Last Published: 18 Feb 2015</span>
                  &nbsp;| <span id="projectVersion">Version: 0.23</span>
                      </div>
            <div class="xright">        
                    
      </div>
      <div class="clear">
        <hr/>
      </div>
    </div>
    <div id="leftColumn">
      <div id="navcolumn">
             
                    
                                <h5>General</h5>
                  <ul>
                  <li class="none">
                          <a href="index.html" title="Home">Home</a>
            </li>
                  <li class="none">
                          <a href="https://sourceforge.net/project/showfiles.php?group_id=250145" class="externalLink" title="Downloads">Downloads</a>
            </li>
                  <li class="none">
                          <a href="apidocs/index.html" title="Javadocs">Javadocs</a>
            </li>
                  <li class="none">
                          <a href="http://sourceforge.net/mail/?group_id=250145" class="externalLink" title="Mailing Lists">Mailing Lists</a>
            </li>
                  <li class="none">
                          <a href="http://sourceforge.net/tracker/?group_id=250145" class="externalLink" title="Bug Tracker">Bug Tracker</a>
            </li>
                  <li class="none">
                          <a href="http://sourceforge.net/projects/codenarc" class="externalLink" title="SourceForge Project">SourceForge Project</a>
            </li>
                  <li class="none">
                          <a href="http://github.com/CodeNarc" class="externalLink" title="GitHub Project">GitHub Project</a>
            </li>
          </ul>
                       <h5>Running</h5>
                  <ul>
                  <li class="none">
                          <a href="codenarc-ant-task.html" title="Ant Task Usage">Ant Task Usage</a>
            </li>
                  <li class="none">
                          <a href="codenarc-command-line.html" title="Command-Line">Command-Line</a>
            </li>
                  <li class="none">
                          <a href="codenarc-run-as-a-test.html" title="Run as a Test">Run as a Test</a>
            </li>
                  <li class="none">
                          <a href="codenarc-other-tools-frameworks.html" title="Other Tools/Frameworks">Other Tools/Frameworks</a>
            </li>
          </ul>
                       <h5>Using</h5>
                  <ul>
                  <li class="none">
                          <a href="codenarc-creating-ruleset.html" title="Creating a RuleSet">Creating a RuleSet</a>
            </li>
                  <li class="none">
                          <a href="codenarc-creating-rule.html" title="Creating a Rule">Creating a Rule</a>
            </li>
                  <li class="none">
                          <a href="codenarc-configuring-rules.html" title="Configuring Rules">Configuring Rules</a>
            </li>
                  <li class="none">
                          <a href="StarterRuleSet-AllRulesByCategory.groovy.txt" title="Starter RuleSet (All)">Starter RuleSet (All)</a>
            </li>
          </ul>
                       <h5>Report Types</h5>
                  <ul>
                  <li class="none">
                          <a href="codenarc-HtmlReportWriter.html" title="HTML Report">HTML Report</a>
            </li>
                  <li class="none">
                          <a href="codenarc-XmlReportWriter.html" title="XML Report">XML Report</a>
            </li>
                  <li class="none">
                          <a href="codenarc-TextReportWriter.html" title="Text and IDE Reports">Text and IDE Reports</a>
            </li>
          </ul>
                       <h5>Sample Reports</h5>
                  <ul>
                  <li class="none">
                          <a href="SampleCodeNarcHtmlReport.html" title="Sample HTML Report">Sample HTML Report</a>
            </li>
                  <li class="none">
                          <a href="SampleCodeNarcXmlReport.xml" title="Sample XML Report">Sample XML Report</a>
            </li>
          </ul>
                       <h5>Rules</h5>
                  <ul>
                  <li class="none">
                          <a href="codenarc-rule-index.html" title="Rule Index">Rule Index</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-basic.html" title="Basic Rules">Basic Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-braces.html" title="Braces Rules">Braces Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-concurrency.html" title="Concurrency Rules">Concurrency Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-convention.html" title="Convention Rules">Convention Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-design.html" title="Design Rules">Design Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-dry.html" title="DRY Rules">DRY Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-enhanced.html" title="Enhanced Rules">Enhanced Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-exceptions.html" title="Exceptions Rules">Exceptions Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-formatting.html" title="Formatting Rules">Formatting Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-generic.html" title="Generic Rules">Generic Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-grails.html" title="Grails Rules">Grails Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-groovyism.html" title="Groovyism Rules">Groovyism Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-imports.html" title="Imports Rules">Imports Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-jdbc.html" title="JDBC Rules">JDBC Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-junit.html" title="JUnit Rules">JUnit Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-logging.html" title="Logging Rules">Logging Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-naming.html" title="Naming Rules">Naming Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-size.html" title="Size/Complexity Rules">Size/Complexity Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-security.html" title="Security Rules">Security Rules</a>
            </li>
                  <li class="none">
                          <a href="codenarc-rules-serialization.html" title="Serialization Rules">Serialization Rules</a>
            </li>
                  <li class="none">
            <strong>Unnecessary Rules</strong>
          </li>
                  <li class="none">
                          <a href="codenarc-rules-unused.html" title="Unused Rules">Unused Rules</a>
            </li>
          </ul>
                       <h5>Developing</h5>
                  <ul>
                  <li class="none">
                          <a href="codenarc-developer-guide.html" title="Developer Guide">Developer Guide</a>
            </li>
          </ul>
                       <h5>Project Documentation</h5>
                  <ul>
                                                                    <li class="collapsed">
                          <a href="project-info.html" title="Project Information">Project Information</a>
                  </li>
                                                                                                                          <li class="collapsed">
                          <a href="project-reports.html" title="Project Reports">Project Reports</a>
                  </li>
          </ul>
                                                                                                                               <a href="http://sourceforge.net" title="Hosted on SourceForge.net" class="poweredBy">
        <img class="poweredBy"  alt="Hosted on SourceForge.net" src="http://sflogo.sourceforge.net/sflogo.php?group_id=208647&type=2"     />
      </a>
                                                                                                                      <a href="http://maven.apache.org" title="Build with Maven 2" class="poweredBy">
        <img class="poweredBy"  alt="Build with Maven 2" src="images/logos/maven-feather.png"     />
      </a>
                       
                    
            </div>
    </div>
    <div id="bodyColumn">
      <div id="contentBox">
        <div class="section">
<h2>Unnecessary Rules (&quot;<i>rulesets/unnecessary.xml</i>&quot;)<a name="Unnecessary_Rules_rulesetsunnecessary.xml"></a></h2><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<div class="section">
<h3><a name="AddEmptyString">AddEmptyString</a> Rule<a name="AddEmptyString_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>Finds empty string literals which are being added. This is an inefficient way to convert any type to a String.</p>
<p>Examples:</p>
<div>
<pre>    // do not add empty strings to things
    def a = '' + 123
    def b = method('' + property)

    // these examples are OK and do not trigger violations
    def c = 456.toString()
    def d = property?.toString() ?: &quot;&quot;
</pre></div></div>
<div class="section">
<h3><a name="ConsecutiveLiteralAppends">ConsecutiveLiteralAppends</a> Rule<a name="ConsecutiveLiteralAppends_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>Violations occur when method calls to append(Object) are chained together with literals as parameters. The chained calls can be joined into one invocation.</p>
<p>Example of violations:</p>
<div>
<pre>    writer.append('foo').append('bar')      // strings can be joined
    writer.append('foo').append(5)          // string and number can be joined
    writer.append('Hello').append(&quot;$World&quot;) // GString can be joined
</pre></div>
<p>Example of passing code:</p>
<div>
<pre>    // usage not chained invocation
    writer.append('Hello')
    writer.append('World')

    writer.append(null).append(5)           // nulls cannot be joined

    writer.append().append('Hello')             // no arg append is unknown
    writer.append('a', 'b').append('Hello')     // two arg append is unknown
</pre></div></div>
<div class="section">
<h3><a name="ConsecutiveStringConcatenation">ConsecutiveStringConcatenation</a> Rule<a name="ConsecutiveStringConcatenation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>Catches concatenation of two string literals on the same line. These can safely by joined. In Java, the Java compiler will join two String literals together and place them in the Constant Pool. However, Groovy will not because the plus() method may override the + operator.</p>
<p>Examples:</p>
<div>
<pre>    // Violations
    def a = 'Hello' + 'World'   // should be 'HelloWorld'
    def b = &quot;$Hello&quot; + 'World'  // should be &quot;${Hello}World&quot;
    def c = 'Hello' + &quot;$World&quot;  // should be &quot;Hello${World}&quot;
    def d = 'Hello' + 5         // should be 'Hello5'
    def e = 'Hello' + '''
                        world   // should be joined
                      '''
    def f = '''Hello
                  ''' + 'world'   // should be joined


    // Not Violations
    def g = 'Hello' +           // OK because of line break
                'World'
    def h = 'Hello' + null      // OK because not a string
    def i = 'Hello' + method()  // OK because not a string
    def j = 'Hello' - &quot;$World&quot;  // OK because not +
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryBigDecimalInstantiation">UnnecessaryBigDecimalInstantiation</a> Rule<a name="UnnecessaryBigDecimalInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>It is unnecessary to instantiate <tt>BigDecimal</tt> objects. Instead just use the decimal literal or the 'G' identifier to force the type, such as <tt>123.45</tt> or <tt>123.45G</tt>.</p>
<p>This rule does not produce violations when the parameter evaluates to an integer/long, e.g. <tt>new BigDecimal(42)</tt>, <tt>new BigDecimal(42L)</tt> or <tt>new BigDecimal(&quot;42&quot;)</tt>, because using the &quot;G&quot; suffix on an integer value produces a <tt>BigInteger</tt>, rather than a <tt>BigDecimal</tt>, e.g. <tt>45G</tt>. So that means there is no way to produce a <tt>BigDecimal</tt> with exactly that value using a literal.</p>
<p>This rule also does not produce violations when the parameter is a double, e.g. <tt>new BigDecimal(12.3)</tt>. That scenario is covered by the <a href="./codenarc-rules-basic.html#BigDecimalInstantiation">BigDecimalInstantiation</a> rule, because that produces an unpredictable (double) value (and so it is <i>unsafe</i>, rather than <i>unnecessary</i>).</p></div>
<div class="section">
<h3><a name="UnnecessaryBigIntegerInstantiation">UnnecessaryBigIntegerInstantiation</a> Rule<a name="UnnecessaryBigIntegerInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>It is unnecessary to instantiate <tt>BigInteger</tt> objects. Instead just use the literal with the 'G' identifier to force the type, such as <tt>8G</tt> or <tt>42G</tt>.</p></div>
<div class="section">
<h3><a name="UnnecessaryBooleanExpression">UnnecessaryBooleanExpression</a> Rule<a name="UnnecessaryBooleanExpression_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p>Checks for unnecessary boolean expressions, including ANDing (&amp;&amp;) or ORing (||) with <tt>true</tt>, <tt>false</tt>, <tt>null</tt>, or a Map/List/String/Number literal.</p>
<p>This rule also checks for negation (!) of <tt>true</tt>, <tt>false</tt>, <tt>null</tt>, or a Map/List/String/Number literal.</p>
<p>Examples of violations include:</p>
<div>
<pre>    result = value &amp;&amp; true              // AND or OR with boolean constants
    if (false || value) { .. }
    return value &amp;&amp; Boolean.FALSE

    result = null &amp;&amp; value              // AND or OR with null

    result = value &amp;&amp; &quot;abc&quot;             // AND or OR with String literal

    result = value &amp;&amp; 123               // AND or OR with Number literal
    result = 678.123 || true

    result = value &amp;&amp; [x, y]            // AND or OR with List literal

    result = [a:123] &amp;&amp; value           // AND or OR with Map literal

    result = !true                      // Negation of boolean constants
    result = !false
    result = !Boolean.TRUE

    result = !null                      // Negation of null

    result = !&quot;abc&quot;                     // Negation of String literal

    result = ![a:123]                   // Negation of Map literal

    result = ![a,b]                     // Negation of List literal
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryBooleanInstantiation">UnnecessaryBooleanInstantiation</a> Rule<a name="UnnecessaryBooleanInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12 (formerly BooleanInstantiation Rule in the &quot;basic&quot; rule set)</i></p>
<p>Checks for direct call to a <tt>Boolean</tt> constructor. Use <tt>Boolean.valueOf()</tt> or the <tt>Boolean.TRUE</tt> and <tt>Boolean.FALSE</tt> constants instead of calling the <tt>Boolean()</tt> constructor directly.</p>
<p>Also checks for <tt>Boolean.valueOf(true)</tt> or <tt>Boolean.valueOf(false)</tt>. Use the <tt>Boolean.TRUE</tt> or <tt>Boolean.FALSE</tt> constants instead.</p>
<p>Here is an example of code that produces a violation:</p>
<div>
<pre>    def b1 = new Boolean(true)             // violation
    def b2 = new java.lang.Boolean(false)  // violation
    def b3 = Boolean.valueOf(true)         // violation
    def b4 = Boolean.valueOf(false)        // violation
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryCallForLastElement">UnnecessaryCallForLastElement</a> Rule<a name="UnnecessaryCallForLastElement_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>This rule checks for excessively verbose methods of accessing the last element of an array or list. For instance, it is possible to access the last element of an array by performing <tt>array[array.length - 1]</tt>, in Groovy it is simpler to either call <tt>array.last()</tt> or <tt>array[-1]</tt>. The same is true for lists. This violation is triggered whenever a <tt>get</tt>, <tt>getAt</tt>, or array-style access is used with an object size check.</p>
<p>Code like this all cause violations.</p>
<div>
<pre>    def x = [0, 1, 2]
    def a = x.get(x.size() -1)
    def b = x.get(x.length -1)
    def c = x.getAt(x.size() -1)
    def d = x.getAt(x.length -1)
    def f = x[(x.size() -1]
    def d = x[(x.length -1]
</pre></div>
<p>All of this code is fine though:</p>
<div>
<pre>    def x = [0, 1, 2]
    def a = x.last()
    def b = x[-1]
    def c = x.getAt(-1)
    def d = x.get(z.size() -1)     // different objects
    def e = x.get(z.length -1)     // different objects
    def f = x.getAt(z.size() -1)   // different objects
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryCallToSubstring">UnnecessaryCallToSubstring</a> Rule<a name="UnnecessaryCallToSubstring_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>Calling String.substring(0) always returns the original string. This code is meaningless.</p>
<p>Examples:</p>
<div>
<pre>    string.substring(0)         // violation
    method().substring(0)       // violation

    prop.substring(1)           // OK, not constant 0
    prop.substring(0, 1)        // OK, end is specified
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryCast">UnnecessaryCast</a> Rule<a name="UnnecessaryCast_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.21</i></p>
<p>Checks for unnecessary cast operations.</p>
<p>Example of violations:</p>
<div>
<pre>    int count = (int)123                    // violation
    def longValue = (long)123456L           // violation
    def bigDecimal = (BigDecimal)1234.56    // violation
    String name = (String) &quot;Joe&quot;            // violation
    def list = (List)[1, 2, 3]              // violation
    def map = (Map)[a:1]                    // violation
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryCatchBlock">UnnecessaryCatchBlock</a> Rule<a name="UnnecessaryCatchBlock_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>Violations are triggered when a <i>catch</i> block does nothing but throw the original exception. In this scenario there is usually no need for a <i>catch</i> block, just let the exception be thrown from the original code. This condition frequently occurs when catching an exception for debugging purposes but then forgetting to take the <tt>catch</tt> statement out.</p></div>
<div class="section">
<h3><a name="UnnecessaryCollectCall">UnnecessaryCollectCall</a> Rule<a name="UnnecessaryCollectCall_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>Some method calls to <tt>Object.collect(Closure)</tt> can be replaced with the spread operator. For instance, <tt>list.collect <a name="it.multiply2"> it.multiply(2) </a></tt> can be replaced by <tt>list*.multiply(2)</tt>.</p>
<p>Examples of violations include:</p>
<div>
<pre>    assert [1, 2, 3].collect { it.multiply(2) }
    assert [1, 2, 3].collect { x -&gt; x.multiply(2) }
    [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;].collect { it.bytes }
</pre></div>
<p>The following code does not produce violations:</p>
<div>
<pre>    [1, 2, 3].collect { it * it }   // OK, closure parameter is referenced twice

    [1, 2, 3].mapMethod { it.multiply(5) } // OK, method call is not collect

    [1, 2, 3].collect(5) // OK, collect parameter is not a closure

    // OK, the closure is not a simple one line statement
    [1, 2, 3].collect { println it; it.multiply(5) }

    // OK, closure has too many arguments
    [1, 2, 3].collect { a, b -&gt; a.multiply(b) }

    // OK, closure statement references parameter multiple times
    [1, 2, 3].collect { it.multiply(it) }

    // OK, it is referenced several times in the closure
    [1, 2, 3].collect { it.multiply(2).multiply(it) }
    [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;].collect { it.bytes.foo(it) }

    // OK, chained methods are too complex to analyze at this point
    [1, 2, 3].collect { it.multiply(2).multiply(4) }

    // in general the above examples can be rewritten like this:
    [1, 2, 3]*.multiply(2)
    [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]*.bytes
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryCollectionCall">UnnecessaryCollectionCall</a> Rule<a name="UnnecessaryCollectionCall_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.11</i></p>
<p>Checks for useless calls to collections. For any collection <tt>c</tt>, calling <tt>c.containsAll(c)</tt> should always be <tt>true</tt>, and <tt>c.retainAll(c)</tt> should have no effect.</p></div>
<div class="section">
<h3><a name="UnnecessaryConstructor">UnnecessaryConstructor</a> Rule<a name="UnnecessaryConstructor_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.11</i></p>
<p>This rule detects when a constructor is not necessary; i.e., when there's only one constructor, it's <tt>public</tt>, has an empty body, and takes no arguments, or else contains only a single call to <tt>super()</tt>.</p>
<p>Example of violations:</p>
<div>
<pre>    class MyClass {
        public MyClass() {          // violation; constructor is not necessary
        }
    }

    class MyClass2 extends OtherClass {
        MyClass2() {                // violation; constructor is not necessary
            super()
        }
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryDefInFieldDeclaration">UnnecessaryDefInFieldDeclaration</a> Rule<a name="UnnecessaryDefInFieldDeclaration_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.16</i></p>
<p>If a field has a visibility modifier or a type declaration, then the def keyword is unneeded. For instance, 'static def constraints = <a name="a"></a>' is redundant and can be simplified to 'static constraints = <a name="a"></a>.</p>
<p>Example of violations:</p>
<div>
<pre>    class MyClass {
        // def is redundant
        static def constraints = {  }

        // def and private is redundant
        def private field1 = { }

        // def and protected is redundant
        def protected field2 = { }

        // def and public is redundant
        def public field3 = { }

        // def and static is redundant
        def static field4 = { }

        // def and type is redundant
        def Object field5 = { }
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryDefInMethodDeclaration">UnnecessaryDefInMethodDeclaration</a> Rule<a name="UnnecessaryDefInMethodDeclaration_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>If a method has a visibility modifier or a type declaration, then the def keyword is unneeded. For instance 'def private method() <a name="a"></a>' is redundant and can be simplified to 'private method() <a name="a"></a>'.</p>
<p>Examples of violations:</p>
<div>
<pre>    // def and private is redundant
    def private method1() { return 4 }

    // def and protected is redundant
    def protected method2() { return 4 }

    // def and public is redundant
    def public method3() { return 4 }

    // def and static is redundant
    def static method4() { return 4 }

    // def and type is redundant
    def Object method5() { return 4 }

    class MyClass {
        def MyClass() {}    // def is redundant
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryDefInVariableDeclaration">UnnecessaryDefInVariableDeclaration</a> Rule<a name="UnnecessaryDefInVariableDeclaration_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.15</i></p>
<p>If a variable has a visibility modifier or a type declaration, then the def keyword is unneeded. For instance 'def private n = 2' is redundant and can be simplified to 'private n = 2'.</p>
<p>Examples of violations:</p>
<div>
<pre>    // def and private is redundant
    def private string1 = 'example'

    // def and protected is redundant
    def protected string2 = 'example'

    // def and public is redundant
    def public string3 = 'example'

    // def and static is redundant
    def static string4 = 'example'

    // def and final is redundant
    def final string5 = 'example'

    // def and a type is redundant
    def String string6 = 'example'
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryDotClass">UnnecessaryDotClass</a> Rule<a name="UnnecessaryDotClass_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.15</i></p>
<p>To make a reference to a class, it is unnecessary to specify the '.class' identifier. For instance String.class can be shortened to String.</p>
<p>Example of violations:</p>
<div>
<pre>    // The '.class' identifier is unnecessary, violation occurs
    def x = String.class

    // Ok, unnecessary '.class' identifier has been excluded
    def x = String
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryDoubleInstantiation">UnnecessaryDoubleInstantiation</a> Rule<a name="UnnecessaryDoubleInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>It is unnecessary to instantiate <tt>Double</tt> objects. Instead just use the double literal with 'D' identifier to force the type, such as <tt>123.45d</tt> or <tt>0.42d</tt>.</p></div>
<div class="section">
<h3><a name="UnnecessaryElseStatement">UnnecessaryElseStatement</a> Rule<a name="UnnecessaryElseStatement_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.14</i></p>
<p>When an <tt>if</tt> statement block ends with a <tt>return</tt> statement, then the <tt>else</tt> is unnecessary. The logic in the <tt>else</tt> branch can be run without being in a new scope.</p>
<p>Example of violations:</p>
<div>
<pre>    if(value){
        println 'Executing if logic...'
        return true
    } else {
        println 'Executing else logic...'
    }

    // can be replaced by:

    if(value){
        println 'Executing if logic...'
        return true
    }
    println 'Executing else logic...'
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryFinalOnPrivateMethod">UnnecessaryFinalOnPrivateMethod</a> Rule<a name="UnnecessaryFinalOnPrivateMethod_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.14</i></p>
<p>A private method is marked final. Private methods cannot be overridden, so marking it final is unnecessary.</p>
<p>Example of violations:</p>
<div>
<pre>    private final method() {}
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryFloatInstantiation">UnnecessaryFloatInstantiation</a> Rule<a name="UnnecessaryFloatInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>It is unnecessary to instantiate <tt>Float</tt> objects. Instead just use the float literal with the 'F' identifier to force the type, such as <tt>123.45F</tt> or <tt>0.42f</tt>.</p></div>
<div class="section">
<h3><a name="UnnecessaryGetter">UnnecessaryGetter</a> Rule<a name="UnnecessaryGetter_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>Checks for explicit calls to getter/accessor methods which can, for the most part, be replaced by property access. A getter is defined as a method call that matches <tt>get[A-Z]</tt> but not <tt>getClass()</tt> or <tt>get[A-Z][A-Z]</tt> such as <tt>getURL()</tt>. Getters do not take method arguments.</p>
<p>These bits of code produce violations:</p>
<div>
<pre>    x.getProperty()
    x.getFirst()
    x.getFirstName()
    x.getA()
</pre></div>
<p>These bits of code do not:</p>
<div>
<pre>    x.property
    x.first
    x.firstName
    x.a
    x.getURL()
    x.getClass()
    x.getProperty('key')
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryGString">UnnecessaryGString</a> Rule<a name="UnnecessaryGString_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>String objects should be created with single quotes, and GString objects created with double quotes. Creating normal String objects with double quotes is confusing to readers.</p>
<p>Example of violations:</p>
<div>
<pre>    def a = &quot;I am a string&quot;     // violation

    // violation
    def b = &quot;&quot;&quot;
        I am a string
    &quot;&quot;&quot;

    def c = &quot;I am a ' string&quot;       // OK

    def d = &quot;&quot;&quot;I am a ' string&quot;&quot;&quot;   // OK

    def e = &quot;&quot;&quot;I am a ' string&quot;&quot;&quot;   // OK

    def f = &quot;I am a \$ string&quot;  // OK

    // OK
    def g = &quot;&quot;&quot;
        I am a \$ string
    &quot;&quot;&quot;

    // OK
    def h = &quot;&quot;&quot;
        I am a $string
    &quot;&quot;&quot;

    def i = 'i am a string'
    def j = '''i am a
        string
    '''
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryIfStatement">UnnecessaryIfStatement</a> Rule<a name="UnnecessaryIfStatement_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p>Checks for unnecessary <b>if</b> statements. The entire <b>if</b> statement, or at least the <i>if</i> or <i>else</i> block, are considered unnecessary for the four scenarios described below.</p>
<p>(1) When the <i>if</i> and <i>else</i> blocks contain only an explicit return of <tt>true</tt> and <tt>false</tt> constants. These cases can be replaced by a simple <i>return</i> statement. Examples of violations include:</p>
<div>
<pre>    if (someExpression)         // can be replaced by: return someExpression
        return true
    else
        return false

    if (someExpression) {       // can be replaced by: return !someExpression
        return false
    } else {
        return true
    }

    if (someExpression) {       // can be replaced by: return someExpression
        return Boolean.TRUE
    } else {
        return Boolean.FALSE
    }
</pre></div>
<p>(2) When the <tt>if</tt> statement is the last statement in a block and the <i>if</i> and <i>else</i> blocks are only <tt>true</tt> and <tt>false</tt> expressions. This is an <i>implicit</i> return of <tt>true</tt>/<tt>false</tt>. For example, the <tt>if</tt> statement in the following code can be replaced by <tt>someExpression</tt> or <tt>someExpression as boolean</tt>:</p>
<div>
<pre>    def myMethod() {
        doSomething()
        if (someExpression)
            true
        else false
    }
</pre></div>
<p>(3) When the second-to-last statement in a block is an <tt>if</tt> statement with no <tt>else</tt>, where the block contains a single <tt>return</tt> statement, and the last statement in the block is a <tt>return</tt> statement, and one <tt>return</tt> statement returns a <tt>true</tt> expression and the other returns a <tt>false</tt> expression. This check is disabled by setting <tt>checkLastStatementImplicitElse</tt> to <tt>false</tt>. For example, the <tt>if</tt> statement in the following code can be replaced by <tt>return expression1</tt>:</p>
<div>
<pre>    def myMethod() {
        doSomething()
        if (expression1) {
            return true
        }
        return false
    }
</pre></div>
<p>(4) When either the <i>if</i> block or <i>else</i> block of an <tt>if</tt> statement that is not the last statement in a block contain only a single constant or literal expression. For example, the <tt>if</tt> statement in the following code has no effect and can be removed:</p>
<div>
<pre>    def myMethod() {
        if (someExpression) { 123 }
        doSomething()
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryInstanceOfCheck">UnnecessaryInstanceOfCheck</a> Rule<a name="UnnecessaryInstanceOfCheck_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.15</i></p>
<p>This rule finds instanceof checks that cannot possibly evaluate to true. For instance, checking that <tt>(!variable instanceof String)</tt> will never be true because the result of a not expression is always a boolean.</p>
<p>Example of violations:</p>
<div>
<pre>    if (!variable instanceof String) { ... }    // always false
    def x = !variable instanceof String         // always false

    if (!variable instanceof Boolean) { ... }    // always true
    def x = !variable instanceof Boolean         // always true

    // this code is OK
    if (!(variable instanceof String)) { ... }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryInstantiationToGetClass">UnnecessaryInstantiationToGetClass</a> Rule<a name="UnnecessaryInstantiationToGetClass_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since in CodeNarc 0.12</i></p>
<p>Avoid instantiating an object just to call getClass() on it; use the .class public member instead.</p>
<div>
<pre>    public class Foo {
     // Replace this
     Class c = new String().getClass();

     // with this:
     Class c = String.class;
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryIntegerInstantiation">UnnecessaryIntegerInstantiation</a> Rule<a name="UnnecessaryIntegerInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>It is unnecessary to instantiate <tt>Integer</tt> objects. Instead just use the literal with the 'I' identifier to force the type, such as <tt>8I</tt> or <tt>42i</tt>.</p></div>
<div class="section">
<h3><a name="UnnecessaryLongInstantiation">UnnecessaryLongInstantiation</a> Rule<a name="UnnecessaryLongInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>It is unnecessary to instantiate <tt>Long</tt> objects. Instead just use the literal with the 'L' identifier to force the type, such as <tt>8L</tt> or <tt>42L</tt>.</p></div>
<div class="section">
<h3><a name="UnnecessaryModOne">UnnecessaryModOne</a> Rule<a name="UnnecessaryModOne_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>Any expression mod 1 (exp % 1) is guaranteed to always return zero. This code is probably an error, and should be either (exp &amp; 1) or (exp % 2).</p>
<p>Examples:</p>
<div>
<pre>    if (exp % 1) {}         // violation
    if (method() % 1) {}    // violation

    if (exp &amp; 1) {}     // ok
    if (exp % 2) {}     // ok
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryObjectReferences">UnnecessaryObjectReferences</a> Rule<a name="UnnecessaryObjectReferences_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>Violations are triggered when an excessive set of consecutive statements all reference the same variable. This can be made more readable by using a <tt>with</tt> or <tt>identity</tt> block. By default, 5 references are allowed. You can override this property using the <b>maxReferencesAllowed</b>&gt; property on the rule.</p>
<p>These two bits of code produce violations:</p>
<div>
<pre>    def p1 = new Person()
    p1.firstName = 'Hamlet'
    p1.lastName = &quot;D'Arcy&quot;
    p1.employer = 'Canoo'
    p1.street = 'Kirschgaraten 5'
    p1.city = 'Basel'
    p1.zipCode = '4051'

    def p2 = new Person()
    p2.setFirstName('Hamlet')
    p2.setLastName(&quot;D'Arcy&quot;)
    p2.setEmployer('Canoo')
    p2.setStreet('Kirschgaraten 5')
    p2.setCity('Basel')
    p2.setZipCode('4051')
</pre></div>
<p>However, these two bits of code do not because they use either a <tt>with</tt> or <tt>identity</tt> block.</p>
<div>
<pre>    def p1 = new Person().with {
        firstName = 'Hamlet'
        lastName = &quot;D'Arcy&quot;
        employer = 'Canoo'
        street = 'Kirschgaraten 5'
        city = 'Basel'
        zipCode = '4051'
    }

    def p2 = new Person().identity {
        firstName = 'Hamlet'
        lastName = &quot;D'Arcy&quot;
        employer = 'Canoo'
        street = 'Kirschgaraten 5'
        city = 'Basel'
        zipCode = '4051'
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryNullCheck">UnnecessaryNullCheck</a> Rule<a name="UnnecessaryNullCheck_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>Groovy contains the safe dereference operator. It can be used in boolean conditional statements to safely replace explicit <tt>x == null</tt> tests. Also, testing the 'this' or 'super' reference for null equality is pointless and can be removed.</p>
<p>Examples of violations:</p>
<div>
<pre>    if (obj != null &amp;&amp; obj.method()) { }

    if (obj != null &amp;&amp; obj.prop) { }

    // this is pointless and won't avoid NullPointerException
    if (obj.method() &amp;&amp; obj != null ) { }

    if (this == null) { }
    if (null == this) { }
    if (this != null) { }
    if (null != this) { }

    if (super == null) { }
    if (null == super) { }
    if (super != null) { }
    if (null != super) { }
</pre></div>
<p>Examples of acceptable code:</p>
<div>
<pre>    // null check it OK
    if (obj != null) { }

    // null safe dereference in if is OK
    if (obj?.method()) { }

    // null safe dereference in ternary is OK
    (obj?.prop &amp;&amp; obj?.prop2) ? x : y

    // obj is reused in a parameter list, so OK
    if (obj != null &amp;&amp; obj.method() &amp;&amp; isValid(obj)) { }

    // rule is not so complex yet...
    (obj != null &amp;&amp; obj.prop &amp;&amp; obj.method()) ? x : y
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryNullCheckBeforeInstanceOf">UnnecessaryNullCheckBeforeInstanceOf</a> Rule<a name="UnnecessaryNullCheckBeforeInstanceOf_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12</i></p>
<p>There is no need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.</p>
<p>Example:</p>
<div>
<pre>    if (x != null &amp;&amp; x instanceof MyClass) {
        // should drop the &quot;x != null&quot; check
    }

    if (x instanceof MyClass &amp;&amp; x != null) {
        // should drop the &quot;x != null&quot; check
    }

    // should drop the &quot;x != null&quot; check
    (x != null &amp;&amp; x instanceof MyClass) ? foo : bar

    if (x != null &amp;&amp; x instanceof MyClass &amp;&amp; x.isValid()) {
        // this is OK and causes no violation because the x.isValid() requires a non null reference
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryOverridingMethod">UnnecessaryOverridingMethod</a> Rule<a name="UnnecessaryOverridingMethod_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.11</i></p>
<p>Checks for an overriding method that merely calls the same method defined in a superclass. Remove it.</p></div>
<div class="section">
<h3><a name="UnnecessaryPackageReference">UnnecessaryPackageReference</a> Rule<a name="UnnecessaryPackageReference_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.14</i></p>
<p>Checks for explicit package reference for classes that Groovy imports by default, such as <tt>java.lang.String</tt>, <tt>java.util.Map</tt> and <tt>groovy.lang.Closure</tt>, as well as classes that were explicitly imported.</p>
<p>You do not need to specify the package for any classes from <i>java.lang</i>, <i>java.util</i>, <i>java.io</i>, <i>java.net</i>, <i>groovy.lang</i> and <i>groovy.util</i>, as well as the classes <i>java.math.BigDecimal</i> and <i>java.math.BigInteger</i>.</p>
<p>Examples of violations include:</p>
<div>
<pre>    // Field types
    class MyClass {
        java.math.BigDecimal amount = 42.10                     // violation
    }

    // Within expressions
    if (value.class == java.math.BigInteger) { }                // violation
    println &quot;isClosure=${v instanceof groovy.lang.Closure}&quot;     // violation
    def p = java.lang.Runtime.availableProcessors()             // violation

    // Constructor calls
    def url = new java.net.URL('http://abc@example.com')        // violation

    // Variable types
    void doSomething() {
        java.math.BigInteger maxValue = 0                       // violation
        java.net.URI uri                                        // violation
    }

    // Method return types
    java.io.Reader getReader() { }                              // violation
    groovy.util.AntBuilder getAntBuilder() { }                  // violation

    // Method parameter types
    void writeCount(java.io.Writer writer, int count) { }       // violation
    void init(String name, groovy.lang.Binding binding) { }     // violation

    // Closure parameter types
    def writeCount = { java.io.Writer writer, int count -&gt; }    // violation

    // Extends and implements
    class MyHashMap extends java.util.HashMap { }               // violation
    class MyList implements java.util.List { }                  // violation

    // Explicitly imported classes
    import javax.servlet.http.Cookie
    import javax.sql.DataSource

    class MyClass {
        void doStuff(javax.servlet.http.Cookie cookie) {        // violation
            def dataSource = [:] as javax.sql.DataSource        // violation
        }
    }
</pre></div>
<p>Known limitations:</p>
<ul>
<li>Does not catch class declarations that explicitly extend <tt>java.lang.Object</tt>. For instance, <tt>class MyClass extends java.lang.Object <a name="a"> </a></tt>. Just don't do that, okay?</li>
<li>Does not catch class declarations that explicitly extend <tt>groovy.lang.Script</tt>. For instance, <tt>class MyScript extends groovy.lang.Script<a name="a"> </a></tt>. Don't do that, either!</li>
<li>Does not catch unnecessary package references if they are the types of anonymous inner class definitions, for older versions of Groovy (<i> 1.7.10?). For instance, &lt;&lt;&lt;def runnable = new java.lang.Runnable() <a name="a..."> ... </a></i>&gt;&gt;.</li></ul></div>
<div class="section">
<h3><a name="UnnecessaryParenthesesForMethodCallWithClosure">UnnecessaryParenthesesForMethodCallWithClosure</a> Rule<a name="UnnecessaryParenthesesForMethodCallWithClosure_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.14</i></p>
<p>If a method is called and the only parameter to that method is an inline closure then the parentheses of the method call can be omitted.</p>
<p>Example of violations:</p>
<div>
<pre>    [1,2,3].each() { println it }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryPublicModifier">UnnecessaryPublicModifier</a> Rule<a name="UnnecessaryPublicModifier_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>The 'public' modifier is not required on methods, constructors or classes.</p>
<p>Example of violations:</p>
<div>
<pre>    // violation on class
    public class MyClass {
        // violation on constructor
        public MyClass() {}

        // violation on method
        public void myMethod() {}
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryReturnKeyword">UnnecessaryReturnKeyword</a> Rule<a name="UnnecessaryReturnKeyword_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.11</i></p>
<p>In Groovy, the <tt>return</tt> keyword is often optional. If a statement is the last line in a method or closure then you do not need to have the <tt>return</tt> keyword.</p></div>
<div class="section">
<h3><a name="UnnecessarySafeNavigationOperator">UnnecessarySafeNavigationOperator</a> Rule<a name="UnnecessarySafeNavigationOperator_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.22</i></p>
<p>Check for the <i>safe navigation</i> operator (<tt>?.</tt>) applied to constants and literals, or <tt>this</tt> or <tt>super</tt>, or constructor calls, all of which can never be null.</p>
<p>Example of violations:</p>
<div>
<pre>    def myMethod() {
        &quot;abc&quot;?.bytes            // violation
        [1,2]?.getSize()        // violation
        [abc:123]?.name         // violation
        [:]?.toString()         // violation
        123?.class              // violation
        123.45?.getClass()      // violation
        Boolean.FALSE?.class    // violation
        Boolean.TRUE?.class     // violation
        this?.class             // violation
        super?.getClass()       // violation
        new Long(100)?.class    // violation
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessarySelfAssignment">UnnecessarySelfAssignment</a> Rule<a name="UnnecessarySelfAssignment_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>Method contains a pointless self-assignment to a variable or property. Either the code is pointless or the equals()/get() method has been overridden to have a side effect, which is a terrible way to code getters and violates the contract of equals().</p>
<p>Examples:</p>
<div>
<pre>    x = x               // violation
    def method(y) {
        y = y           // violation
    }
    a.b.c = a.b.c       // violation

    x = y               // acceptable
    a.b = a.zz          // acceptable
    a.b = a().b         // acceptable
</pre></div></div>
<div class="section">
<h3><a name="UnnecessarySemicolon">UnnecessarySemicolon</a> Rule<a name="UnnecessarySemicolon_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>Semicolons as line terminators are not required in Groovy: remove them. Do not use a semicolon as a replacement for empty braces on for and while loops; this is a confusing practice.</p>
<p>The rule contains a String property called 'excludePattern'. Any source code line matching this pattern will not trigger a violation. The default value is '\s?\*.*|/\*.*|.*//.*|.*\*/.*' This is to filter out comments. Any source line that even looks like it is a comment is ignored.</p>
<p>\s?*.* == whitespace plus star character plus anything /*.* == any line that contains the /* sequence .*//.* == any line that contains the // sequence .**/.* == any line that contains the */ sequence</p>
<p>Example of violations:</p>
<div>
<pre>    package my.company.server;  // violation

    import java.lang.String;    // violation

    println(value) ;             // violation

    for (def x : list);         // violation

    // this code is OK
    println(value); println (otherValue)
</pre></div></div>
<div class="section">
<h3><a name="UnnecessarySubstring">UnnecessarySubstring</a> Rule<a name="UnnecessarySubstring_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.15</i></p>
<p>This rule finds usages of <tt>String.substring(int)</tt> and <tt>String.substring(int, int)</tt> that can be replaced by use of the subscript operator. For instance, <tt>var.substring(5)</tt> can be replaced with <tt>var[5..-1]</tt>.</p>
<p>Note that the String.substring(beginIndex,endIndex) method specifies a range of beginIndex..endIndex-1, while Groovy's String subscript specifies an inclusive range. So, <tt>&quot;123456&quot;.substring(1, 5)</tt> is equivalent to <tt>&quot;123456&quot;[1..4]</tt>.</p>
<p>Example of violations:</p>
<div>
<pre>    myVar.substring(5)          // can use myVar[5..-1] instead
    myVar.substring(1, 5)       // can use myVar[1..4] instead
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryStringInstantiation">UnnecessaryStringInstantiation</a> Rule<a name="UnnecessaryStringInstantiation_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.12 (formerly StringInstantiation Rule in the &quot;basic&quot; rule set)</i></p>
<p>Checks for direct call to the <tt>String</tt> constructor that accepts a <tt>String</tt> literal. In almost all cases, this is unnecessary. Use a <tt>String</tt> literal (e.g., &quot;...&quot;) instead of calling the corresponding <tt>String</tt> constructor (<tt>new String(&quot;..&quot;)</tt>) directly.</p>
<p>Here is an example of code that produces a violation:</p>
<div>
<pre>    def s = new String('abc')
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryTernaryExpression">UnnecessaryTernaryExpression</a> Rule<a name="UnnecessaryTernaryExpression_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p>Checks for ternary expressions where the conditional expression always evaluates to a boolean and the <i>true</i> and <i>false</i> expressions are merely returning <tt>true</tt> and <tt>false</tt> constants. These cases can be replaced by a simple boolean expression. Examples of violations include:</p>
<div>
<pre>    x==99 ? true : false                    // can be replaced by: x==99
    x &amp;&amp; y ? true : false                   // can be replaced by: x &amp;&amp; y
    x||y ? false : true                     // can be replaced by: !(x||y)
    x &gt;= 1 ? true: false                    // can be replaced by: x &gt;= 1
    x &lt; 99 ? Boolean.TRUE : Boolean.FALSE   // can be replaced by: x &lt; 99
    !x ? true : false                       // can be replaced by: !x
</pre></div>
<p>The rule also checks for ternary expressions where the <i>true</i> and <i>false</i> expressions are the same constant or variable. Examples include:</p>
<div>
<pre>    x ? '123' : '123'              // can be replaced by: '123'
    x ? null : null                // can be replaced by: null
    x ? 23 : 23                    // can be replaced by: 23
    x ? MAX_VALUE : MAX_VALUE      // can be replaced by: MAX_VALUE
    ready ? minValue : minValue    // can be replaced by: minValue
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryTransientModifier">UnnecessaryTransientModifier</a> Rule<a name="UnnecessaryTransientModifier_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>New in CodeNarc 0.13</i></p>
<p>The field is marked as transient, but the class isn't Serializable, so marking it as transient has no effect. This may be leftover marking from a previous version of the code in which the class was transient, or it may indicate a misunderstanding of how serialization works.</p>
<p>Some Java frameworks change the semantics of the transient keyword. For instance, when using Terracotta the transient keyword may have slightly different semantics. You may need to turn this rule off depending on which Java frameworks are in use.</p>
<p>Examples:</p>
<div>
<pre>    class MyClass {
        // class not serializable, violation occurs
        transient String property
    }

    class MySerializableClass implements Serializable {
        // OK, class is serializable
        transient String property
    }
</pre></div></div>
<div class="section">
<h3><a name="UnnecessaryToString">UnnecessaryToString</a> Rule<a name="UnnecessaryToString_Rule"></a></h3><!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<p><i>Since CodeNarc 0.21</i></p>
<p>Checks for unnecessary calls to <tt>toString()</tt>. This includes:</p>
<ul>
<li>Calls to <tt>toString()</tt> on a String literal or expression</li>
<li>Calls to <tt>toString()</tt> for the value assigned to a <tt>String</tt> field or variable (if <i>checkAssignments</i> is <tt>true</tt>).</li></ul>
<table border="1" class="bodyTable">
<tr class="a">
<td align="left"><b>Property</b></td>
<td align="left"><b>Description</b></td>
<td align="left"><b>Default Value</b></td></tr>
<tr class="b">
<td align="left">checkAssignments</td>
<td align="left">If <tt>true</tt>, then check for calls to <tt>toString()</tt> for the value assigned to a <tt>String</tt> field or variable.</td>
<td align="left"><tt>true</tt></td></tr></table>
<p>Example of violations:</p>
<div>
<pre>    def name = &quot;Joe&quot;.toString()                             // violation - string literal
    def groupId = ((String)row.get('GroupID')).toString()   // violation - string expression

    class MyClass {
        String name = nameNode.toString()           // violation - field
        String code = account.getCode().toString()  // violation - field

        void run() {
            String name = nameNode.toString()       // violation - variable
            String id = account.id.toString()       // violation - variable
        }
    }
</pre></div></div></div>
      </div>
    </div>
    <div class="clear">
      <hr/>
    </div>
    <div id="footer">
      <div class="xright">
              Copyright &#169;                   2015.
          All Rights Reserved.      
                    
                  </div>
      <div class="clear">
        <hr/>
      </div>
    </div>
  </body>
</html>