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 3.x ==
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 In recent versions of Eclipse (>3.3) there is the possibility to configure Eclipse to automatically format a file when saving it. To do this, open //Window > Preferences//, select //Java > Editor > Save Actions// and enable //Perform the selected actions on save// and //Format source code//.
25
26 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]].
27
28 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.
29
30 To generate a javadoc, press ##Meta+Shift+J## while on the element you want to document.
31
32 == IntelliJ IDEA ==
33
34 * Set up IntelliJ IDEA code styles:
35 * 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]].
36 * Go to IntelliJ's preferences and to ##Editor > Code Style## and select ##Import Scheme > IntelliJ IDEA Code Style XML ## as shown on(((
37 {{image reference="intellij-idea-import-styles.png" width="350px"/}}
38 )))
39 * Set up File Templates (used when creating a new Java class, Interface, etc):(((
40 Download [[idea-fileTemplates-xwiki.tar.gz>>attach:idea-fileTemplates-xwiki.tar.gz]].
41
42 Close IntelliJ IDEA. Ungzip and untar the file in the following location (or copy unzipped "fileTemplates" directory in the following location):
43
44 * For Mac: in ##~~/Library/Preferences/IntelliJIdeaXX/##
45 * For Linux: in ##/.IntelliJIdeaXX/config.##
46 * For Windows: in ##C:\Users\username\.<IDEA VERSION>\config\##.
47 )))
48 * If codestyle is not imported automatically, go to ##Other Settings > Default Settings > Java codestyle > Set from (XML) > select file downloaded above.##
49 * Restart Intellij IDEA.
50
51 = Interface best practices =
52
53 == Do not use 'public' in interfaces ==
54
55 Public is always implied in interfaces. Do not write:
56
57 {{code}}
58 public interface Page
59 {
60 public String getParentSpaceKey();
61 }
62 {{/code}}
63
64 But instead, write
65
66 {{code}}
67 public interface Page
68 {
69 String getParentSpaceKey();
70 }
71 {{/code}}
72
73 == Make sure your code is backward compatible ==
74
75 When you add a new method to an interface, it needs to be backward compatible otherwise your build will fail with error:
76
77 {{error}}
78 Method was added to an Interface.
79 {{/error}}
80
81 To ensure backward compatibility, use ##default## and throw an Exception:
82
83 {{code}}
84 default MethodType myNewMethod()
85 {
86 throw new UnsupportedOperationException();
87 }
88 {{/code}}
89
90 = Javadoc Best Practices =
91
92 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.
93
94 == Write useful comments ==
95
96 Do not repeat the name of the method or any useless information. For example, if you have:
97
98 {{code language="java"}}
99 /**
100 * @return the id
101 */
102 public String getId()
103 {
104 return this.id;
105 }
106 {{/code}}
107
108 Instead, write:
109
110 {{code language="java"}}
111 /**
112 * @return the attachment id (the id is the filename of the XWikiAttachment object used to construct this Attachment object)
113 */
114 public String getId()
115 {
116 return this.id;
117 }
118 {{/code}}
119
120 == Do not duplicate Javadoc ==
121
122 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:
123
124 {{code language="java"}}
125 /**
126 * Do something blah blah.
127 */
128 public void doSomething()
129 {
130
131 [...]
132 {{/code}}
133
134 Instead, write either the following:
135
136 {{code language="java"}}
137 /**
138 * {@inheritDoc}
139 *
140 * <p>Optionally add here javadoc additional to the one inherited from the parent javadoc.</p>
141 */
142 @Override
143 public void doSomething()
144 {
145 [...]
146 {{/code}}
147
148 or (it you don't have anything else to add in the javadoc):
149
150 {{code language="java"}}
151 @Override
152 public void doSomething()
153 {
154 [...]
155 {{/code}}
156
157 {{warning}}
158 Don't forget the {{{@Override}}} annotation!
159 {{/warning}}
160
161 == Do not duplicate method comments with parameters comments ==
162
163 Instead of writing:
164
165 {{code language="java"}}
166 /**
167 * Returns the key of the space to which this page belongs to.
168 *
169 * @return - Parent space's key as String.
170 */
171 public String getParentSpaceKey();
172 {{/code}}
173
174 Write:
175
176 {{code language="java"}}
177 /**
178 * @return the key of the space to which this page belongs to. For example "Main".
179 */
180 public String getParentSpaceKey();
181 {{/code}}
182
183 == Use version and since javadoc tags ==
184
185 For example:
186
187 {{code language="java"}}
188 /**
189 * Something, blah blah...
190 *
191 * @version $Id$
192 * @since 1.6M1
193 */
194 {{/code}}
195
196 {{warning}}
197 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.
198 {{/warning}}
199
200 == Use one @since per version ==
201
202 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.
203
204 For example:
205
206 {{code language="java"}}
207 [...]
208 * @since 7.4.5
209 * @since 8.2.2
210 * @since 8.3M2
211 */
212 {{/code}}
213
214 (and not {{code language="java"}}@since 7.4.5, 8.2.2, 8.3M2{{/code}})
215
216 == Use the right format for examples ==
217
218 If you need to use example and have what you past be not modified, use the ##{@code}}## construct, as in:
219
220 {{code language="java"}}
221 * <pre>{@code
222 * <plugin>
223 * <groupId>org.xwiki.platform</groupId>
224 * <artifactId>xwiki-platform-tool-provision-plugin</artifactId>
225 * <version>...version...</version>
226 * <configuration>
227 * <username>Admin</username>
228 * <password>admin</password>
229 * <extensionIds>
230 * <extensionId>
231 * <id>org.xwiki.contrib.markdown:syntax-markdown-markdown12</id>
232 * <version>8.5.1</version>
233 * </extensionId>
234 * </extensionIds>
235 * </configuration>
236 * <executions>
237 * <execution>
238 * <id>install</id>
239 * <goals>
240 * <goal>install</goal>
241 * </goals>
242 * </execution>
243 * </executions>
244 * </plugin>
245 * }</pre>
246 {{/code}}
247
248 {{error}}
249 There's currently a [[bug in Checkstyle>>https://github.com/checkstyle/checkstyle/issues/5482]] that forces us to escape the ##<## as in:
250
251 {{code language="none"}}
252 * <pre><code>
253 * &#60;plugin&#62;
254 * &#60;groupId&#62;org.xwiki.platform&#60;/groupId&#62;
255 * &#60;artifactId&#62;xwiki-platform-tool-provision-plugin&#60;/artifactId&#62;
256 * &#60;version&#62;...version...&#60;/version&#62;
257 * &#60;configuration&#62;
258 * &#60;username&#62;Admin&#60;/username&#62;
259 * &#60;password&#62;admin&#60;/password&#62;
260 * &#60;extensionIds&#62;
261 * &#60;extensionId&#62;
262 * &#60;id&#62;org.xwiki.contrib.markdown:syntax-markdown-markdown12&#60;/id&#62;
263 * &#60;version&#62;8.5.1&#60;/version&#62;
264 * &#60;/extensionId&#62;
265 * &#60;/extensionIds&#62;
266 * &#60;/configuration&#62;
267 * &#60;executions&#62;
268 * &#60;execution&#62;
269 * &#60;id&#62;install&#60;/id&#62;
270 * &#60;goals&#62;
271 * &#60;goal&#62;install&#60;/goal&#62;
272 * &#60;/goals&#62;
273 * &#60;/execution&#62;
274 * &#60;/executions&#62;
275 * &#60;/plugin&#62;
276 * </code></pre>
277 {{/code}}
278 {{/error}}
279
280 = Trailing Whitespace =
281
282 Trailing whitespace is prohibited except for one case.
283 In empty lines in a javadoc comment, a single trailing space character is acceptable but not required.
284
285 {{code language="java"}}
286 /**
287 * The Constructor.
288 *
289 * $param something...
290 */
291 {{/code}}
292
293 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.
294
295 = Class/Interface names =
296
297 * Prefix class names with ##Abstract## for abstract classes
298 * Class names should start with an uppercase letter
299 * The interface name should be as short and expressive as possible with no technical prefix or suffix. For example "Parser".
300 ** 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).
301 * Classes implementing interfaces should extend the interface name by prefixing it with a characteristic of the implementation. For example "XWikiParser".
302 ** As a consequence implementation classes shouldn't be suffixed with "Impl", "Implementation", etc.
303 * Default implementation classes where there's only one implementation provided by XWiki should be prefixed with "Default". As in "DefaultParser".
304
305 = Members and fields names =
306
307 * All methods and fields names should be camelCase, starting with a lower letter (##someProperty##, ##getSomeProperty()##)
308 * The names should be understandable and short, avoiding abbreviations (##parentDocument## instead of ##pdoc##, for example)
309 * Constants should all be uppercase, with underscores as word separators, and no prefix letter (##WIKI_PAGE_CREATOR## instead of ##WIKIPAGECREATOR##)
310 * 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"##)
311
312 = Package names =
313
314 * All code that is not located in the oldcore module should use ##org.xwiki##.
315 * The package name for code using the component-based architecture must be of the format ##org.xwiki.(module name).*##. For example ##org.xwiki.rendering##.
316 * 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.##**
317 * [[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).
318
319 = Logging Best Practices =
320
321 * Use SLF4J. Specifically, if your code is in a Component it must get a Logger using the following construct:(((
322 {{code language="java"}}
323 import org.slf4j.Logger;
324 ...
325 @Inject
326 private Logger logger;
327 {{/code}}
328
329 If not inside a Component, a Logger can be retrieve through:
330
331 {{code language="java"}}
332 import org.slf4j.Logger;
333 ...
334 private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
335 {{/code}}
336 )))
337 * You should use the severity according to the following rules:
338 ** **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).
339 ** **debug**: Logs that are informational but that shouldn't be printed by default. Logging configuration needs to be updated to show these logs.
340 ** **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:(((
341 {{code language="java"}}
342 LOGGER.warn("Failed to determine if the index exists: [{}]. Trying to recreate the index..", e.getMessage());
343 {{/code}}
344
345 write instead:
346
347 {{code language="java"}}
348 LOGGER.warn("Failed to determine if the index exists: [{}]. Trying to recreate the index..", ExceptionUtils.getRootCauseMessage(e));
349 {{/code}}
350
351 These logs are shown by default (with the default XWiki logging configuration).
352 )))
353 ** **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).
354 * 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:(((
355 {{code language="java"}}
356 this.logger.debug("Test message with [{}] and [{}]", param1, param2);
357 {{/code}}
358
359 Do NOT write:
360
361 {{code language="java"}}
362 this.logger.debug("Test message with [" + param1 + "] and [" + param2 + "]", param1, param2);
363 {{/code}}
364 )))
365 * Always log as much information as possible to make it easier to understand what’s going on.
366 * 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.
367
368 = Imports =
369
370 * imports should be added individually for each class/interface
371 * individual imports should be grouped together and separated by blank lines following this model:(((
372 {{code language="java"}}
373 import java.*
374
375 import javax.*
376
377 import org.*
378
379 import com.*
380
381 import <any other imports>
382
383 import static <any static imports>
384 {{/code}}
385 )))
386 * 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]].
387
388 = Equals/HashCode and ToString implementations =
389
390 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]].
391
392 For example:
393
394 {{code language="java"}}
395 ...
396 @Override
397 public boolean equals(Object object)
398 {
399 if (object == null) {
400 return false;
401 }
402 if (object == this) {
403 return true;
404 }
405 if (object.getClass() != getClass()) {
406 return false;
407 }
408 WikiBotListenerData rhs = (WikiBotListenerData) object;
409 return new EqualsBuilder()
410 .appendSuper(super.equals(object))
411 .append(getReference(), rhs.getReference())
412 .isEquals();
413 }
414
415 @Override
416 public int hashCode()
417 {
418 return new HashCodeBuilder(3, 17)
419 .appendSuper(super.hashCode())
420 .append(getReference())
421 .toHashCode();
422 }
423 ...
424 {{/code}}
425
426 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).
427
428 For example:
429
430 {{code language="java"}}
431 ...
432 @Override
433 public String toString()
434 {
435 ToStringBuilder builder = new XWikiToStringBuilder(this);
436 builder = builder.append("Typed", isTyped())
437 .append("Type", getType().getScheme());
438
439 if (getReference() != null) {
440 builder = builder.append("Reference", getReference());
441 }
442
443 if (!getBaseReferences().isEmpty()) {
444 builder = builder.append("Base References", getBaseReferences());
445 }
446
447 Map<String, String> params = getParameters();
448 if (!params.isEmpty()) {
449 builder = builder.append("Parameters", params);
450 }
451
452 return builder.toString();
453 }
454 ...
455 {{/code}}
456
457 This example would generate the following:
458
459 {{code language="java"}}
460 ...
461 ResourceReference reference = new ResourceReference("reference", ResourceType.DOCUMENT);
462 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference]", reference.toString());
463
464 reference.addBaseReference("baseref1");
465 reference.addBaseReference("baseref2");
466 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference] "
467 + "Base References = [[baseref1], [baseref2]]", reference.toString());
468
469 reference.setParameter("name1", "value1");
470 reference.setParameter("name2", "value2");
471 Assert.assertEquals("Typed = [true] Type = [doc] Reference = [reference] "
472 + "Base References = [[baseref1], [baseref2]] "
473 + "Parameters = [[name1] = [value1], [name2] = [value2]]", reference.toString());
474 ...
475 {{/code}}
476
477 = Test classes =
478
479 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.
480
481 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).
482
483 = Script Services =
484
485 See [[Best practices for the Script Module>>extensions:Extension.Script Module#HBestPractices]].

Get Connected