Creating a single new value from the collection with your own conditioning

Samrith Yoeun
3 min readAug 20, 2020

Senario 😅:

It is a Thursday afternoon, and you are given a task to get the response from API and arrange 4 values of Address (commune, district, county, and country) to create a single line string to display it on screen.

You are also told to only skip the value of Address if it is empty, and put a ‘,’ to seperate each type of address field.

You said to yourself,

it is a piece of cake 🍰, let’s just define a String, checking the response value of each Address field (commune, district, county, and country) to make sure it is not empty, and put a ‘,’ between them. Piece of Cake, Yeah.

… And your code might look like this 🤣 (let’s focus on getAddress function):

well it is lengthy 😌, but it worked right ?…

Haha, then your manager come to your desk and tell you 🙃:

Dude! PO (Product officer) said they want to add more fields(village, streetNumber, to display in the address Label, rearrange the order from (commune, district, province, country) to (country, province, district, commune, village, houseNumber), and also change the separator from ‘,’ to ‘-’.

Within your mind, you were like 🤨,

Damn bruh , when will we have the finalize PRD (product requirment document) that wont be change in a blink 💨 ??? you seriously tell me to redo the whole things again?

But somehow you need to do it 😖

That’s when the use of Reduce of collection come to play.

Reduce : is a method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration

Reduce take two main arguement ‘initialResult’ and ‘nextPartialResult’

initialResult: The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed.

nextPartialResult:A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller.

And here is the Enhance code of AddressEntity look like (Again, focus on func getAddress)

well, this piece of code will help you to be more flexible on the next PRD changes.

Let’s talk about what’s new (and better) in func getAddress()

  1. we are using a collection . The good things are that we can change the collection element order to reflex the change in output of reduce, the next time they add a new field we simply add it into our collection.
  2. we defined our separator, now it can be changed within the matter of second. (no need to find replace for ‘,’ anymore)
  3. our function become shorter (I can make the function shorter with the help of Unnamed param, but i dont want to confuse the junior dev that will soon read my code)

That’s it for today, this article does help me release some stress 😤, and i hope you write some wonderful code with Reduce.

--

--