r/java • • Dec 11 '25

Modern Bytecode Instrumentation with ByteBuddy – Rafael Winterhalter | The Marco Show

https://www.youtube.com/watch?v=AzfhxgkBL9s
40 Upvotes

12 comments sorted by

View all comments

Show parent comment

3

u/repeating_bears Dec 12 '25

I didn't mean to imply that named and default params were the only language features that start to obviate the need for builders; they were just examples. There are other features that also help: some kind of spread operator, or withers like you mentioned.

But with only having named and defaults params, we could structure our tests like this

@Test
public void markPostAsSpam_PostTurnsInvisible() {
    Post post = createPost(); // visible = true is the "sensible test default"
    Post spamPost = postService.markAsSpam(post);
    Post invisiblePost = createPost(isVisible: false);
    assertThat(spamPost).isEqualTo(invisiblePost);
}

// This method exists within test
// hypothetical syntax where = denotes default if omitted
private static Post createPost(
    String title = "Test Post",
    String content = "",
    List<String> tags = List.of("news"),
    isVisible = true
) {
    return new Post(title, content, tags, isVisible);
}

Post's constructor in this instance may either provide default params (e.g. for app code) or not. It doesn't matter, as the test code will provide all of them.

Why is that worse than your example?

2

u/JustJustust Dec 12 '25

If I understand your intention correctly, then createPost in your example is a factory method with the sole purpose of providing test defaults and named params for a constructor that doesn't have any?

That would allow me to keep production code free of test values and still have a low-overhead way to provide them for tests. Makes perfect sense to me, thanks! :)

For some reason I had assumed the defaults with test values would have to be on the actual constructor.

2

u/repeating_bears Dec 12 '25

That's right, but it would also be possible to mix and match.

Here's an example where Post provides a default for 'content', which the test factory method uses, but the factory method also applies more defaults on top of that.

class Post {
    Post(String title, List<String> tags, boolean isVisible, String content = "") {
        //...
    }
}

class MyTest {
    @Test
    public void something() {}
    
    private static Post createPost(
        String title = "Test Post",
        List<String> tags = List.of("news"),
        isVisible = true
    ) {
        // content is omitted, so Post's default is used
        // Perhaps the tests have no reason to change it
        return new Post(title, tags, isVisible);
    }
}