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

Get Connected