6

I started working on a project and I saw some methods with this With prefix and I'm wondering if this refers to a known pattern.

Does anyone know of this naming pattern?

2
  • Could you provide some examples? I’ve seen methods with a With prefix used in a Fluent Builder Pattern, but even then only use it when it makes sense. Commented Jul 8, 2021 at 17:24
  • @RikD I saw 2 sub-patterns: A) methods that returns void and simply set fields (essentially setters); and B) methods that set fields and returns this. Commented Jul 8, 2021 at 17:33

1 Answer 1

7

I've seen a with prefix used in a couple of different ways that may be similar to what's being done in the codebase you're working on.

Joshua Bloch's Builder pattern

var myobj = MyObj.builder() .withProperty1("property 1 value") .withProperty2("property 2 value") .build(); 

Clone immutable objects

var myImmutableObj = new MyImmutableObj("property 1 value", "property 2 value"); var myImmutableObjClone = myImmutableObj.withProperty1("different property 1 value"); 
7
  • Very interesting, I think they are using both approaches in this project. You nailed it, thanks! Commented Jul 8, 2021 at 17:34
  • 3
    To be clear, this is Joshua Bloch's Builder Pattern. Not the GoF Builder Pattern. Commented Jul 8, 2021 at 19:33
  • @candied_orange are both of them called "builder pattern"? Commented Jul 8, 2021 at 20:08
  • @underthevoid yes. So much so that I never just say builder pattern anymore without qualifying. So much so that I nag other people about it. I hate names that require disambiguation. So much that it can make me fail to upvote an otherwise decent answer while I wait for an edit. Commented Jul 8, 2021 at 21:58
  • 1
    @svidgen didn't want to be hasty and start an edit war. But Mike's been gone for 6 hours now. So... Commented Jul 9, 2021 at 2:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.