Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does any library exist which provides a fluent way to construct Java format strings? [closed]

Tags:

java

The syntax for Java's format strings can get complicated, for example:

"|%1$-10s|%2$-10s|%3$-20s|\n"

It would seem to be ripe for someone to create a fluent DSL to aid with the construction of these format strings (similar to what Jooq does for SQL).

Does such a thing exist?

like image 465
sanity Avatar asked Jun 17 '13 15:06

sanity


1 Answers

You could create such an API using fluflu, a fluent API generator, which was inspired by jOOQ's API and jOOQ's underlying API design techniques.

Fluflu offers annotations that are processed using APT tools to generate a fluent API from the API implementation. The annotations model a finite state machine. Here's an example from their wiki:

@Fluentize(className = "CoreClass", startState = "State0", startMethod = "start")
public abstract class ToBeFluentized implements Cloneable {

    @Transitions({ 
        @Transition(from = "State0", end = true),
        @Transition(from = "State1", end = true) 
    })
    public void end() {
    }

    protected String with = null;
    protected List<byte[]> b = new LinkedList<>();

    @Transition(from = { "State0", "State1" }, to = "State0")
    public abstract ToBeFluentized with(
        @AssignTo("with") String a, @AddTo("b") byte[] b
    );

    @Transition(from = "State1", to = "State0")
    public ToBeFluentized z() {
        return this;
    }

    Set<Integer> j = new HashSet<>(); 
    @Transition(from = "State1", to = "State1", name="a")
    public abstract ToBeFluentized z(@AddTo("j") int j);

    @Transition(from = "State0", to = "State1")
    public ToBeFluentized a() {
        return this;
    }

    @Transition(from = "State0", to = "State1")
    public ToBeFluentized b() {
        return this;
    }

    @Transition(from = "State0", to = "State1")
    public ToBeFluentized vari(String... strings) {
        return this;
    }
}

This can then be used as such:

State0 c = CoreClass.start().a().z();
State0 d = c.b().with("z", "z".getBytes());
State0 e = c.b().with("q", new byte[]{0,0,1});
d.end();
e.end();

Of course, you'll still have to write the implementation :-)

like image 73
Lukas Eder Avatar answered Oct 22 '22 14:10

Lukas Eder