google / mug

A small Java 8 library (string manipulation, stream utils)
Apache License 2.0
367 stars 65 forks source link

StringFormat is great. But it's not type safe if the StringFormat is defined far away. #38

Closed xingyutangyuan closed 11 months ago

xingyutangyuan commented 1 year ago

Example:

// A.java
StringFormat format = new StringFormat("{foo}/{bar}-{baz}");

// B.java
format.parse(input, (foo, bar) -> ...);

// C.java
format.format("x", "y");

Seems easy to mess up?

fluentfuture commented 1 year ago

Internally we have some ErrorProne compile-time checks to ensure safety.

Might make sense to consider porting them, or just implementing them directly here, if it sounds useful, I guess?

If we do, we might need to add a new artifact holding the EP checks.

fluentfuture commented 11 months ago

Thanks setting up ErrorProne!

The EP plugin is now in place to protectc common usage (at least when using bazel).

There is a known issue with the bazel java_plugin, that is, it only enforces the check when mug:format is the direct dependency. But if a StringFormat constant is referenced without importing the StringFormat type, the mug:format target isn't required and the plugin won't be effective.

I'm not yet sure what the Maven story is (the annotation processor isn't yet effective).

If we can't get Maven to work, or if Maven build suffers the same issue, we could implement a check to guard against using StringFormat as a public field, or method return type.

fluentfuture commented 11 months ago

I believe this is now fixed.