Skip to content
Advertisement

How do I connect methods with dots? – Refactoring

I am trying to refactor my code. But I dont know how to do what I want to do. I dont know how it’s called so I dont find it with google. My Code:

public void print(int from, int to) {
        // TODO Auto-generated method stub
        
        for(;from<=to;from++)
        {
            if(from % 3 == 0)
            {
                if(from % 5 == 0)
                {
                    System.out.println("Fizz Buzz");
                }
                else 
                {
                    System.out.println("Fizz");
                }
            }
            else
            {
                if(from % 5 == 0)
                {
                    System.out.println("Buzz");
                }
                else 
                {
                    System.out.println(from);
                }
            }
        }
        
    }

I want to refactor everything so the final version looks like this:

print("Fizz").If(from).IsMultipleOf(3);
print("Buzz").If(from).IsMultipleOf(5);
print("Fizz Buzz").If(from).IsMultipleOf(3).And.IsMultipleOf(5);

or like this:

if(If(from).IsMultipleOf(3) && If(from).IsMultipleOf(5))
{
print("Fizz Buzz");
}

So the “If(from).IsMultipleOf(3)” shall return true/false and if its true it shall execute the print() function. But I dont know how to do it with the dots (“.”).

Could someone please tell me the right term to google for or show me an example?

-Thanks already in advance!

Advertisement

Answer

You need look for Fluent Api Pattern and Builder Pattern

Simple example

public class CheckTest {

    private int num;

    // private constructor for avoiding new CheckTest()
    private CheckTest(int num){ 
        this.num = num;
    } 

    // must start with Print.num(...); on static method
    // see we are returning the same class to use other methods in one line
    public static CheckTest num(int num){ 
        return new CheckTest(num);
    }

    // can be called by Print.num().isMultipleOf()
    public boolean isMultipleOf(int muiltipleOf){ 
        return ( this.num % muiltipleOf ) == 0;
    }

    // can be called by Print.num().isMultipleOfThenPrint()
    public void ifIsMultipleOfThenPrint(int muiltipleOf, String msgToPrint){
        if( isMultipleOf(muiltipleOf))
            System.out.println(msgToPrint);
    }
}

using our simple class

if( CheckTest.num(10).isMultipleOf(5) && CheckTest.num(15).isMultipleOf(5) ){
    System.out.println("print");
}

CheckTest.num(15).ifIsMultipleOfThenPrint(5,"print");

Advertisement