3

I have found thee code, I'm beginner in java,

Code:

map.addMarker(new MarkerOptions()
                .position(new LatLng(10, 10))
                .title("Hello world")

What i know is when we instantiate an object with parameter we do this :

MarkerOptions markerOptions= new MarkerOptions(23, 94);
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Zakaria
  • 39
  • 1
  • 5
  • 2
    I don't get you, but i think you search for [Builder pattern](https://jlordiales.me/2012/12/13/the-builder-pattern-in-practice/) – Youcef LAIDANI Nov 30 '17 at 12:12

2 Answers2

2

Welcome to stack oveflow.

Basically, break down the function a little bit:

map.addMarker(new MarkerOptions()
            .position(new LatLng(10, 10))
            .title("Hello world")

is the same as:

MarkerOptions someOptions = new MarkerOptions();

LatLng location = new LatLng(10, 10);
someOptions.position(location)
someOptions.title("Hello World");

map.addMarker(someoptions);

When you'er a new programmer, breaking it down like this allows you to easily inspect (either through the debugger or printing off) the various elements.

The design pattern here is basically that the code is using a sort of Builder Pattern system: instead of taking map.addMarker taking a lot of optional or override variants, it takes an "options" object, and you can either create it in advance, or create it on the fly (like here). This way the options object can have tons of default parameters, and you only set the ones you care about right now.

When you're making a lot of things, doing it in one line might make more readable code to a reasonably trained developer, but when you're starting out, it can be more confusing.

Jmons
  • 1,766
  • 17
  • 28
  • thanks for help, is this design pattern particular to googleMap library or can used in all classes in java? – Zakaria Nov 30 '17 at 12:29
  • Oh you see it on any complex libray thing, and not just Java either - C# is full of them... for example anything to do with http requests might take an 'options' object, because there are hundreds of possible options you might set (timeouts, follow redirects) etc. have a look at this: https://stackoverflow.com/questions/3394853/builder-pattern-vs-config-object – Jmons Nov 30 '17 at 12:34
1

in your example MarkerOptions markerOptions= new MarkerOptions(23, 94);

we call markerOptions a handler it handle the memory address of the object so we can create an object withour saving it's memory address for further use like this (new MarkerOptions()).

In you example you'are using the constructor to pass params (23.97) but you can also use the setters like this new MarkerOptions().position(new LatLng(10, 10)) he is calling the method position and pass a new object in parameters the same of .title("Hello world")