Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what this code mean in java, is he using a design pattern

Tags:

java

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);
like image 695
Zakaria Avatar asked Jan 30 '26 21:01

Zakaria


1 Answers

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.

like image 160
Jmons Avatar answered Feb 03 '26 11:02

Jmons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!