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?

  • 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.
    – Rik D
    Jul 8 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. Jul 8 at 17:33

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")

Clone immutable objects

var myImmutableObj = new MyImmutableObj("property 1 value", "property 2 value");
var myImmutableObjClone = myImmutableObj.withProperty1("different property 1 value");
  • Very interesting, I think they are using both approaches in this project. You nailed it, thanks! Jul 8 at 17:34
  • 2
    To be clear, this is Joshua Bloch's Builder Pattern. Not the GoF Builder Pattern. Jul 8 at 19:33
  • @candied_orange are both of them called "builder pattern"? Jul 8 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. Jul 8 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... Jul 9 at 2:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.