Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multiple functions starting with dots

Tags:

java

There is a type of statement in java that I could not understand or even find anything about through googling. I would like to share an example which I wrote but without understanding the language structure :

MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.post("/user_sessions/first")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"username\":\""+username+"\",\"password\":\""+password+"\"}"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();

I don't understand what contentType , content, andExpect and andReturn are. They are obviously functions, but how can I call them like this. What class do they belong to? Overally I am very confused with the structure here.

like image 503
Özüm Avatar asked Jan 10 '23 21:01

Özüm


2 Answers

What you are seeing here is called a fluent interface. A fluent interface is a mechanism to help improve the readability of code by cascading method calls. When you create a method the return value is that of the class, so in pseudo code this would be something like -

class Foo {
   private String baa;
   private String moo;
   public Foo setBaa( String baa ) {
     this.baa = baa;
     return this;
   }
   public Foo setMoo( String moo ) {
     this.moo = moo;
     return this;
   }
}

Note: the use of this as a return value to show that we are returning our current foo instance. This would allow the folliwng behaviour -

Foo test = new Foo();
test.setBaa( "baa" ).setMoo( "moo" );

If you would like more information on Fluent interfaces please have a look at http://en.wikipedia.org/wiki/Fluent_interface which gives a fairly in depth explanation.

like image 145
David Long Avatar answered Jan 14 '23 21:01

David Long


This is done for better readability. You could also write it as:

result = this.mockMvc.perform(MockMvcRequestBuilders.post("/user_sessions/first").contentType(MediaType.APPLICATION_JSON).content("{\"username\":\""+username+"\",\"password\":\""+password+"\"}")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();

All those methods return objects and the following methods are invoked on the returned objects.

like image 35
stevecross Avatar answered Jan 14 '23 21:01

stevecross