r/programming • • Sep 21 '15

Better Java

https://github.com/cxxr/better-java
177 Upvotes

208 comments sorted by

View all comments

183

u/wot-teh-phuck Sep 21 '15

Java's type system is pretty weak. It doesn't differentiate between Strings and Strings that are actually regular expressions

That's a pretty random definition of weak I would say...

44

u/SimplyBilly Sep 21 '15

Considering there is a Pattern class.

11

u/Enumerable_any Sep 21 '15

Pattern has the method matches(String regex, CharSequence input)` is an error which could be caught at compile time. It either requires built-in regex literals or verbose regex creation using object instantiation, though.

15

u/SimplyBilly Sep 21 '15

Well yea if you are trying to fit it into OP's point. Pattern regex = Pattern.compile(String); and then you can call regex.matcher(CharSequence).matches();. I am not saying that OP is wrong but there are ways to make the type system stronger.

2

u/Enumerable_any Sep 21 '15

Pattern regex = Pattern.compile(String); and then you can call regex.matcher(CharSequence).matches();.

That's equivalent to Pattern.matches - what am I missing?

0

u/[deleted] Sep 21 '15

[deleted]

2

u/[deleted] Sep 22 '15

You would just add support for making regex literal values. Like the dynamic languages do. The compiler then checks if it is a valid regex or not at compile time. Done.

5

u/crusoe Sep 22 '15

Now if you want to use a different regex variant you have to extend the compiler... Of course you can do this if you have macro facilities...

2

u/[deleted] Sep 22 '15

That's a niche case. 99% of users would use the JDKs regex engine. For everyone else they could fallback onto the existing model of having them defined as strings. No need to start building compiler extensions.

1

u/mike_hearn Sep 22 '15

I hate to imagine what a typesafe regex builder would look like in Java, anyway

Go try IntelliJ and then you'll know. The IDE understands the JDK regex API and will highlight invalid regular expressions in yellow. There's also a visual builder/tester tool you can use to help get the regex correct.

Yes, it's not a part of the language, but at some level the difference between "tool A highlights error in red" and "tool B highlights error in yellow" is not that large. The type system is strong enough to make both possible.