FWIW, I too have fallen into this trap, and I did that even more than
once. When my brain sees Path.endsWith(String), it somehow silently
assumes that its semantic is that of String.endsWith(String).

Of course, it isn't. What's worse, I learn about my mistake at
runtime. But not because of an exception, no; I learn about it by
getting unexpected results.

There used to be a method that implemented the file extension thingy,
but the commit was backed out. If it makes its way back in one form or
another, it might help to avoid the trap:

commit 10356e767a44632c5de142d4666bd85d4618bf71
Author: Brian Burkhalter <b...@openjdk.org>
Date:   Wed Dec 7 18:54:18 2022 +0000

    8298303: (fs) temporarily remove Path.getExtension

    Reviewed-by: smarks, alanb

commit 50d91a31d495adf8e189d0188918f4ff22f93876
Author: Brian Burkhalter <b...@openjdk.org>
Date:   Tue Nov 1 21:35:54 2022 +0000

    8057113: (fs) Path should have a method to obtain the filename extension

    Reviewed-by: rriggs, lancea, mr, alanb

On Wed, Sep 10, 2025 at 8:01 PM David Alayachew
<davidalayac...@gmail.com> wrote:
>
> Hello @core-libs-dev,
>
> I have frequently run into the following pothole.
>
> Imagine the following directory setup.
>
> root/folderA/fileX.java
> root/folderB/fileY.js
> root/folderC/fileZ.html
>
> In this directory, let's say that we run the following code.
>
> Files
> .walk(Path.of("root"))
> .filter(path -> path.endsWith("html"))
> .forEach(System.out::println)
> ;
>
> One would expect only fileZ.html to be printed out, but nothing does. The 
> reason why is because path.endsWith(String) is effectively an alias for 
> path.endsWith(Path.of(String)). The confusion being that Path.of(someString) 
> is looking for a file or a directory. Thus, since there is neither a file nor 
> a folder called "html", the stream prints out nothing.
>
> This a very easy pothole to fall into, as the method name endsWith is the 
> same as the one for String, thus, people will easily mix it up. And worse 
> yet, depending on what they test with, they can easily confuse themselves 
> into thinking they are good. For example, if I had done "fileZ.html" as my 
> endsWith, I would have returned exactly what was expected, causing me to be 
> misled.
>
> And as a cherry on the top, the syntactic benefit of this method is very 
> little. Wrapping your string in a Path.of() means that you fall under the 
> Path.endsWith(Path) overload, which is more explicit what it does. And at the 
> very least, should give pause to the developer thinking it is doing String 
> comparison, as they have to wrap their String in a Path, causing a moment to 
> think.
>
> So, since this is a low value method and it causes high confusion, I vote 
> that we deprecate it.
>
> Thoughts?
>
> Thank you for your time.
> David Alayachew

Reply via email to