Skip to content

Commit 838f350

Browse files
committed
Avoid using Optional#get
Fixes xdev-software/java-setup-template#8
1 parent 76cf223 commit 838f350

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

.config/pmd/java/ruleset.xml

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,36 @@
208208
<rule ref="category/java/security.xml"/>
209209

210210

211+
<rule name="AvoidOptionalGet"
212+
language="java"
213+
message="Avoid using Optional#get"
214+
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
215+
externalInfoUrl="https://stackoverflow.com/a/49159955">
216+
<description>
217+
`Optional#get` can be interpreted as a getter by developers, however this is not the case as it throws an exception when empty.
218+
219+
It should be replaced by
220+
* doing a mapping directly using `.map` or `.ifPresent`
221+
* using the preferred `.orElseThrow`, `.orElse` or `.or` methods
222+
223+
Java Developer Brian Goetz also writes regarding this topic:
224+
225+
> Java 8 was a huge improvement to the platform, but one of the few mistakes we made was the naming of `Optional.get()`, because the name just invites people to call it without calling `isPresent()`, undermining the whole point of using `Optional` in the first place.
226+
>
227+
> During the Java 9 time frame, we proposed to deprecate `Optional.get()`, but the public response to that was ... let's say cold. As a smaller step, we introduced `orElseThrow()` in 10 (see [JDK-8140281](https://bugs.openjdk.java.net/browse/JDK-8140281)) as a more transparently named synonym for the current pernicious behavior of `get()`. IDEs warn on unconditional use of `get()`, but not on `orElseThrow()`, which is a step forward in teaching people to code better. The question is, in a sense, a "glass half empty" view of the current situation; `get()` is still problematic.
228+
</description>
229+
<priority>3</priority>
230+
<properties>
231+
<property name="xpath">
232+
<value>
233+
<![CDATA[
234+
//MethodCall[pmd-java:matchesSig('java.util.Optional#get()')]
235+
]]>
236+
</value>
237+
</property>
238+
</properties>
239+
</rule>
240+
211241
<rule name="AvoidStringBuilderOrBuffer"
212242
language="java"
213243
message="StringBuilder/StringBuffer should not be used"

0 commit comments

Comments
 (0)