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 Adding a new method to a public interface is a breaking change and your build will fail with error:
74
75 {{error}}
76 Method was added to an Interface.
77 {{/error}}
78
79 But it's possible to make a new interface method backward compatible by providing a default implementation (using the ##default## keyword as in):
80
81 {{code}}
82 @Unstable
83 default MethodType myNewMethod()
84 {
85 return myOtherMethod();
86 }
87 {{/code}}
88
89 = Javadoc Best Practices =
90
91 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.
92
93 == Write useful comments ==
94
95 Do not repeat the name of the method or any useless information. For example, if you have:
96
97 {{code language="java"}}
98 /**
99 * @return the id
100 */
101 public String getId()
102 {
103 return this.id;
104 }
105 {{/code}}
106
107 Instead, write:
108
109 {{code language="java"}}
110 /**
111 * @return the attachment id (the id is the filename of the XWikiAttachment object used to construct this Attachment object)
112 */
113 public String getId()
114 {
115 return this.id;
116 }
117 {{/code}}
118
119 == Do not duplicate Javadoc ==
120
121 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:
122
123 {{code language="java"}}
124 /**
125 * Do something blah blah.
126 */
127 public void doSomething()
128 {
129
130 [...]
131 {{/code}}
132
133 Instead, write either the following:
134
135 {{code language="java"}}
136 /**
137 * {@inheritDoc}
138 *
139 * <p>Optionally add here javadoc additional to the one inherited from the parent javadoc.</p>
140 */
141 @Override
142 public void doSomething()
143 {
144 [...]
145 {{/code}}
146
147 or (it you don't have anything else to add in the javadoc):
148
149 {{code language="java"}}
150 @Override
151 public void doSomething()
152 {
153 [...]
154 {{/code}}
155
156 {{warning}}
157 Don't forget the {{{@Override}}} annotation!
158 {{/warning}}
159
160 == Do not duplicate method comments with parameters comments ==
161
162 Instead of writing:
163
164 {{code language="java"}}
165 /**
166 * Returns the key of the space to which this page belongs to.
167 *
168 * @return - Parent space's key as String.
169 */
170 public String getParentSpaceKey();
171 {{/code}}
172
173 Write:
174
175 {{code language="java"}}
176 /**
177 * @return the key of the space to which this page belongs to. For example "Main".
178 */
179 public String getParentSpaceKey();
180 {{/code}}
181
182 == Use version and since javadoc tags ==
183
184 For example:
185
186 {{code language="java"}}
187 /**
188 * Something, blah blah...
189 *
190 * @version $Id$
191 * @since 1.6M1
192 */
193 {{/code}}
194
195 {{warning}}
196 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.
197 {{/warning}}
198
199 == Use one @since per version ==
200
201 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.
202
203 For example:
204
205 {{code language="java"}}
206 [...]
207 * @since 7.4.5
208 * @since 8.2.2
209 * @since 8.3M2
210 */
211 {{/code}}
212
213 (and not {{code language="java"}}@since 7.4.5, 8.2.2, 8.3M2{{/code}})
214
215 == Use the right format for examples ==
216
217 If you need to use example and have what you past be not modified, use the ##{@code}}## construct, as in:
218
219 {{code language="java"}}
220 * <pre>{@code
221 * <plugin>
222 * <groupId>org.xwiki.platform</groupId>
223 * <artifactId>xwiki-platform-tool-provision-plugin</artifactId>
224 * <version>...version...</version>
225 * <configuration>
226 * <username>Admin</username>
227 * <password>admin</password>
228 * <extensionIds>
229 * <extensionId>
230 * <id>org.xwiki.contrib.markdown:syntax-markdown-markdown12</id>
231 * <version>8.5.1</version>
232 * </extensionId>
233 * </extensionIds>
234 * </configuration>
235 * <executions>
236 * <execution>
237 * <id>install</id>
238 * <goals>
239 * <goal>install</goal>
240 * </goals>
241 * </execution>
242 * </executions>
243 * </plugin>
244 * }</pre>
245 {{/code}}
246
247 {{error}}
248 There's currently a [[bug in Checkstyle>>https://github.com/checkstyle/checkstyle/issues/5482]] that forces us to escape the ##<## as in:
249
250 {{code language="none"}}
251 * <pre><code>
252 * &#60;plugin&#62;
253 * &#60;groupId&#62;org.xwiki.platform&#60;/groupId&#62;
254 * &#60;artifactId&#62;xwiki-platform-tool-provision-plugin&#60;/artifactId&#62;
255 * &#60;version&#62;...version...&#60;/version&#62;
256 * &#60;configuration&#62;
257 * &#60;username&#62;Admin&#60;/username&#62;
258 * &#60;password&#62;admin&#60;/password&#62;
259 * &#60;extensionIds&#62;
260 * &#60;extensionId&#62;
261 * &#60;id&#62;org.xwiki.contrib.markdown:syntax-markdown-markdown12&#60;/id&#62;
262 * &#60;version&#62;8.5.1&#60;/version&#62;
263 * &#60;/extensionId&#62;
264 * &#60;/extensionIds&#62;
265 * &#60;/configuration&#62;
266 * &#60;executions&#62;
267 * &#60;execution&#62;
268 * &#60;id&#62;install&#60;/id&#62;
269 * &#60;goals&#62;
270 * &#60;goal&#62;install&#60;/goal&#62;
271 * &#60;/goals&#62;
272 * &#60;/execution&#62;
273 * &#60;/executions&#62;
274 * &#60;/plugin&#62;
275 * </code></pre>
276 {{/code}}
277 {{/error}}
278
279 = Trailing Whitespace =
280
281 Trailing whitespace is prohibited except for one case.
282 In empty lines in a javadoc comment, a single trailing space character is acceptable but not required.
283
284 {{code language="java"}}
285 /**
286 * The Constructor.
287 *
288 * $param something...
289 */
290 {{/code}}
291
292 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.
293
294 = Class/Interface names =
295
296 * Prefix class names with ##Abstract## for abstract classes
297 * Class names should start with an uppercase letter
298 * The interface name should be as short and expressive as possible with no technical prefix or suffix. For example "Parser".
299 ** 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).
300 * Classes implementing interfaces should extend the interface name by prefixing it with a characteristic of the implementation. For example "XWikiParser".
301 ** As a consequence implementation classes shouldn't be suffixed with "Impl", "Implementation", etc.
302 * Default implementation classes where there's only one implementation provided by XWiki should be prefixed with "Default". As in "DefaultParser".
303
304 = Members and fields names =
305
306 * All methods and fields names should be camelCase, starting with a lower letter (##someProperty##, ##getSomeProperty()##)
307 * The names should be understandable and short, avoiding abbreviations (##parentDocument## instead of ##pdoc##, for example)
308 * Constants should all be uppercase, with underscores as word separators, and no prefix letter (##WIKI_PAGE_CREATOR## instead of ##WIKIPAGECREATOR##)
309 * 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"##)
310
311 = Package names =
312
313 * All code that is not located in the oldcore module should use ##org.xwiki##.
314 * The package name for code using the component-based architecture must be of the format ##org.xwiki.(module name).*##. For example ##org.xwiki.rendering##.
315 * 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.##**
316 * [[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).
317
318 = Logging Best Practices =
319
320 * Use SLF4J. Specifically, if your code is in a Component it must get a Logger using the following construct:(((
321 {{code language="java"}}
322 import org.slf4j.Logger;
323 ...
324 @Inject
325 private Logger logger;
326 {{/code}}
327
328 If not inside a Component, a Logger can be retrieve through:
329
330 {{code language="java"}}
331 import org.slf4j.Logger;
332 ...
333 private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
334 {{/code}}
335 )))
336 * You should use the severity according to the following rules:
337 ** **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).
338 ** **debug**: Logs that are informational but that shouldn't be printed by default. Logging configuration needs to be updated to show these logs.
339 ** **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:(((
340 {{code language="java"}}
341 LOGGER.warn("Failed to determine if the index exists: [{}]. Trying to recreate the index..", e.getMessage());
342 {{/code}}
343
344 write instead:
345
346 {{code language="java"}}
347 LOGGER.warn("Failed to determine if the index exists: [{}]. Trying to recreate the index..", ExceptionUtils.getRootCauseMessage(e));
348 {{/code}}
349
350 These logs are shown by default (with the default XWiki logging configuration).
351 )))
352 ** **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).
353 * 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:(((
354 {{code language="java"}}
355 this.logger.debug("Test message with [{}] and [{}]", param1, param2);
356 {{/code}}
357
358 Do NOT write:
359
360 {{code language="java"}}
361 this.logger.debug("Test message with [" + param1 + "] and [" + param2 + "]", param1, param2);
362 {{/code}}
363 )))
364 * Always log as much information as possible to make it easier to understand what’s going on.
365 * 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.
366
367 = Imports =
368
369 * imports should be added individually for each class/interface
370 * individual imports should be grouped together and separated by blank lines following this model:(((
371 {{code language="java"}}
372 import java.*
373
374 import javax.*
375
376 import org.*
377
378 import com.*
379
380 import <any other imports>
381
382 import static <any static imports>
383 {{/code}}
384 )))
385 * 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]].
386
387 = Equals/HashCode and ToString implementations =
388
389 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]].
390
391 For example:
392
393 {{code language="java"}}
394 ...
395 @Override
396 public boolean equals(Object object)
397 {
398 if (object == null) {
399 return false;
400 }
401 if (object == this) {
402 return true;
403 }
404 if (object.getClass() != getClass()) {
405 return false;
406 }
407 WikiBotListenerData rhs = (WikiBotListenerData) object;
408 return new EqualsBuilder()
409 .appendSuper(super.equals(object))
410 .append(getReference(), rhs.getReference())
411 .isEquals();
412 }
413
414 @Override
415 public int hashCode()
416 {
417 return new HashCodeBuilder(3, 17)
418 .appendSuper(super.hashCode())
419 .append(getReference())
420 .toHashCode();
421 }
422 ...
423 {{/code}}
424
425 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).
426
427 For example:
428
429 {{code language="java"}}
430 ...
431 @Override
432 public String toString()
433 {
434 ToStringBuilder builder = new XWikiToStringBuilder(this);
435 builder = builder.append("Typed", isTyped())
436 .append("Type", getType().getScheme());
437
438 if (getReference() != null) {
439 builder = builder.append("Reference", getReference());
440 }
441
442 if (!getBaseReferences().isEmpty()) {
443 builder = builder.append("Base References", getBaseReferences());
444 }
445
446 Map<String, String> params = getParameters();
447 if (!params.isEmpty()) {
448 builder = builder.append("Parameters", params);
449 }
450
451 return builder.toString();
452 }
453 ...
454 {{/code}}
455
456 This example would generate the following:
457
458 {{code language="java"}}
459 ...
460 ResourceReference reference = new ResourceReference("reference", ResourceType.DOCUMENT);
461 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference]", reference.toString());
462
463 reference.addBaseReference("baseref1");
464 reference.addBaseReference("baseref2");
465 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference] "
466 + "Base References = [[baseref1], [baseref2]]", reference.toString());
467
468 reference.setParameter("name1", "value1");
469 reference.setParameter("name2", "value2");
470 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference] "
471 + "Base References = [[baseref1], [baseref2]] "
472 + "Parameters = [[name1] = [value1], [name2] = [value2]]", reference.toString());
473 ...
474 {{/code}}
475
476 = Test classes =
477
478 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.
479
480 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).
481
482 = Script Services =
483
484 See [[Best practices for the Script Module>>extensions:Extension.Script Module#HBestPractices]].
485
486 = Deprecation =
487
488 {{version since="14.0RC1"}}
489 * Always use both the ##@Deprecated## annotation and the ##@deprecated## javadoc tag.
490 * In the ##@deprecated## javadoc tag, always specify WHY it’s deprecated and WHAT should be used instead.
491 * 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##.
492
493
494 Example:
495
496 {{code language="java"}}
497 public class Worker
498 {
499 /**
500 * Calculate period between versions.
501 *
502 * @param machine the instance
503 * @return the computed time
504 * @deprecated This method is no longer acceptable to compute time between versions because... Use {@link Utils#calculatePeriod(Machine)} instead.
505 */
506 @Deprecated(since = "4.5")
507 public int calculate(Machine machine)
508 {
509 return machine.exportVersions().size() * 10;
510 }
511 }
512 {{/code}}
513 {{/version}}

Get Connected