Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
4
5 The XWiki project is following a specific coding style for Java code. We're using [[Checkstyle>>http://checkstyle.sourceforge.net/]] ([[checkstyle.xml>>https://raw.github.com/xwiki/xwiki-commons/master/xwiki-commons-tools/xwiki-commons-tool-verification-resources/src/main/resources/checkstyle.xml]]) to ensure compliance of the code. Our build (the Maven one) is configured to fail on violations. This is part of the [[automated checks>>https://dev.xwiki.org/xwiki/bin/view/Community/Building/#HAutomaticChecks]], see there for ways to skip if necessary at times. However the decision to follow this code style and enforce it was only made long after the beginning of the project and not all the code base has been moved to this new code style. Hence:
6
7 * We're only enforcing the code style in the code that has been moved to the new code style. The checked files are defined in //xwiki/core/pom.xml// (bottom of file).
8 * We're asking new code to follow the new style and then once a Java file is compliant, to edit //xwiki/core/pom.xml// and add it there so that we cannot regress...
9
10 For examples of "clean" class see the following example and its unit tests:
11
12 * DefaultObservationManager.java ([[main sources>>https://github.com/xwiki/xwiki-commons/blob/master/xwiki-commons-core/xwiki-commons-observation/xwiki-commons-observation-local/src/main/java/org/xwiki/observation/internal/DefaultObservationManager.java]]|[[tests>>https://github.com/xwiki/xwiki-commons/blob/master/xwiki-commons-core/xwiki-commons-observation/xwiki-commons-observation-local/src/test/java/org/xwiki/observation/ObservationManagerTest.java]])
13
14 = Configuring your IDE to use the XWiki code style =
15
16 == Eclipse ==
17
18 Download [[codestyle-eclipse-java.xml>>https://raw.github.com/xwiki/xwiki-commons/master/xwiki-commons-tools/xwiki-commons-tool-verification-resources/src/main/resources/codestyle-eclipse-java.xml]].
19
20 After this, select //Window > Preferences//, and open up the configuration for //Java > Code Style > Code Formatter//. Click on the button labeled //Import...// and select the file you downloaded. Give the style a name, and click OK.
21
22 To reformat a file, press ##Ctrl+Shift+F## while inside that file. To format only a portion of the file, select it and press the same key combination.
23
24 Download [[codetemplates-eclipse.xml>>https://raw.github.com/xwiki/xwiki-commons/master/xwiki-commons-tools/xwiki-commons-tool-verification-resources/src/main/resources/codetemplates-eclipse.xml]].
25
26 After this, select //Window > Preferences//, and open up the configuration for //Java > Code Style > Code Templates//. Click on the button labeled //Import...// and select the file you downloaded. You can enable "Automatically add comments for new methods and types" if you want.
27
28 To generate a javadoc, press ##Meta+Shift+J## while on the element you want to document.
29
30 == IntelliJ IDEA ==
31
32 * Set up IntelliJ IDEA code styles:
33 * Download [[codestyle-idea.xml>>https://raw.github.com/xwiki/xwiki-commons/master/xwiki-commons-tools/xwiki-commons-tool-verification-resources/src/main/resources/codestyle-idea.xml]].
34 * Go to IntelliJ's ##File > Settings## and to ##Editor > Code Style## and select ##Import Scheme > IntelliJ IDEA Code Style XML## as shown on(((
35 {{image reference="intellij-idea-import-styles.png" width="350px"/}}
36 )))
37 * Set up File Templates (used when creating a new Java class, Interface, etc):(((
38 Download [[idea-fileTemplates-xwiki.tar.gz>>attach:idea-fileTemplates-xwiki.tar.gz]].
39
40 Close IntelliJ IDEA. Ungzip and untar the file in the [[configuration directory>>https://www.jetbrains.com/help/idea/directories-used-by-the-ide-to-store-settings-caches-plugins-and-logs.html#config-directory]] (or copy unzipped "fileTemplates" directory in the following location):
41
42 * For Mac: in ##~~/Library/Application Support/JetBrains/<IDEA VERSION>##
43 * For Linux: in ##/.config/JetBrains/<IDEA VERSION>##
44 * For Windows: in ##C:\Users\<username>\AppData\Roaming\JetBrains\<IDEA VERSION>##
45 )))
46 * If codestyle is not imported automatically, go to ##Other Settings > Default Settings > Java codestyle > Set from (XML) > select file downloaded above.##
47 * Restart Intellij IDEA.
48
49 = Interface best practices =
50
51 == Do not use 'public' in interfaces ==
52
53 Public is always implied in interfaces. Do not write:
54
55 {{code}}
56 public interface Page
57 {
58 public String getParentSpaceKey();
59 }
60 {{/code}}
61
62 But instead, write
63
64 {{code}}
65 public interface Page
66 {
67 String getParentSpaceKey();
68 }
69 {{/code}}
70
71 == Make sure your code is backward compatible ==
72
73 When you add a new method to an interface, it needs to be backward compatible otherwise your build will fail with error:
74
75 {{error}}
76 Method was added to an Interface.
77 {{/error}}
78
79 To ensure backward compatibility, use ##default## and throw an Exception:
80
81 {{code}}
82 default MethodType myNewMethod()
83 {
84 throw new UnsupportedOperationException();
85 }
86 {{/code}}
87
88 = Javadoc Best Practices =
89
90 We are following the [[Oracle Javadoc coding conventions>>http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#styleguide]]. Please make sure you're familiar with them when you write javadoc.
91
92 == Write useful comments ==
93
94 Do not repeat the name of the method or any useless information. For example, if you have:
95
96 {{code language="java"}}
97 /**
98 * @return the id
99 */
100 public String getId()
101 {
102 return this.id;
103 }
104 {{/code}}
105
106 Instead, write:
107
108 {{code language="java"}}
109 /**
110 * @return the attachment id (the id is the filename of the XWikiAttachment object used to construct this Attachment object)
111 */
112 public String getId()
113 {
114 return this.id;
115 }
116 {{/code}}
117
118 == Do not duplicate Javadoc ==
119
120 If you inherit from an interface/class then you shouldn't copy the Javadoc from the super type. Instead you should reference it or add more fine-tuned explanations. For example if //getSomething()// is the implementation of a method defined in an inherited //Something// interface or parent class, you shouldn't write:
121
122 {{code language="java"}}
123 /**
124 * Do something blah blah.
125 */
126 public void doSomething()
127 {
128
129 [...]
130 {{/code}}
131
132 Instead, write either the following:
133
134 {{code language="java"}}
135 /**
136 * {@inheritDoc}
137 *
138 * <p>Optionally add here javadoc additional to the one inherited from the parent javadoc.</p>
139 */
140 @Override
141 public void doSomething()
142 {
143 [...]
144 {{/code}}
145
146 or (it you don't have anything else to add in the javadoc):
147
148 {{code language="java"}}
149 @Override
150 public void doSomething()
151 {
152 [...]
153 {{/code}}
154
155 {{warning}}
156 Don't forget the {{{@Override}}} annotation!
157 {{/warning}}
158
159 == Do not duplicate method comments with parameters comments ==
160
161 Instead of writing:
162
163 {{code language="java"}}
164 /**
165 * Returns the key of the space to which this page belongs to.
166 *
167 * @return - Parent space's key as String.
168 */
169 public String getParentSpaceKey();
170 {{/code}}
171
172 Write:
173
174 {{code language="java"}}
175 /**
176 * @return the key of the space to which this page belongs to. For example "Main".
177 */
178 public String getParentSpaceKey();
179 {{/code}}
180
181 == Use version and since javadoc tags ==
182
183 For example:
184
185 {{code language="java"}}
186 /**
187 * Something, blah blah...
188 *
189 * @version $Id$
190 * @since 1.6M1
191 */
192 {{/code}}
193
194 {{warning}}
195 Do not use author javadoc tags! We don't have code ownership in XWiki. Everyone can modify any portion of code and all committers support all code.
196 {{/warning}}
197
198 == Use one @since per version ==
199
200 When introducing a class or a new method on several branches, multiple {{code language="java"}}@since{{/code}} annotations must be used to mention the different versions in which this element has been added.
201
202 For example:
203
204 {{code language="java"}}
205 [...]
206 * @since 7.4.5
207 * @since 8.2.2
208 * @since 8.3M2
209 */
210 {{/code}}
211
212 (and not {{code language="java"}}@since 7.4.5, 8.2.2, 8.3M2{{/code}})
213
214 == Use the right format for examples ==
215
216 If you need to use example and have what you past be not modified, use the ##{@code}}## construct, as in:
217
218 {{code language="java"}}
219 * <pre>{@code
220 * <plugin>
221 * <groupId>org.xwiki.platform</groupId>
222 * <artifactId>xwiki-platform-tool-provision-plugin</artifactId>
223 * <version>...version...</version>
224 * <configuration>
225 * <username>Admin</username>
226 * <password>admin</password>
227 * <extensionIds>
228 * <extensionId>
229 * <id>org.xwiki.contrib.markdown:syntax-markdown-markdown12</id>
230 * <version>8.5.1</version>
231 * </extensionId>
232 * </extensionIds>
233 * </configuration>
234 * <executions>
235 * <execution>
236 * <id>install</id>
237 * <goals>
238 * <goal>install</goal>
239 * </goals>
240 * </execution>
241 * </executions>
242 * </plugin>
243 * }</pre>
244 {{/code}}
245
246 {{error}}
247 There's currently a [[bug in Checkstyle>>https://github.com/checkstyle/checkstyle/issues/5482]] that forces us to escape the ##<## as in:
248
249 {{code language="none"}}
250 * <pre><code>
251 * &#60;plugin&#62;
252 * &#60;groupId&#62;org.xwiki.platform&#60;/groupId&#62;
253 * &#60;artifactId&#62;xwiki-platform-tool-provision-plugin&#60;/artifactId&#62;
254 * &#60;version&#62;...version...&#60;/version&#62;
255 * &#60;configuration&#62;
256 * &#60;username&#62;Admin&#60;/username&#62;
257 * &#60;password&#62;admin&#60;/password&#62;
258 * &#60;extensionIds&#62;
259 * &#60;extensionId&#62;
260 * &#60;id&#62;org.xwiki.contrib.markdown:syntax-markdown-markdown12&#60;/id&#62;
261 * &#60;version&#62;8.5.1&#60;/version&#62;
262 * &#60;/extensionId&#62;
263 * &#60;/extensionIds&#62;
264 * &#60;/configuration&#62;
265 * &#60;executions&#62;
266 * &#60;execution&#62;
267 * &#60;id&#62;install&#60;/id&#62;
268 * &#60;goals&#62;
269 * &#60;goal&#62;install&#60;/goal&#62;
270 * &#60;/goals&#62;
271 * &#60;/execution&#62;
272 * &#60;/executions&#62;
273 * &#60;/plugin&#62;
274 * </code></pre>
275 {{/code}}
276 {{/error}}
277
278 = Trailing Whitespace =
279
280 Trailing whitespace is prohibited except for one case.
281 In empty lines in a javadoc comment, a single trailing space character is acceptable but not required.
282
283 {{code language="java"}}
284 /**
285 * The Constructor.
286 *
287 * $param something...
288 */
289 {{/code}}
290
291 The trailing whitespace in the center line in that comment is permissible. See [[this proposal>>http://lists.xwiki.org/pipermail/devs/2010-October/020439.html]] for more information.
292
293 = Class/Interface names =
294
295 * Prefix class names with ##Abstract## for abstract classes
296 * Class names should start with an uppercase letter
297 * The interface name should be as short and expressive as possible with no technical prefix or suffix. For example "Parser".
298 ** As a consequence interfaces shouldn't be prefixed with "I" (as in "IParser") or suffixed with "Interface" (as in "ParserInterface"), nor suffixed with "IF" (as in "ParserIF).
299 * Classes implementing interfaces should extend the interface name by prefixing it with a characteristic of the implementation. For example "XWikiParser".
300 ** As a consequence implementation classes shouldn't be suffixed with "Impl", "Implementation", etc.
301 * Default implementation classes where there's only one implementation provided by XWiki should be prefixed with "Default". As in "DefaultParser".
302
303 = Members and fields names =
304
305 * All methods and fields names should be camelCase, starting with a lower letter (##someProperty##, ##getSomeProperty()##)
306 * The names should be understandable and short, avoiding abbreviations (##parentDocument## instead of ##pdoc##, for example)
307 * Constants should all be uppercase, with underscores as word separators, and no prefix letter (##WIKI_PAGE_CREATOR## instead of ##WIKIPAGECREATOR##)
308 * Constants should be ##public/private static final## in classes (##public static final String CONTEXT_KEY = "theKey"##) and without any modifiers in interfaces, since ##public##, ##static## and ##final## are implied and enforced (##String PREFERENCES_DOCUMENT_NAME = "XWiki.XWikiPreferences"##)
309
310 = Package names =
311
312 * All code that is not located in the oldcore module should use ##org.xwiki##.
313 * The package name for code using the component-based architecture must be of the format ##org.xwiki.(module name).*##. For example ##org.xwiki.rendering##.
314 * Non user-public code must be located in an ##internal## package just after the module name. For example: ##org.xwiki.rendering.internal.parser.##**. General rule is ##org.xwiki.(module name).internal.##**
315 * [[Script Services>>extensions:Extension.Script Module]] component implementations should be located in a ##script## package and in a **non-internal package**. This is because they are considered API and we wish to have our backward-compatibility tool report any breakage (and also so that they are included in the generated Javadoc).
316
317 = Logging Best Practices =
318
319 * Use SLF4J. Specifically, if your code is in a Component it must get a Logger using the following construct:(((
320 {{code language="java"}}
321 import org.slf4j.Logger;
322 ...
323 @Inject
324 private Logger logger;
325 {{/code}}
326
327 If not inside a Component, a Logger can be retrieve through:
328
329 {{code language="java"}}
330 import org.slf4j.Logger;
331 ...
332 private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
333 {{/code}}
334 )))
335 * You should use the severity according to the following rules:
336 ** **info**: To be used when it’s absolutely necessary for the user to see the message in the logs. Usually only used at startup and we want to limit what the user sees to the absolute necessary to avoid swamping him. These logs are shown by default (with the default XWiki logging configuration).
337 ** **debug**: Logs that are informational but that shouldn't be printed by default. Logging configuration needs to be updated to show these logs.
338 ** **warning**: To be used when an error happens but it doesn’t compromise the stability and general working of an XWiki instance. A warning just shows the user that something has gone wrong and it should provide him with as much information as possible to solve the issue. Do not print a stack trace when you output a warning since stack traces fill the logs and should be reserved for errors. In the view of users stack traces are synonymous with errors. We want it to be easy for admins to visually check the log files and see important problems (i.e. errors). In order to display the root cause without displaying a full stack trace, use ##org.apache.commons.lang3.exception.ExceptionUtils##. Instead of writing:(((
339 {{code language="java"}}
340 LOGGER.warn("Failed to determine if the index exists: [{}]. Trying to recreate the index..", e.getMessage());
341 {{/code}}
342
343 write instead:
344
345 {{code language="java"}}
346 LOGGER.warn("Failed to determine if the index exists: [{}]. Trying to recreate the index..", ExceptionUtils.getRootCauseMessage(e));
347 {{/code}}
348
349 These logs are shown by default (with the default XWiki logging configuration).
350 )))
351 ** **error**: To be used when there’s an important problem that compromises the stability of the XWiki instance or that prevent an important system from working and that should not have happened. Always pass a stack trace when logging errors since it’s something that shouldn’t have happened an a developer will need to debug the problem to fix it. These logs are shown by default (with the default XWiki logging configuration).
352 * If you need to perform computations for passing parameters to the logging calls you should instead use the appropriate SLF4J signature [[to not incur performance penalty>>http://www.slf4j.org/faq.html#logging_performance]]. For example:(((
353 {{code language="java"}}
354 this.logger.debug("Test message with [{}] and [{}]", param1, param2);
355 {{/code}}
356
357 Do NOT write:
358
359 {{code language="java"}}
360 this.logger.debug("Test message with [" + param1 + "] and [" + param2 + "]", param1, param2);
361 {{/code}}
362 )))
363 * Always log as much information as possible to make it easier to understand what’s going on.
364 * Surround parameters with ##[]## in order to separate visually the text from the parameters and also clearly notice when leading/trailing spaces are located in parameters.
365
366 = Imports =
367
368 * imports should be added individually for each class/interface
369 * individual imports should be grouped together and separated by blank lines following this model:(((
370 {{code language="java"}}
371 import java.*
372
373 import javax.*
374
375 import org.*
376
377 import com.*
378
379 import <any other imports>
380
381 import static <any static imports>
382 {{/code}}
383 )))
384 * The above code style settings for IntelliJ IDEA will automatically follow these rules, so you usually do not have to take care (Be careful that the default configuration for IntelliJ IDEA is not appropriate). For Eclipse you should import [[eclipse.importorder>>https://github.com/xwiki/xwiki-commons/blob/master/xwiki-commons-tools/xwiki-commons-tool-verification-resources/src/main/resources/eclipse.importorder]].
385
386 = Equals/HashCode and ToString implementations =
387
388 We've decided to standardize on using Apache Commons Lang [[HashCodeBuilder>>http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html]], [[EqualsBuilder>>http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html]] and [[ToStringBuilder>>http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/builder/ToStringBuilder.html]].
389
390 For example:
391
392 {{code language="java"}}
393 ...
394 @Override
395 public boolean equals(Object object)
396 {
397 if (object == null) {
398 return false;
399 }
400 if (object == this) {
401 return true;
402 }
403 if (object.getClass() != getClass()) {
404 return false;
405 }
406 WikiBotListenerData rhs = (WikiBotListenerData) object;
407 return new EqualsBuilder()
408 .appendSuper(super.equals(object))
409 .append(getReference(), rhs.getReference())
410 .isEquals();
411 }
412
413 @Override
414 public int hashCode()
415 {
416 return new HashCodeBuilder(3, 17)
417 .appendSuper(super.hashCode())
418 .append(getReference())
419 .toHashCode();
420 }
421 ...
422 {{/code}}
423
424 XWiki provides a custom ##ToStringBuilder## implementation named ##XWikiToStringBuilder## that uses a custom XWiki's ##toString## style (see the [[Text Module>>extensions:Extension.Text Module]] for information).
425
426 For example:
427
428 {{code language="java"}}
429 ...
430 @Override
431 public String toString()
432 {
433 ToStringBuilder builder = new XWikiToStringBuilder(this);
434 builder = builder.append("Typed", isTyped())
435 .append("Type", getType().getScheme());
436
437 if (getReference() != null) {
438 builder = builder.append("Reference", getReference());
439 }
440
441 if (!getBaseReferences().isEmpty()) {
442 builder = builder.append("Base References", getBaseReferences());
443 }
444
445 Map<String, String> params = getParameters();
446 if (!params.isEmpty()) {
447 builder = builder.append("Parameters", params);
448 }
449
450 return builder.toString();
451 }
452 ...
453 {{/code}}
454
455 This example would generate the following:
456
457 {{code language="java"}}
458 ...
459 ResourceReference reference = new ResourceReference("reference", ResourceType.DOCUMENT);
460 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference]", reference.toString());
461
462 reference.addBaseReference("baseref1");
463 reference.addBaseReference("baseref2");
464 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference] "
465 + "Base References = [[baseref1], [baseref2]]", reference.toString());
466
467 reference.setParameter("name1", "value1");
468 reference.setParameter("name2", "value2");
469 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference] "
470 + "Base References = [[baseref1], [baseref2]] "
471 + "Parameters = [[name1] = [value1], [name2] = [value2]]", reference.toString());
472 ...
473 {{/code}}
474
475 = Test classes =
476
477 We often write sometimes complex tools in ##test## classes but those should never be used in ##main## code. While Maven accept it technically it's not the case of Eclipse for example.
478
479 If they really are needed then it's a sign that they should probably move to ##main## or that the test tool manipulating those classes should itself have its classes locate in ##test## (see xwiki-platform-test-page for an example for this use case).
480
481 = Script Services =
482
483 See [[Best practices for the Script Module>>extensions:Extension.Script Module#HBestPractices]].
484
485 = Deprecation =
486
487 {{version since="14.0RC1"}}
488 * Always use both the ##@Deprecated## annotation and the ##@deprecated## javadoc tag.
489 * In the ##@deprecated## javadoc tag, always specify WHY it’s deprecated and WHAT should be used instead.
490 * In the ##@Deprecated## annotation always use the ##since## parameter to specify WHEN it's been deprecated, and don't specify ##forRemoval## [[we don't break APIs in XWiki>>Community.DevelopmentPractices#HBackwardCompatibility]] and the default value is ##false##.
491
492
493 Example:
494
495 {{code language="java"}}
496 public class Worker
497 {
498 /**
499 * Calculate period between versions.
500 *
501 * @param machine the instance
502 * @return the computed time
503 * @deprecated This method is no longer acceptable to compute time between versions because... Use {@link Utils#calculatePeriod(Machine)} instead.
504 */
505 @Deprecated(since = "4.5")
506 public int calculate(Machine machine)
507 {
508 return machine.exportVersions().size() * 10;
509 }
510 }
511 {{/code}}
512 {{/version}}

Get Connected