Search code examples
javainterfacefieldfluent

How to make a method pop first in java fluent interface?


This is my first asking, so sorry if I messed something. I have a task to implement a Mail, using Java fluent interface. I must have fields: From, To, Subject.

The problem is, I can not make "From" to appear as first and only. Example: MailBuilder builder = new MailBuilder(); builder.from("Stiliyan").to("Alexander").subject("Welcome aboard");

But when I type the first dot "." all of them appears. (eg builder.to("a").from("b")..)

So in short: builder.(HERE MUST APPEAR ONLY "from").to("No worries")..."

Here is MailBuilder.java

So here after "." must appear ONLY from method


Solution

  • Then your declared return type of each of the builder methods cannot be the same. You can still return the same builder instance though. For example:

    interface IFromBuilder {
        IToBuilder from(String from);
    }
    
    interface IToBuilder {
        IMailBuilder to(String to);
    }
    
    interface IMailBuilder {
        Mail build();
    }
    
    class MailBuilder implements IFromBuilder, IToBuilder, IMailBuilder {
    
        private String from;
        private String to;
    
        @Override
        public IToBuilder from(String from) {
            this.from = from;
            return this;
        }
    
        @Override
        public IMailBuilder to(String to) {
            this.to = to;
            return this;
        }
    
        @Override
        public Mail build() {
            return new Mail(from, to);
        }
    }
    
    class Mail {
        private final String from;
        private final String to;
    
        public Mail(String from, String to) {
            this.from = from;
            this.to = to;
        }
    
        public static IFromBuilder newBuilder() {
            return new MailBuilder();
        }
    }
    
    
    public class Demo {
        public static void main(String[] args) {
            Mail mail = Mail.newBuilder().from("sender@a.com").to("receiver@b.com").build();
        }
    }