Search code examples
javajnarect

JAVA method calling upon method


I think i confused myself a little bit - anyways, how do i call a method upon another method. Like method().method().method(); ? I'd like to create a similar method myself for this sample code:

public RECT getPositionOfClient() {
    HWND client = User32.INSTANCE.FindWindow("classname", "client");
    RECT rect = new RECT();
    User32.INSTANCE.GetWindowRect(client , rect);
    System.out.println("rect = " + rect);
    return rect;
}

Here i'd like to be able call getPositionOfClient().getTop(); or getPositionOfClient().getBottom(); which is something the JNA RECT class provides (top,bottom, left, right). How do i do this?

Thanks in advance :)


Solution

  • In order to make that possible, you need fluent APIs.

    Meaning: each of your methods ... has to return some object; like:

    Whatever a() { ... does something ... and 
     return whatEverInstance;
    }
    

    and then, when all your a()s, and b()s return something, you can write down such code.

    And if you "stay" within the same class, and each method is just doing a

    return this;
    

    so you keep calling methods on the same object; than that is a somehow acceptable practice.

    For any other cases: you should be really careful about doing that! As this practice in that case means: violating Law of Demeter.

    The point is: a class should only know about its direct neighbors. You don't want to write code like

    myField.doSomething().inSomeOtherClass().andNow2HopsAway() ...
    

    because that couples this code to a completely different class.

    Long story short: don't build fluent APIs just for the fun of it. Consider carefully where they make sense; and never forget about the Law of Demeter!

    EDIT; after reading your questions and comments more thoroughly; I think you not only confused yourself, but also us:

    as of now

    public RECT getPositionOfClient() { ... returns an instance of RECT }
    

    And top, left, ... are fields on RECT.

    So you get

    int whatever = foo.getPositionOfClient().top;
    

    Done. It is a field; you don't need anything else but use ".top" for example when your method is already returning a RECT!