<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Byte-sized learner</title><description>Father of two, educator, life-long learner, pragmatic programmer, footballer</description><link>https://htswe.github.io/</link><language>en</language><item><title>From Chaos to Clarity: Unifying Teams</title><link>https://htswe.github.io/blog/chao-to-clarity-unifying-teams/</link><guid isPermaLink="true">https://htswe.github.io/blog/chao-to-clarity-unifying-teams/</guid><description>When I wrote the last post, the word that echoed in my head was chaos. Smart people were pushing hard in different directions, and the migration felt like a crowded intersection with all green lights…</description><pubDate>Mon, 25 Aug 2025 00:00:00 GMT</pubDate><content:encoded>### Introduction

When I wrote the last post, the word that echoed in my head was chaos. Smart people were pushing hard in different directions, and the migration felt like a crowded intersection with all green lights. We were moving, but not together. This is how the noise turned into a shared rhythm.

### The Messy Middle

![Bustling City Traffic Jam](https://images.pexels.com/photos/30726390/pexels-photo-30726390.jpeg)

Two major streams powered the effort: one team rebuilding an MVP existing feature screen in React Native, the others laying foundations and adding tons of stuffs — Design System, Cursor AI rules, CI/CD, Detox Testing, Adding Greenfield features, integrating SDKs for a brownfield app, etc. Around them orbited more groups: web developers, design system, backend, automation QA, and a few mobile engineers from native teams. Work multiplied; alignment didn’t. Secrets were handled differently on iOS and Android. Decisions lingered. Engineers were busy, yet unsure if busy meant progress. Everyone cared. No one owned the whole picture.

### Listening Before Leading

I started with conversations, not plans. One by one, I met the leaders and asked two questions: what brought you here, and what would make this worth it? Some wanted testing to be the bedrock. Others prized developer experience. A few were laser-focused on shipping. Naming those motivations changed how decisions sounded—less abstract, more human. It gave us a shared vocabulary for trade-offs.

![Listening](https://images.pexels.com/photos/1490844/pexels-photo-1490844.jpeg)

Then I went to the people most affected: the native platform heads — one of them my direct manager. With so many external voices, it was easy for the core teams to feel like passengers. I made sure they weren’t. When they co-owned the plan, adoption followed naturally.

I mapped stakeholders — who was involved, what they planned next, what are their concerns, what drove their choices. Patterns emerged. This map becomes the guiding star on what is important to us.

### Slow Down to Speed Up

I wrote a simple roadmap. No 50-page strategy, just phases, guardrails, and clear description. It lowered the temperature immediately. People didn’t need perfect answers — they needed to see where we were going and how we’d course-correct.

![Running](https://images.pexels.com/photos/4775192/pexels-photo-4775192.jpeg)

External consultants were our leverage. We didn’t hand them the steering wheel; we asked them to sit in the passenger seat and help read the map and get the guidance. Our engineers capability grew. Dependency didn’t.

### Build the Channels, Then the Message

We fixed the basics: Slack channels with purpose, Slack and Email groups for easier communication and meetings, GitHub teams for visibility and ownership. On the iOS side, that work revealed structure gaps we could mirror from Android. Communication stopped feeling like a firehose and started behaving like a system.

![Channels](https://images.pexels.com/photos/31129059/pexels-photo-31129059.jpeg)

Then came the big moment: the first online meeting with all engineers. Nearly a hundred engineers joined. I’d never spoken to a group that large. I recognize a few names. To keep it human, I planted a few questions with engineers ahead of time. The Q&amp;A flowed. Years of working with large groups did their quiet work — I stayed calm, kept it clear, and we made the plan feel real for everyone.

### Documentation as a Product

I built a new Confluence home from scratch — structure first, content second.

![Writing](https://images.pexels.com/photos/796603/pexels-photo-796603.jpeg)

I found champions and gave them ownership. We treated documentation like a product: actively maintained, reviewed, and refactored. AI tools made it faster to draft and evolve. No more of answering the same question twice. People asked, we pointed to the documentation.

### Cadence Creates Trust

![Trust](https://images.pexels.com/photos/6476774/pexels-photo-6476774.jpeg)

Every week, leaders received a short update. Every other week, the broader team did too. Wins, decisions, risks, next steps — short and honest. When we had something genuinely useful, we invited the right people to the table. Predictability reduced anxiety. Transparency built trust.

### The Support Loop

![Support](https://images.pexels.com/photos/1072824/pexels-photo-1072824.jpeg)

Some engineers were stuck and some were simply exhausted. We rotated consultants to pair with them. When issues were solved, we turned fixes into share-backs: short posts, quick demos, doc updates. The loop turned blockers into learning and learning into momentum.

### Closing

Hard work still matters. But creating systems, setting up clear &amp; inclusive roadmaps, documentation, support loops — buy us the time to think and the space to lead. Clarity wasn’t a single decision; it was a set of habits practiced every week.

Next up: Scaling the Platform: The Architectural Decisions That Saved Us</content:encoded><category>cross-platform</category><category>migration</category><category>mobile development</category></item><item><title>Cross-Platform Migration: Two Weeks In</title><link>https://htswe.github.io/blog/cross-platform-migration-continued/</link><guid isPermaLink="true">https://htswe.github.io/blog/cross-platform-migration-continued/</guid><description>It’s been two weeks since our cross-platform migration journey. While I’ve gained significant insights, this initial phase has highlighted the inherent challenges of this complex undertaking.</description><pubDate>Tue, 25 Mar 2025 00:00:00 GMT</pubDate><content:encoded>### Introduction

It’s been two weeks since our [cross-platform migration journey](2025-03-11-migration-to-cross-platform). While I’ve gained significant insights, this initial phase has highlighted the inherent challenges of this complex undertaking.

### The Chaos

![Team Collaboration](https://images.pexels.com/photos/3184292/pexels-photo-3184292.jpeg)

The project is structured around two main groups: one focused on replacing a key feature screen with React Native, and another setting up foundational elements like CI/CD scripts and other utilities. Despite our common goal, the team currently feels a sense of chaos and disorganization. With numerous stakeholders involved from web development, design, and backend, there is a distinct lack of clarity on goals and plans. This dynamic has left the team feeling uncertain and divided.

#### Feature vs. Foundation Team Dynamics

The feature team, which includes both Android and iOS engineers, seems to collaborate more closely, likely due to their shared focus on the same screens. In contrast, the foundation team appears more distant, with each member focusing on their platform’s builds. This has led to duplicated efforts and friction, for example, with secrets management differing between platforms.

### The Struggle

![Late Night Work](https://images.pexels.com/photos/4050299/pexels-photo-4050299.jpeg)

The team is working tirelessly, often late into the night. Newcomers face challenges with initial setups due to outdated documentation, which disrupts the flow for busy team members. A workshop with Codelab-style instructions proved beneficial, as it empowered sub-team leaders to effectively train their teammates.

### Personal Reflections

These past two weeks have been intense. My work hours have extended as I balance my native responsibilities with my new React Native role. The stress is palpable, with longer meetings and persistent alignment challenges. I am grateful for the support from my manager and mentor.

On the leadership and learning front, I&apos;ve found it challenging to drive alignment across multiple team heads with differing priorities. This experience has reinforced the importance of proactive leadership, and I have taken the initiative to lead conversations and bridge gaps between the two mobile organizations.

Learning about CI/CD and JS bundling was initially tough, but tools like Cursor LLM accelerated my understanding. I was initially gathering insights on the team&apos;s experience on compile times and tool efficacy for native development.

### Looking Ahead

![Future Planning](https://images.pexels.com/photos/3184465/pexels-photo-3184465.jpeg)

Despite the challenges, this journey offers valuable lessons in collaboration and adaptation. In the next post, we will explore how we overcome these challenges.

### Summary

The past two weeks have highlighted the complexities of cross-platform migration, from team dynamics to technical hurdles. While the road is challenging, the potential benefits make it a journey worth pursuing. Stay tuned for more insights as we continue this transformation.</content:encoded><category>cross-platform</category><category>migration</category><category>mobile development</category></item><item><title>The Journey from Native App to Cross-Platform</title><link>https://htswe.github.io/blog/migration-to-cross-platform/</link><guid isPermaLink="true">https://htswe.github.io/blog/migration-to-cross-platform/</guid><description>After eight years of relying on native Android and iOS apps, my company&apos;s business growth had presented several new challenges. Our platform was struggling to scale, with development velocity constra…</description><pubDate>Tue, 11 Mar 2025 00:00:00 GMT</pubDate><content:encoded>### Introduction

After eight years of relying on native Android and iOS apps, my company&apos;s business growth had presented several new challenges. Our platform was struggling to scale, with development velocity constrained by the need to hire at least one developer for each platform before a project could even begin.

As the team expanded, a division emerged. The Android and iOS teams, each with their own leads and development practices, tended to work in silos. My key challenge was to address this by increasing efficiency and fostering a culture of reusability and knowledge-sharing across platforms.

### My Search for a Solution: The Kotlin Multiplatform Evaluation

To address this challenge, I began to evaluate cross-platform solutions together with 2 other android and iOS leads. My initial thought was to explore Kotlin Multiplatform (KMP), which seemed promising for sharing business logic.

After several discussions with the Android and iOS leads, I found that the iOS team was reluctant to share UI code due to their ongoing migration to SwiftUI. However, we discovered that KMP could be used to build a shared library for non-UI code, which was a significant breakthrough.

My team and I initiated a **proof-of-concept** by building a deep-link parser to be shared between the apps. This was a critical first step in proving the value of a shared codebase.

### Strategic Insights from the Kotlin Multiplatform Proof-of-Concept

Our six-month evaluation period provided valuable insights:

- **Organizational and Technical Hurdles**: We discovered that KMP&apos;s lack of a mature Swift export at the time was a major deterrent for the iOS team. This showed me that technical compatibility is not enough; organizational buy-in is a critical factor in a large-scale migration.

- **Tooling and Development Efficiency**: The need to constantly switch between Xcode and Android Studio highlighted the high cost of a fragmented development environment. I learned that a seamless developer experience is essential for a project&apos;s success.

- **Team Dynamics**: My team and I intentionally gave the iOS lead the space to explore and learn, to ensure we addressed their concerns and gave them a sense of ownership in the process. This taught me that building trust is key to successful collaboration.

### The Strategic Pivot to React Native

In a sudden turn of events, the React Native idea was introduced to my team. I quickly recognized its strategic advantages. With the New Architecture announced in 2024, React Native had made significant performance improvements.

The business case was further strengthened by two key factors:

- **Over-the-Air (OTA) Updates**: React Native&apos;s unique ability to ship instant updates to our users was a huge selling point.

- **Resourcing Efficiency**: With an internal team of web developers already proficient in React, I saw an opportunity to consolidate our talent pool and accelerate our resourcing strategy.

The team quickly built a prototype that resembled an existing product. Using AI tools, we were able to quickly validate the idea and secure buy-in from senior leadership.

### Lessons Learned as a Leader

This journey taught me valuable lessons that go beyond the technical. As a leader, I realized that the success of a technology initiative depends on:

- **Bridging the Technical and Human Gaps**: The frontend project was driven by a backend team, which caused significant friction. This experience taught me the importance of empowering the right people with the right skills to drive a project forward.

- **Navigating Tooling Hurdles**: Even with advanced tools, we faced significant challenges. I learned to identify these hurdles early and create a support system for the team to overcome them.

While you could read many articles on migrating platforms from a technical standpoint, this experience has been a masterclass in collaboration, adaptation, and leadership. It has prepared me to lead future teams through their own transformation journeys.</content:encoded><category>cross-platform</category><category>migration</category><category>mobile development</category></item><item><title>Guide for manager during performance review</title><link>https://htswe.github.io/blog/guide-for-manager-during-performance-review/</link><guid isPermaLink="true">https://htswe.github.io/blog/guide-for-manager-during-performance-review/</guid><description>Year end is around the corner. And it means &quot;annual performance review&quot;. Your HR has a short briefing on the process this year (hopefully, it is not much different from last year). You and your team…</description><pubDate>Tue, 19 Nov 2024 00:00:00 GMT</pubDate><content:encoded>### Introduction

Year end is around the corner. And it means &quot;annual performance review&quot;. Your HR has a short briefing on the process this year (hopefully, it is not much different from last year). You and your team start to get busy, the timelines are usually tight. And now, it is about time to have a one on one chat for the review.

Where do you start? How do you go about it? For a new manager, this could be daunting. I hope this article could help you with it.

### Start early and do harder ones first

You won&apos;t do an effective job at handling all the advice below if you start late on this. Too many leaders with large teams write all their performance reviews on the same day in a short period of time. Rather, take the time to think through what you will write (and later say) and how you plan to communicate it. Also, do the hardest reviews first – this will help clear your mind and also keep you from stressing about difficult reviews throughout the process.

### If you need to, practice

![image-center](https://images.pexels.com/photos/260447/pexels-photo-260447.jpeg)

Many reviews won&apos;t require practice in advance, but at least some will. Practice giving tough feedback and having difficult conversations with a neutral party (not another employee, of course). Tap into help from a peer, leader, or human resources professional who can help.

### Don&apos;t bring surprises (and if you have to, give people time to save face)

Feedback should be coming from you **regularly** during the review period. If there is something negative that shows up on the performance review, the person you are reviewing should already have been hearing about it from you for awhile and had a chance to begin working on it. When this isn&apos;t possible (due to leadership transitions) give people time to absorb negative feedback and save some face before attempting to have a constructive conversation.

### Balance the conversation appropriately

If the person you are reviewing is doing great work in 95% of their duties, don&apos;t spend half the time talking about the 1-2 areas where they are lacking. Save that conversation for another time to go into more detail. 

![image-center](https://images.pexels.com/photos/1431158/pexels-photo-1431158.jpeg)

Likewise, if a person is seriously under performing in a major of their work, then don&apos;t try to find positive things to talk about to balance out the bad news – your time giving feedback needs to accurately reflect the work they are doing.

### Give specific examples

You aren&apos;t credible on your praise if the best you can say is “good job” and you don&apos;t give people a path to correct themselves if critical feedback only suggests a “needs improvement.” People need to know specifically what they are doing well so they can repeat and specifically where to make changes to be more in alignment with great performance. Plus, you build trust with people when you cite specific examples. Agree or not, at least they know you care enough to pay attention.

### Hold your ground

During the review conversation is not the time to be making changes to what you are communicating (thus the importance of &quot;Start early and do harder ones first&quot;). Decide on your message in advance and stick to it. A mixed message based upon strong feedback from the other party only serves to make the conversation more complicated and sending a different message than you intended. If you&apos;ve had a hard time holding your ground in the past, you need to practice in advance. See &quot;If you need to, practice&quot;.

### Avoid talking about others not present

![image-center](https://images.pexels.com/photos/583437/pexels-photo-583437.jpeg)

You are reviewing one person at a time, not the entire team. Be sure your feedback focuses on the person at hand and doesn&apos;t veer into an inappropriate conversation about what others are or are not doing in their development. If you need to speak about others for the purpose of examples, stick to the facts and not your opinions or feedback about their development.

### Conclusion

In summary, we explore how we could execute the performance review for both you and your team. We all want to do our best for ourselves and our teammates. Following those guides will help you to sail smoother in the performance reviews, and of course, &quot;Practice makes perfect&quot;.</content:encoded><category>thoughts</category><category>learning</category><category>soft-skill</category></item><item><title>The 7 success factors in building 5 millions downloaded app</title><link>https://htswe.github.io/blog/7-success-factors-in-building-app/</link><guid isPermaLink="true">https://htswe.github.io/blog/7-success-factors-in-building-app/</guid><description>Due to Google Play’s recent policy requiring the disclosure of real names and addresses, I had to close my Google Play account, resulting in the loss of all my apps. While this was unfortunate, looki…</description><pubDate>Fri, 08 Nov 2024 00:00:00 GMT</pubDate><content:encoded>### Why I write it

Due to Google Play’s recent policy requiring the disclosure of real names and addresses, I had to close my Google Play account, resulting in the loss of all my apps. While this was unfortunate, looking back, it has had a significant positive impact on my life and career as an Android developer. My continued passion for the Android ecosystem has been driven by my love for creating community-focused apps as a hobby. I still remember waking up at 5 a.m. every morning and working weekends for those apps. I truly enjoyed it—developing new features users wanted and seeing people use them every day brought me great satisfaction.

### An app with close to 5M downloads

![image-center](/assets/images/store-listing.png)

I never anticipated that one of my apps would become so widely recognized within the community. As it is being shut down on Google Play this month (September 2024), it has nearly 5 million downloads and thousands of daily active users!!! What started as a solo hobby project has turned into something much bigger than I expected, and I’m both surprised and proud of this journey and success.

As the app comes to a close, I’ve reflected on what made it successful, and here are the key factors, in my view, that contributed to its growth.

### The 7 success factors in building app

#### 1. Being first in the market (Global vs Niche)

![image-center](https://images.pexels.com/photos/18543328/pexels-photo-18543328/free-photo-of-great-egret-with-catched-fish-in-beak.jpeg)

In 2011, Android was still relatively new, around the time of Android OS 2.3. There were some apps available on the &quot;Android Market&quot; (before it was rebranded to &quot;Google Play&quot;), including a few good calendar apps like Google Calendar.

Inspired by my tech mentor Charles Keck&apos;s Chinese calendar on Windows OS, I decided to create a calendar specifically for the Myanmar community. Although Android devices weren’t yet affordable for everyone, demand for budget options was growing.

My initial thoughts were:

1. Large companies wouldn’t target a single community.
2. Competing globally would be tough for a solo project.
3. I wanted a calendar for my own needs, and waiting years for Google or others to add regional calendars wasn’t ideal.

&gt; Choosing a niche market meant less competition, and my app was the first of its kind on the Android Market.

#### 2. Spreading the words

![image-center](https://images.pexels.com/photos/1600757/pexels-photo-1600757.jpeg)

Many great projects struggle to reach users, especially when you&apos;re working solo. Friends and family can only spread the word so far, and formal marketing — ads in newspapers, social media, or search engines—can be costly. Like it or not, ***learning to promote your work is essential***.

&gt; Make it community-driven.

Knowing my limits with time and money, I focused on reaching my target audience directly. I joined community forums and Facebook groups interested in mobile tech and app sharing, messaging active members. Many were surprisingly helpful—some even owned mobile shops where they installed apps for customers. They loved the idea of getting early access to my app, so I sent them a copy before each official release.

This approach worked well. They gained a unique offering for their customers, while I gained advocates who spread the word, educated my end users, and helped grow my app&apos;s reach.

#### 3. Time for feedback

![image-center](https://images.pexels.com/photos/10339902/pexels-photo-10339902.jpeg)

The app is now in users&apos; hands, but how do they feel about it? I recall attending a [Design Thinking](https://www.interaction-design.org/literature/topics/design-thinking) workshop where we learned:

&gt; Listen not only to &quot;words&quot; but also to &quot;clues.&quot;

Feedback goes beyond words; observing user interactions reveals more. I shared the app with friends and family, asking them to explore it without guidance. Watching how naturally (or not) they navigated to specific features provided valuable insights.

Designing with the user&apos;s perspective in mind is crucial. When an app feels intuitive, users are more likely to return and engage consistently.

#### 4. Journalist is your friend - seek for &quot;win win&quot;

![image-center](https://images.pexels.com/photos/3062540/pexels-photo-3062540.jpeg)

Publicity is a powerful way to reach a large audience. At the time, tech bloggers, magazines, and newspapers regularly featured industry trends, gadget reviews, and ads for big tech companies. I noticed some also reviewed mobile apps — whether paid or free — that their readers might find useful.

&gt; Have a press kit on hand.

It is time to do cold calls. I prepared a press kit, complete with many high-resolution images in various formats, and sent it to editors, keeping it as easy as possible for them to publish. It paid off; some outlets ran my content word-for-word, and even competitors published the same content at same time. Writing the piece myself allowed me to emphasize the app&apos;s value and encourage people to download and try it out.

#### 5. Negativity to Opportunity

![image-center](https://images.pexels.com/photos/16841952/pexels-photo-16841952/free-photo-of-man-breaking-a-pile-of-bricks-with-his-fist.jpeg)

I am proud of the app&apos;s positive ratings from thousands of users, though it hasn&apos;t always been smooth sailing.

![image-center](/assets/images/user-rating.png)

While we all enjoy good reviews, negative feedback can sometimes offer valuable insights. For instance, accuracy is crucial in a calendar app. Once, a user claimed it was inaccurate and discouraged others from using it. Rather than ignore it, I reached out to understand the issue. Often, misunderstandings arise when users reference the wrong sources.

When we take the time to listen and explain, even critical users can become allies, helping clarify things for others in the community in the future. Since feedback is rare, don&apos;t shy away from engaging with it—especially the negative kind.

&gt; Negative is a form of feedback and an opening for you to try.

#### 6. User Experience vs Profitability

![image-center](https://images.pexels.com/photos/5159249/pexels-photo-5159249.jpeg)

Seeing a growing user base can make monetization tempting, and financial incentive does help sustain long-term development. Many projects fade once initial passion wanes, so finding a way to profit is key to continued updates and new features.

Options include in-app purchases, converting users to a paid version, or adding ads. While ads are a popular choice, they can drive users away if too intrusive. Partnering with brands for sponsored ads, as I did with Samsung and OPPO, is another option but often requires contracts and is usually short-term.

&gt; Strike a balance.

My approach was to prioritize user experience by only using small, unobtrusive banner ads and ensuring the app works offline, hiding ads when users are disconnected. This way, revenue is generated without compromising content or usability.

#### 7. Understanding user pain points

![image-center](https://images.pexels.com/photos/52706/pexels-photo-52706.jpeg)

As the user base grew, feature requests started coming in through emails and internet forums. While it was natural for users to want the app tailored to their preferences, prioritizing these requests was sometimes challenging.

Early on, some users suggested reducing the app size to make it easier to download and more affordable on their data plans. However, I didn&apos;t prioritize this change because I noticed that most users downloaded apps over WiFi. Additionally, with faster 4G networks and cheaper data plans becoming more common, reducing the app size by a few megabytes felt less impactful compared to the development effort required.

&gt; The needs of user change over time.

The world and technology are constantly evolving, so it&apos;s essential to anticipate which features will remain relevant not only today but also in the years ahead.

### Conclusion

Building an app with nearly 5 million downloads has been an incredible journey, filled with lessons in timing, adaptability, and resilience. Reflecting on the seven factors that contributed to this success—finding a unique niche, building a community, embracing feedback, partnering with media, turning negativity into opportunities, balancing user experience with profitability, and understanding evolving user needs—has shown me that passion, user empathy, and creative problem-solving are at the heart of a successful app. Although this chapter is closing, the experience has shaped my approach to development and my commitment to creating valuable, user-centered products in the future.</content:encoded><category>thoughts</category><category>learning</category><category>reflection</category></item><item><title>Notes from Clockwork</title><link>https://htswe.github.io/blog/notes-clockwork/</link><guid isPermaLink="true">https://htswe.github.io/blog/notes-clockwork/</guid><description>&quot;Clockwork: Design Your Business to Run Itself&quot; by Mike Michalowicz is a book focused on helping entrepreneurs and business owners create systems that allow their businesses to run more efficiently a…</description><pubDate>Thu, 29 Aug 2024 00:00:00 GMT</pubDate><content:encoded>### About this book

&quot;Clockwork: Design Your Business to Run Itself&quot; by Mike Michalowicz is a book focused on helping entrepreneurs and business owners create systems that allow their businesses to run more efficiently and independently. But it is also applicable for people who wants to focus on their productivity.

### Who should read

Initially, this book talks mainly about the challenges faced by business owners. But as it goes on, some of the concepts are applicable to everyone who want to focus on productivity of self and the team you are working with.

### My random notes and thoughts

Here are some key lessons from the book:

#### 1. **The Queen Bee Role (QBR)**

**Identify the Core Function**: Every business or role has a primary function that is crucial to its success. This is called the Queen Bee Role (QBR). The key is to identify what that core function is and ensure it is protected and prioritized above everything else. The QBR could be different for different people and different business. This is to help identify the core function via some exercises.

**Protect the QBR**: Once the QBR is identified, the entire team should be aligned in supporting it. This ensures that the most critical aspect of the business is never compromised, allowing the business to thrive. The main idea is not to work on everything, instead focus on QBR and take actions to support that role.

#### 2. **Focus on Designing Systems**

**Delegate, Don’t Abdicate**: One of the challenges for business owner and leader is the delegation. Delegating effectively doesn’t mean handing off tasks and forgetting about them. Instead, it involves creating systems and processes that empower the team to take ownership of their roles while maintaining accountability.

**Create SOPs (Standard Operating Procedures)**: Establish clear, repeatable processes for every significant task in the business. This ensures consistency and efficiency, even when you are not directly involved. This will also save the time to train new teammate.

#### 3. **Utilize the 4D Mix**

**Do, Decide, Delegate, Design**: The 4Ds represent different phases of work. Many time, the business owners are busy &quot;doing&quot; and &quot;deciding&quot;. Doing is when you are the one executing the task, deciding is when someone is doing it for you, but you are the one who decides what to do or how to do. Delegate is where you allow someone to make decision and design is where you change the environment so that everyone can work effectively. As a business owner, your goal is to spend more time in the &quot;Design&quot; phase, focusing on strategy and growth, and less time in the &quot;Do&quot; and &quot;Decide&quot; phases.

**Shift from Doing to Designing**: Set conscious effort to gradually move away from day-to-day operations (“Doing”) and decision-making (“Deciding”) to focus on high-level planning and business design. This transition is crucial for scaling the business.

#### 4. **Leverage Your Team**

**Empower Employees**: Trust the team to take on responsibilities. Empowering them not only frees up your time but also builds a stronger, more resilient organization.

**Build a Self-Sustaining Team**: Your business should not be dependent on any one individual, including yourself. Train and develop your team to operate effectively without constant oversight.

#### 5. **Work Less, Achieve More**

**Efficiency over Hustle**: The goal is to create a business that runs smoothly with minimal intervention, not to work yourself to exhaustion. Focus on doing the right things rather than doing more things.

**Implement the &quot;4-Week Vacation&quot; Test**: The ultimate test of your business’s ability to run itself is whether you can take a four-week vacation without the business falling apart. This goal forces you to put the necessary systems and team structures in place. Do not take shorter weeks as team will tend to wait for your return.

#### 6. **Measure What Matters**

**Track Key Metrics**: Identify and monitor the key performance indicators (KPIs) that truly matter to your business’s success. Use these metrics to make informed decisions and guide your business strategy. This will also guide you whether you need to intervene.

**Continuous Improvement**: Regularly review and refine your processes and systems. Continuous improvement ensures that your business adapts to changes and remains efficient over time.

### Conclusion

Although the book targets the business owner, in my opinion, this could also apply to the team leader. Instead of spending a lot of times &quot;doing&quot; and &quot;deciding&quot;, we should put effort to move into &quot;delegation&quot; and &quot;design&quot; phases to create a self-sustaining business or team that operates efficiently and effectively, allowing us more freedom and flexibility.</content:encoded><category>thoughts</category><category>learning</category><category>soft-skill</category></item><item><title>Ruby on Rails (part 3)</title><link>https://htswe.github.io/blog/ruby-on-rails-part-3/</link><guid isPermaLink="true">https://htswe.github.io/blog/ruby-on-rails-part-3/</guid><description>By using formfor helper, it will automatically adjust if it is new record or updating existing record when submit is executed.</description><pubDate>Sun, 25 Aug 2024 00:00:00 GMT</pubDate><content:encoded>## Controllers and CRUD

Rails helper also has view creation.

```ruby
&lt;%= form_for(@subject) do |f| %&gt;
    &lt;% f.text_field(:name) %&gt;
    &lt;% f.text_field(:position) %&gt;
    &lt;% f.text_field(:visible) %&gt;

    &lt;% f.submit(&quot;Create Subject&quot;) %&gt;
&lt;% end %&gt;
```

By using `form_for` helper, it will automatically adjust if it is new record or updating existing record when `submit` is executed.

Likewise, the text fields will be auto populated if it is existing records.

## Strong params to regulate input

Mass assignment is the term for passing a hash of values, usually form parameters to an object that&apos;s going to be assigned to the object&apos;s attributes. `New`, `create`, and `update` are the primary methods that use mass assignment, but there are a few others as well. In each one of these cases, you&apos;ll see that we&apos;re taking a hash of values, and we&apos;re essentially just dumping them into the object and asking the object to assign all of the attributes based on that hash. That&apos;s what mass assignment is.

Rails is making our lives much easier by allowing us to assign values to this object all at once, instead of having to assign them one by one. Unfortunately, this convenience also introduces a major security issue. The attacker will add sensitive parameter like password to overwrite.

To counter this, rails introduces required parameter and permissable parameters.

```ruby
params.require(:subject).permit(:name, :position, :visible)
```

## Partials and Helpers

To better organize code, rails also provide the partials and helpers.

```ruby
&lt;%= form_for(@subject, :url =&gt; subjects_path, :method =&gt; &apos;post&apos;) do |f| %&gt;

    &lt;%= render(:partial =&gt; &apos;form&apos;, :locals =&gt; {:f =&gt; f}) %&gt;

    &lt;div class=&quot;form-buttons&quot;&gt;
        &lt;%= f.submit(&quot;Create Subject&quot;) %&gt;
    &lt;/div&gt;
&lt;% end %&gt;
```

```ruby
# /views/subjects/_form.html.erb

&lt;table summary=&quot;Subject form fields&quot;&gt;
    &lt;tr&gt;
        &lt;th&gt;Name&lt;/th&gt;
        &lt;td&gt;&lt;%= f.text_field(:name) %&gt;&lt;/td&gt;
    &lt;/tr
    ...
&lt;/table&gt;
```

This `_form.html.erb` can be reused in both new or edit form.

## More readings

[api](https://api.rubyonrails.org)

[guide](https://guides.rubyonrails.org)</content:encoded><category>learning</category><category>ruby on rails</category></item><item><title>Ruby on Rails (part 2)</title><link>https://htswe.github.io/blog/ruby-on-rails-part-2/</link><guid isPermaLink="true">https://htswe.github.io/blog/ruby-on-rails-part-2/</guid><description>ActiveRecord is the rails implementation of active record design pattern. Instead of database row, it retrieves and manipulates data as objects.</description><pubDate>Sat, 24 Aug 2024 00:00:00 GMT</pubDate><content:encoded>## Models and ActiveRecord

### ActiveRecord and ActiveRelation

ActiveRecord is the rails implementation of active record design pattern. Instead of database row, it retrieves and manipulates data as objects.

It also understands the structure of the table, knows how to create, read, update and delete rows as objects.

```ruby
user = User.new
user.first_name = &quot;John&quot;
user.save # SQL INSERT

user.last_name = &quot;Doe&quot;
user.save # SQL UPDATE since it knows there is already row exists

user.destroy # SQL DELETE
```

ActiveRelation is also known as &quot;Arel&quot;. It simplifies the generation of complex database queries. It is chainable and do not execute until needed.

```ruby
users = User.where(first_name: &quot;John&quot;) # SQL not yet execute
users = users.order(&quot;last_name ASC&quot;).limit(5) # chain it to previous query

users.each {|user|
    ... # SQL is now executed because it is needed by now
}
```

### Rails console

We could use rails console to interact with rails.

```shell
rails console -e development
rails console # default environment is development
rails c #shorthand
```

Note: rails comes with `irb` (interactive ruby), but `irb` command alone will not load with your project.

### Create records using ActiveRecord

There are 2 ways that you could create record.

1. instantiate -&gt; set values -&gt; save
2. create

Using approach 1,

```shell
$ rails console
&gt; subject = Subject.new(:name =&gt; &apos;First Subject&apos;)
&gt; subject.position = 1
&gt; subject.save
```

Using approach 2,

```shell
$ rails console
&gt; subject = Subject.create(:name =&gt; &apos;Second Subject&apos;, :position = 2)
```

### Update records using ActiveRecord

There are 2 ways that you could update record.

1. find -&gt; set values -&gt; save
2. find -&gt; update

Using approach 1,

```shell
$ rails console
&gt; subject = Subject.find(1) # find by id or primary key
&gt; subject.name = &quot;New Subject&quot;
&gt; subject.save
```

Using approach 2,

```shell
$ rails console
&gt; subject = Subject.find(2) # find by id or primary key
&gt; subject.update(:name =&gt; &quot;New Subject&quot;, :position =&gt; 2)
```

### Delete records using ActiveRecord

1. find -&gt; destroy

```shell
$ rails console
&gt; subject = Subject.find(2) # find by id or primary key
&gt; subject.destroy
```

### Find records using ActiveRecord

Primary Key Finder: `Subject.find(2)` will return an object or an error.

Condition: `Subject.where(:visible =&gt; true)` will help to filter.

Note: for dynamic data (eg. user&apos;s input), be careful.

```shell
User.where(&quot;first_name LIKE #{@query}&quot;) # SQL Injection can happen
User.where([&quot;first_name LIKE ?&quot;, @query]) # SQL sanitization
```

If you want to find first, `Subject.where(:visible =&gt; true).first`
It will return an object or `nil`

Other conditions would be

```shell
Subject.order(&apos;position ASC&apos;)
Subject.limit(20)
Subject.offset(100) # skip 100 results
```

### One-to-many assocations

```ruby
class Subject
    has_many :pages
end

class Page
    belongs_to :subject
end
```

After linking between two tables, we can then use it:

```shell
subject.pages
subject.pages &lt;&lt; page
subject.pages.delete(page)
subject.pages.empty?
subject.pages.size
```

## CRUD

For most web application, we will have Create, Read, Update and Delete operations.

To create a controller,

```ruby
rails generate controller Subjects
```

This will create the controller under `app/controllers/subjects_controller.rb`.

```ruby
class SubjectsController &lt; ApplicationController

    def index
        # list of records
    end

    def show
        # a single record
    end

    def new
        # display new form
    end

    def create
        # process new form
    end

    def edit
        # display edit form
    end

    def update
        # process edit form
    end

    def delete
        # display delete form
    end

    def destroy
        # process delete form
    end
end
```

These methods will be linked to the `routes.rb` under `config`.

```ruby
Rails.application.routes.draw do

    get &apos;subjects/index&apos;
    get &apos;subjects/show&apos;
    get &apos;subjects/new&apos;
    get &apos;subjects/edit&apos;
    get &apos;subjects/delete&apos;

end
```

## REST

REST stands for Representational state transfer. Using REST, we are going to perform state transformations upon resources.

Here are some REST HTTP verbs.
`GET` - Retrieve items from resource
`POST` - Create new item in resource
`PATCH` - Update existing item in resource
`DELETE` - Delete existing item in resource

### Resourceful routes

In part 1, we discussed about 3 other routes and now, we are going to look at resourceful routes. It is the combination of RESTful and CRUD and it is Rails default.

It is used by most professional Rails developers and optimized for REST.

| HTTP Verb | URL | Action | Description |
| --------- | --- | ------ | ----------- |
| GET | /subjects | index | show all items |
| GET | /subjects/:id | show | show item with :id |
| GET | /subjects/new | new | show new form |
| POST | /subjects | create | create an item |
| GET | /subjects/:id/edit | edit | show edit form for item with :id |
| PATCH | /subjects/:id | update | update item with :id |
| GET | /subjects | delete | show delete form for item with :id |
| DELETE | /subjects | destroy | delete item with :id |

To enable this behavior, rails make it easy. To get it,

```rub
# config/routes.rb

resources :subjects
```

### Omitting resourceful routes

If you don&apos;t want to use the default, you could also modify:

```rub
# config/routes.rb

# all except show action
resources :subjects, :except =&gt; [:show]

# only these
resources :users, :only =&gt; [:index, :show]

# additional route
resources :subjects do

    member do
        get :delete # GET /subjects/:id/delete
    end

    collection do
        get :export # GET /subjects/export
    end

end

```

### Using resourceful URL helper

```ruby
&lt;%= link_to(&apos;All Subjects&apos;, subjects_path) %&gt;
&lt;%= link_to(&apos;Show Subject&apos;, subjects_path(@subject.id) ) %&gt;
&lt;%= link_to(&apos;Edit Subject&apos;, edit_subjects_path(@subject) ) %&gt;
```

This will help to shorten in format.

```ruby
{ :controller =&gt; `subjects`, :action =&gt; `show`, :id =&gt; 5 }

# can be shorten as
subject_path(5)
```

| HTTP Verb | URL | Action | Helper |
| --------- | --- | ------ | ----------- |
| GET | /subjects | index | subjects_path |
| GET | /subjects/:id | show | subject_path(:id) |
| GET | /subjects/new | new | new_subject_path |
| POST | /subjects | create | subjects_path |
| GET | /subjects/:id/edit | edit | edit_subject_path(:id) |
| PATCH | /subjects/:id | update | subject_path(:id) |
| GET | /subjects/:id/delete | delete | delete_subject_path(:id) |
| DELETE | /subjects/id | destroy | subject_path(:id) |</content:encoded><category>learning</category><category>ruby on rails</category></item><item><title>Ruby on Rails (part 1)</title><link>https://htswe.github.io/blog/ruby-on-rails-part-1/</link><guid isPermaLink="true">https://htswe.github.io/blog/ruby-on-rails-part-1/</guid><description>Ruby is an object oriented programming language, invented by Yukihiro Matsumoto in 1995. Ruby on Rail is an open-source web application framework, created by David Heinemeier Hansson in 2003.</description><pubDate>Fri, 23 Aug 2024 00:00:00 GMT</pubDate><content:encoded>## What is Ruby on Rails

### Introduction

Ruby on rail is made up of 2 parts.

* Ruby is an object oriented programming language, invented by Yukihiro Matsumoto in 1995.
* Ruby on Rail is an open-source web application framework, created by David Heinemeier Hansson in 2003.

Rails framework also has many default features built in, especially web security features.

### MVC architecture

The Ruby on Rails framework uses an MVC architecture. The M stands for model, the V stands for view, and the C stands for controller. The model refers to the data objects that we use. The view is the presentation layer. It&apos;s what the user sees and interacts with, the webpages, the HTML, the CSS, and the JavaScript. The controller processes and responds to user events, such as clicking on links and submitting forms. The controller will make decisions based on the request and then control what happens in response. It controls the interaction with our models and our views.

## Getting started

### Create new project

`$ rails new simple_app -d mysql`
The above command line creates a new project and configure it to use the mySQL database.

### Configure

Look for `config` directory. check out `application.rb`. `/config/initializers` is where the initialization stuffs take place, right at boot. `environment` is where we keep configuration for each environment. `database.yml` is where database configurations are stored for different environment.

### Access project from a browser

From command line: `$rails server` or `$rails s` to start the server.
From web, visit `localhost:3000`

### Rails architecture

![rail-architecture](/assets/images/rail-architecture.png)

### Routing

 The routes file is stored in `config/routes.rb`.

* Simple match route
* Default route
* Root route
* Resourceful route

#### Simple match route

```ruby
get &quot;demo/index&quot; #shorthand

match &quot;demo/index&quot;, :to =&gt; &quot;demo#index&quot;, :via =&gt; :get
```

we&apos;re mapping this string to the demo controller and the index action and we&apos;re going to do it using a `get` request.

### Default route

```ruby
get &apos;:controller(/:action(/:id))&apos;

match &apos;:controller(/:action(/:id))&apos;, :via =&gt; :get
```

eg. `GET /students/edit/52`, it is going to `StudentsController`, `edit` action and `52` as its id.

Default route was the widely used in early version, but Resourceful route is getting more popular these days.

### Root route

```ruby
root &quot;demo#index&quot;
match &quot;/&quot;, :to =&gt; &quot;demo#index&quot;, :via =&gt; :get
```

if it matches nothing, it will match to the root.

## Controller, Views and Dynamic Content

### Render

default behavior is rendering the template matching the current controller and action.

For example, we want to have a default behavior on `hello` route

```ruby
class DemoController &lt; ApplicationController
    layout false

    def index
    end

    def hello
    end
end
```

route is `get demo/hello`.
action is `hello` method inside `DemoController`.
view is `demo/hello.html.erb`.

if you want different template, use `render`.

```ruby
render(:template =&gt; &apos;demo/not_default&apos;)
render(&apos;demo/not_default&apos;) # shorthand
render(&apos;not_default&apos;) # if it is under same controller
```

### Redirect

They can also redirect or send the user to a different controller and action. Imagine this scenario, a user requests a web page that&apos;s inside a password protected area.

When you redirect, what actually happens is that rails returns a status code to the browser which looks like this.

```shell
HTTP/1.1 302 Found
Location: http://localhost:3000/demo/hello
```

The location is the new URL we want the browser to try. When browsers receive this response, they automatically make a new request for this new URL.

In rails, you could do,

```ruby
redirect_to(:controller =&gt; &apos;demo&apos;, :action =&gt; &apos;index&apos;)
redirect_to(controller: &apos;demo&apos;, action: &apos;index&apos;)
redirect_to(:action =&gt; &apos;index&apos;)
redirect_to(&apos;https://wikipedia.com&apos;)
```

### ERB Template

```ruby
&lt;% code %&gt; # execute without output
&lt;%= code %&gt; # execute with output
```

### Instance variable

To share the instance variable to other components in MVC architecture, use `@`.

```ruby
# DemoController
def hello
    @array = [1, 2, 3, 4, 5]
end
```

```ruby
# hello.html.erb

&lt;% @array.times do |n| %&gt;
    &lt;p&gt;&lt;%= n %&gt;&lt;/p&gt;

```

### Link

```ruby
&lt;%= link_to(text, target) %&gt;
```

## Database and Migration

You can use either SQL command or Ruby migration command. If you want to test if your project is able to connect to the database as the user,

```shell
rails db:schema:dump
```

### Generate migration

```ruby
rails generate migration MigrationName
```

Another handy usecase is to generate model.

```ruby
rails generate model ModelName
```

When you generate a general migration, a new file will be created in `db/migration` directory.

```ruby
class MyMigration &lt; ActiveRecord::Migration(6.0)

    def change
    end

end
```

`change` method consists of two methods, `up` and `down`. Ruby on Rails is smart enough to know that you are migrating up or down, therefore, it will reverse automatically according to your code inside `change` method. However, if you have different steps for `up` and `down`, you may also specify it by yourself.

```ruby
class MyMigration &lt; ActiveRecord::Migration(6.0)

    def up
    end

    def down
    end

end
```

Here are some common methods:
`create_table`, `add_column`,
`drop_table`, `remove_column`,
`rename_table`, `rename_column`

Next, we will see the model generation.

```shell
rails generate model User first_name:string last_name:string email:string
```

This will create all necessary files for `User` model with the parameters such as `first_name`, `last_name` and `email`. It also generate the test files and model files as well.

To execute them,

```shell
$rails db:migrate
```

This will execute all the migration scripts and update the database.

### Run migration

Here are some useful rails commands.

```shell
# this will show the current status
rails db:migrate:status

# this resets to initial version
rails db:migrate VERSION=0

# this will migrate until the specified version
rails db:migrate VERSION=202408242545324
```

### Foreign key

If you want to have foreign key, we could manually edit the file with `t.belongs_to`. It is a shortcut and if you are looking for longer form, `t.integer :student_id, index: true` or `t.references :student`.

```ruby
class User &lt; ActiveRecord::Migration[6.0]

    def change
        create_table :user do |t|
            t.belongs_to :student
            t.string :first_name
            t.string :last_name
            t.string :email
            t.timestamps
        end
    end
end
```</content:encoded><category>learning</category><category>ruby on rails</category></item><item><title>Learning from Crucial Conversation</title><link>https://htswe.github.io/blog/learning-from-crucial-conversation/</link><guid isPermaLink="true">https://htswe.github.io/blog/learning-from-crucial-conversation/</guid><description>This post is an extraction of some lessons from the book, &quot;Crucial Conversation&quot;. It is one of the books that also helped me in my career.</description><pubDate>Mon, 01 Jul 2024 00:00:00 GMT</pubDate><content:encoded>### About this book

This post is an extraction of some lessons from the book, &quot;Crucial Conversation&quot;. It is one of the books that also helped me in my career.

### Who should read

The book might be dry and there are many lessons to be learnt from the book. So, definitely it is one of the books that I have read again and again after some times. The good news is that I could borrow an ebook easily from national library in Singapore.

This book is useful for anyone. In fact, if you are struggling with how to get into or navigate during crucial conversation, this book is a book that you should definitely read it.

I took some notes just like the previous one, [team of teams](/leadership/notes-team-of-teams/), however, I am quite surprised later that it has more than 1 hour of reading. So I decided to break it down into a byte-sized article instead. If you want to read more, check out the &quot;Crucial Conversation&quot; tag.

### Disagree using **ABC**s

Now, you are inside the discussion and there is something that you disagree. How do you disagree?

When you want to disagree, use **ABC** response.

**A**gree - If you agree with some of what was said, respond by identifying what you agree with. Instead of saying &quot;I disagree,&quot; you should have said, &quot;Mike, I agree that we should do xyz.&quot; This will provide you a situation where the other person will be less defensive.

**B**uild - If you agree and want to add to it, build on their idea. &quot;I agree we should to do xyz. I also think we should do 123.&quot; Building on someone&apos;s else idea, will give you some supports.

**C**ompare - If you disagree with what was said, don&apos;t attack, criticize, or disagree. Rather, compare your opinion. This is often best done by first paraphrasing the other person&apos;s idea, then sharing your own. For example, &quot;Mike, you think we should do xyz. Is that right? I think we should do 123.&quot;

### Paraphrase and Priming

Both paraphrase and prime can produce immediate and measurable impact on an **interaction**, Paraphrase is more well-known than prime.

What is paraphrase? **Paraphrase** is simply taking time *to repeat back* what you&apos;ve heard. It could have a big impact on others. Instead of formulating a response, focus on what is being said. It is not only important that you use this skill, but how you use this skill.

By paraphrasing, the message you want to send is not only that you are *staying on track with conversation*, but also that you are okay with what is being shared.

**Priming** is by paraphrasing with a little *inference*. Priming is where empathy and paraphrasing meet. To do well, you need to put yourself in the other&apos;s position, take what&apos;s been shared, and make an educated guess as to how they are thinking and feeling about the topic. For example, you ask: &quot;It sounds like you&apos;ve experienced things from me that make you think I have a grudge about how things went at the end. Is that right? What have I done that looked like that?&quot;

### Make it safe by using Contrasting

While you want to keep dialogue consists of the free flow of meaning, that would stop when one feels a lack of safety. If you noticed that you and the others have moved away from dialogue, you need to do something to make it safer.

&gt; If you simply understand that **your challenge is to make it safer** during dialogue, 9 out of 10 times, you&apos;ll intuitively do something that helps.

The action could be as simple as by asking a question or showing interest in others&apos; views. Apologies, smiles, even a request of a short &quot;time-out&quot; can help restore safety. The main idea is to make it safe for everyone, so the dialogue could be effective.

One of the methods is by using Contrasting. For example, if you want to talk about something personal about him, you might start your conversation: &quot;Mike, I wanna discuss something about your behavior. I don&apos;t intend to hurt your feelings. I want to share something that could be helpful for your own. Could I share with you?&quot; Establish Mutual Purpose. Let the other person know your intentions are honorable.

And of course, in any time during the dialogue, if you noticed that safety is getting compromised, you need to do something to make it safer again.

### Conclusion

There are many wisdoms and sharing of approaches in crucial conversation. You may be scared and struggling in the beginning. But the more you practice, the better you will be.</content:encoded><category>thoughts</category><category>learning</category><category>soft-skill</category><category>crucial conversation</category></item><item><title>What I learnt from Team of Teams</title><link>https://htswe.github.io/blog/notes-team-of-teams/</link><guid isPermaLink="true">https://htswe.github.io/blog/notes-team-of-teams/</guid><description>This book is written by ex US army general and the story is mainly how US adapt to the new war between the AQI and US intelligence units. It gives a good insight about the struggle and how it overcam…</description><pubDate>Sun, 30 Jun 2024 00:00:00 GMT</pubDate><content:encoded>### About this book

This book is written by ex US army general and the story is mainly how US adapt to the new war between the AQI and US intelligence units. It gives a good insight about the struggle and how it overcame to respond to the threats. It also outlined the history of wars, industry revolution and how the information and communication become so critical in information age.

### Who should read

Initially, I was worried that a book about war. I personally prefer reading interesting stories, and this book turned out to be one of the good books to read. Not everyone of us are working in military or able to relate to war. But some of us work in big or small government or private corporations.

This book gives a good overview of what it feel to be working in a big organization with thousands of people with different cultures and backgrounds. If you are a person who is struggling with cross team communication, this book could be a good book to learn.

### My random notes and thoughts

There is no particular orders, but I took some notes along the way so that I could discuss it with my mentor.

#### 1. A new challenge in interconnected world

&gt; In place of maps, whiteboards began to appear in our headquarters. Soon they are everywhere. Standing around them, markers in hand, we thought out loud, diagramming what we knew, what we suspected, and what we did not know. We covered the bright white surfaces with multi-colored words and drawings, erased, and then covered again.
&gt;
&gt; _Whiteboards (pg 24)_

---
&gt; As network theorist and military analyst John Arquilla put it: We killed &quot;about 20 of Al Qaeda&apos;s &apos;number threes&apos; over the past decade, but everyone in the network is number three. To our way of thinking, an organization without a predictable methodology or clear chain of command wasn&apos;t really an organization at all. But it didn&apos;t. It continued to function as persistently and implacably as ever, demonstrating a coherence of purpose and strategy.
&gt;
&gt; _Whiteboards (pg 26)_

---
&gt; At its heart, Nelson crafted an organizational culture that rewarded individual initiative and critical thinking, as opposed to simple execution of commands.
&gt;
&gt; _Managing chaos (pg 31)_

---

#### 2. Is it a science problem?

&gt; Taylor became fascinated by the contrast between the scientific precision of the machine in the shop and the remarkably unscientific processes that connected the human to these beautiful contraptions.
&gt;
&gt; There was no explanation. &quot;It was a tradition,&quot; he wrote. &quot;It had no scientific basis.&quot; Each worker had developed his own system of hammering, melting, and hardening, of work and breaks, etc., which each believed to be superior to that of his colleagues. Because there was no forum for comparing their outputs, everyone could continue to operator under the belief that his own system was best. They could not all be right, Taylor thought -- there must be _one best way_.
&gt;
&gt; After two years of struggle, he had an epiphany: he would not make them work harder -- he would show them that it could be done and then have everyone do exactly that.
&gt;
&gt; _The perfect step (pg 39)_

---
&gt; The structures of our organizations reflect this ideal. Whether imbued with a &quot;lazy worker&quot; Theory X or a &quot;motivated worker&quot; Theory Y disposition, the &quot;org charts&quot; of most multiperson endeavors look pretty similar: a combination of specialized vertical columns (departments or divisions) and horizontal tiers that denote levels of authority, with the most powerful literally on top -- the only tier that can access all columns.
&gt;
&gt; Taylor&apos;s system of reductionist planning lent itself naturally to a new generation of neat and tidy hierarchies. Peter Ducker argued that Taylor, more than Karl Marx, deserves a place in the pantheon of modern intellectual thought alongside Darwin and Freud.
&gt;
&gt; _We have other men paid for thinking (pg 47)_

---

#### 3. What went wrong actually?

&gt; Lorenz presented a paper, &quot;Does the Flap of a Butterfly&apos;s Wings in Brazil Set Off a Tornado in Texas?&quot; The phrase &quot;the butterfly effect entered the world&quot;
&gt;
&gt; Being ___complex___ is different from being ___complicated___. Things that are complicated may have many parts, but those parts are joined, in relatively simple ways. They ultimately can be broken down into a series of neat and tidy deterministic relations.
&gt;
&gt; Complexity, on the other hand, occurs when the number of interactions between components increases dramatically -- the interdependencies that allow viruses and bank runs to spread; this is where things quickly become unpredictable.
&gt;
&gt; _Comets and cold fronts (pg 56)_

---
&gt; Complex systems are fickle and volatile, presenting a broad range of possible outcomes; the type and sheer number of interactions prevent us from making accurate predictions. As a result, treating an ecosystem as though it were a machine with predictable trajectories from input to output is a dangerous folly.
&gt;
&gt; _Square peg, round hole (pg 67)_

---

#### 4. Will sufficient data save the day?

&gt; &quot;Big Data&quot;, data rich records can be wonderful for explaining how complex phenomena happened and how they might happen, but they can&apos;t tell us when and where they will happen. For instance, data on the spread of virus can provide an insight into how contagion patterns look in our networked world, but that is very different from knowing exactly where the next outbreak will occur. Gaining understanding is not always the same as predicting.
&gt;
&gt; _Big data will not save us (pg 72)_

---
&gt; &quot;Resilience thinking&quot; is a burgeoning field that attempts to deal in new ways with the new challenges of complexity. In a resilience paradigm, managers accept the reality that they will inevitably confront unpredicted threats; rather than erecting strong, specialized defenses, they create systems that aim to roll with the punches, or even benefit from them. Resilient systems are those that can encounter unforeseen threats and, when necessary, put themselves back together again.
&gt;
&gt; As environmentalists David Salt and Brian Walker explain in their book _Resilience Thinking_, &quot;Humans are great optimizers. We look at everything around us, whether a cow, a house, or a share portfolio, and ask ourselves how we can manage it to get the best return. [but] the more you optimize elements of a complex system of humans and nature for some specific goal, the more you diminish that system&apos;s resilience.
&gt;
&gt; _The threat from behind (pg 79)_

---

#### 5. Trust is the ingredient

&gt; This is about more than the feel-good effects of &quot;bonding&quot;. It is done because teams whose members know one another deeply perform better. Any coach knows that these sorts of relationships are vital for success. A fighting force with good individual training, a solid handbook, and a sound strategy can execute a plan efficiently, and as long as the environment remains fairly static, odds of success are high. But a team fused by trust and purpose is much more potent. Such as group can improvise a coordinated response to dynamic, real-time developments.
&gt;
&gt; _Get a swim buddy (pg 98)_

---
&gt; The difference between command and control on the one hand, and adapt and collaborate on the other, was the difference between success and failure. The proliferation of teams across a diversity of complex environments -- from special operations to trauma care -- evidences their ability to thrive in the midst of the sort of challenge that our Task Force faced.
&gt;
&gt; We have honed the traits of trust and purpose at the team level, but our organization at large was the complete opposite -- it was a classic command.
&gt;
&gt; _Charm school (pg 114)_

---

#### 6. Something is still missing

&gt; Each team exhibited horizontal bonds of trust and a common sense of purpose, but the only external ties that mattered to each team ran vertically, connecting it to the command superstructure, just like workers on an assembly line. Meaningful relationships between teams were nonexistent.
&gt;
&gt; In MECE (mutually exclusive and collectively exhaustive) structure, two VPs or two workers are designed to exist independently -- they do not need to know each other, they do not even need to speak the same language.
&gt;
&gt; _MECE (pg 118)_
&gt;
&gt; The teams were operating independently -- like workers in an efficient factory -- while trying to keep pace with an interdependent environment. We all knew intuitively that intelligence gathered would almost certainly impact what our operators saw on the battlefield, and that battlefield details would almost certainly represent valuable context for intel analysis, but those elements of our organization were not communicating with each other.
&gt;
&gt; We could try to solve it with a triage plan for relaying and processing data, but that would be like responding United 173 with a specific technical procedure for landing gear malfunction. At best, we would solve one particular problem; at worst we would increase paperwork.
&gt;
&gt; The choke point existed not because of insufficient guidance from above, but because of a dearth of integration.
&gt;
&gt; To fix the choke point, we needed to fix the management system and organizational culture that created it. As soon as we looked at our organization through the lens of the team structure -- searching for weakness in horizontal connectivity rather than new possibilities for top-down planning. We referred to them as &quot;blinks&quot;.
&gt;
&gt; Stratification and silos were hardwired throughout the Task Force. Although all our units resided on the same compound, most lived with their &quot;kind&quot;, some used different gyms, units controlled access to their planning areas, and each tribe had its own brand of standoffish superiority complex. Resources were shared reluctantly. Our forces lived a proximate but largely parallel existence.
&gt;
&gt; Until we fixed the blinks, we would not be fully effective. We needed operational teams to gather, organize, and relay data to analysts. Simultaneously, we needed to disseminate the relevant takeaways to the thousands of people in our organization; and we needed administrative higher-ups to modify operations and allocate resources based on the analysis.
&gt;
&gt; _MECE (page 122)_

---

#### 7. Building trust at a large scale

&gt; Small teams are effective in large part because they are small -- people know each other intimately and have clocked hundreds of hours with each other. In large organizations most people will inevitably be strangers to one another. In fact, the very traits that make teams great can often work to prevent their _coherence_ into a broader whole.
&gt;
&gt; How does one build a team with seven thousand swim buddies?
&gt;
&gt; _Commands of teams (pg 126)_

---
&gt; _Diminishing marginal returns_ -- With most goods and services, each additional unit brings less value or gratification than the one before: a sandwich will bring a very hungry man great satisfaction. The second sandwich will bring some happiness, the third a little less, and the tenth will probably be difficult to eat and might make you sick. As it relates to manpower, this is know as the problem of &quot;too many cooks in the kitchen.&quot;
&gt;
&gt; _The point at which everyone else sucks (pg 126)_
---
&gt; British anthropologist Robin Dunbar theorized that the number of people an individual can actually trust usually fall between 100 and 230. This limitation leads to a kind of tribal competitiveness.
&gt;
&gt; The goal becomes to accomplish missions better than the team that bunks on the other side of the base, rather than to win the war. In other words, the magic of teams is a double-edged sword once organizations get big: some of the same traits that make an adaptable team great can make it incompatible with the structure it serves.
&gt;
&gt; _The point at which everyone else sucks (pg 127)_

---
&gt; &quot;As a team gets bigger, the number of links that need to be managed among members goes up at an accelerating, almost exponential rate.&quot; In his handbook _Leading Teams_, Hackman reminds us of &quot;Brook&apos;s Law&quot;: the adage that adding staff to speed up a behind-schedule project &quot;has no better chance of working ... than would a scheme to produce a baby quickly by assigning nine women to be pregnant for one month each ... adding manpower to a late software project makes it later.&quot;
&gt;
&gt; _The point at which everyone else sucks (pg 128)_

---
&gt; On a single team, every individual needs to know every other individual in order to build trust, and they need to maintain comprehensive awareness at all times in order to maintain common purpose -- easy with a group of twenty-five, doable with a group of fifty, tricky above one hundred and definitely impossible across a task force of seven thousand.
&gt;
&gt; We don&apos;t need every member of the Task Force to know everyone else; we just needed everyone to know _someone_ on every team, so that when they thought about, or had to work with, the unit that bunked next door or their intelligence counterparts in D.C., they envisioned a friendly face rather than a competitive rival.
&gt; We needed to enable a team operating in an interdependent environment to understand the butterfly-effect ramifications of their work and make them aware of the other teams with whom they would have to cooperate in order to achieve strategic success.
&gt;
&gt; _Team of teams (pg 129)_

---
&gt; Effective prediction has become increasingly difficult, and in many situations impossible. Continuing to function under the illusion that we can understand and foresee exactly wthat will be relevant to whom is hubris. It might feel safe, but it is the opposite. Functioning safely in an interdependent environment requires that every team possess a holistic understanding of the interaction between all the moving parts. Everyone has to see the system in its entirety for the plan to work.
&gt;
&gt; _The &quot;need to know&quot; fallacy (pg 141)_

---

#### 8. Building a shared platform for everyone

&gt; NASA -- all data were on display in a central control room that had links with automated displays to Apollo field centers. These rooms buzzed with activity, constantly receiving updates from contractors and teams and in turn providing information to them. As the utility of this information became evident, more and more engineers who were initially opposed started to come around.
&gt;
&gt; The reason that it worked and that we got it ready on schedule was because we had everybody in that room that we needed to make a decision ... it got to appoint where we could identify a problem in the morning and by the close of business we could solve it, get the money allocated, get the decisions made, and get things working.
&gt;
&gt; This approach, contrary to reductionism, believes that one cannot understand a part of system without having at least a rudimentary understanding of the whole. It was the organizational manifestation of this insight that imbued NASA with the adaptive, emergent intelligence it needed to put a man on the moon.
&gt;
&gt; _New metal alloys, some of which have not yet been invented (pg 149)_

---
&gt; Consider a doctor and her education. Doctors come in many varieties -- pediatricians, ENTs, radiologists, etc, yet while in medical school, all undergo the same rigorous overview of the way the human body works. Because the human body is not a set of independent elements, but a system of interdependent elements, you need to understand how the metabolism of sugar works in order to understand how diabetes can cause the death of issue in fingers.
&gt;
&gt; _Sets and systems (pg 152)_

---
&gt; How we organize physical space says a lot about how we think people behave; but how people behave is often a by-product of how we set up physical space. At Balad we needed a space that facilitated not the orderly, machine like flow of paperwork, but the erratic, networked flow of ideas -- an architecture designed not for separation, but for the merging of worlds. We weren&apos;t the only ones to be trying this -- there was a growing movement in the private sector to organize offices for better cooperation, too.
&gt;
&gt; In Silicon Valley, Google, Facebook, and other titans, as well as countless start-ups, use open plans that put different teams and different rungs of management in the same space.
&gt;
&gt; _Brains out of the footlocker (pg 159)_

---

#### 9. Mistrust, Doubt and Leak

&gt; The O&amp;I, as it was commonly called, is standard military practice: a regular meeting held by the leadership of a given command to integrate everything the command is doing with everything it knows.
&gt;
&gt; In early days, only the CIA liaison&apos;s seat was occupied. Intuitively, we knew that if we could generate enough success on the battlefield, others would want to participate. The problem was how to get their participation up front. We needed to bind everyone into a single enterprise, but we had no explicit authority to do so.
&gt;
&gt; One partner agency offered the same response every day for the first year of our experiment: &quot;Nothing new to report on our end.&quot;
&gt;
&gt; In time, people came to appreciate the value of systematic understanding. O&amp;I attendance grew as the quality of the information and interaction grew. Eventually, we had seven thousand people attending almost daily for up to two hours.
&gt;
&gt; _The O&amp;I, pushback, success (pg 168)_

---
&gt; Massive leaks are not an inevitable consequence of the current level of information sharing, but even if they were, the benefits vastly outweigh the potential costs. The sharing of information within US intelligence community since 9/11 has saved many lives and done far more good than the damage from incidents like the Manning and Snowden leaks has done harm.
&gt;
&gt; _What about wikileaks? (pg 171)_

---

#### 9. Forced Exchange

&gt; One of the most controversial moves was our embedding program, an exchange system we began in late 2003 in which we would take an individual from one team -- say, an Army Special Forces operator -- and assign him to a different part of our force for six months -- a team of SEALs, for example, or a group of analysts. Our hope was that, by allowing our operators to see how the war looked from inside other groups, and by building personal relationships, we could build between teams some of the fluency that traditionally exists within teams.
&gt;
&gt; Predictably, initial resistance was intense. &quot;Our teams train in entirely different ways,&quot; I was informed.
&gt;
&gt; Although it was a &quot;forced&quot; initiative, once the mandate was in place, elite units were naturally incentivize to send their best operators and leaders. Over time, he would also begin to see some of the positives of the alternative approach. As an added bonus, they would see their newfound friend as representative of the entire unit. When these operators returned to their home unit, their positive comments on the rival unit would spread, deepening the ties between teams. Slowly, we grew the bonds of trust needed for us to overcome our Prisoner&apos;s Dilemma.
&gt;
&gt; _Walk a mile in an analyst&apos;s shoe (pg 177)_

---
&gt; When asking for LNO nominations to fill critical positions, we used two criteria:
&gt;
&gt; (1) if it doesn&apos;t pain you to give the person up, pick someone else
&gt;
&gt; (2) if it is not someone whose voice you&apos;ll recognize when they call you at home at 2am, pick someone else.
&gt;
&gt; Previously, we might have made decisions based on rank, position, or where people wanted to go in their careers. But to get this right, _Personal qualities trumped everything else_.
&gt;
&gt; _Walk a mile in an analyst&apos;s shoe (pg 178)_

---

#### 10. Two essential ingredients

&gt; Fostering such engagement is more easily said than done. Almost every company has posters and slogans urging employees to &quot;work together&quot;, but simply telling people to &quot;communicate&quot; is the equivalent of Taylor&apos;s telling his workers to &quot;do things faster&quot;, and stopping there.
&gt;
&gt; It is necessary, we found, to forcibly dismantle the old system and replace it with an entirely new managerial architecture. Our new architecture was shared consciousness, and it consisted of two elements.
&gt;
&gt; The first was extreme, participatory transparency -- the &quot;system management&quot; of NASA that we mimicked with our O&amp;I forums and our open physical space. This allowed all participants to have a holistic awareness equivalent to the contextual awareness of ___purpose___ we already knew at a team level.
&gt;
&gt; The second was the creation of strong internal connectivity across teams -- something we achieved with our embedding and liaison programs. This mirrored the ___trust___ that enabled our small teams to function.
&gt;
&gt; _Decentralized operations with coordinated control (pg 197)_

---

#### 11. Mindset shift for the leader

&gt; In short, when they can see what&apos;s going on, leaders understandably want to control what&apos;s going on. Empowerment tends to be a tool of last resort. We can call this tethering of visibility to control the &quot;Perry Principle&quot;.
&gt;
&gt; Taylor&apos;s contemporary Henri Fayol enumerated the &quot;five functions of management&quot; as &quot;planning, organizing, commanding, coordinating and controlling&quot;. The last three become much easier to attend to when you have more information, creating a cycle of seeking ways to gather and centralize more information in order to push more and more efficient directives to the organization. The function of workers is to feed this cycle and await the next commands.
&gt;
&gt; Today&apos;s managers have access to all kinds of information their employees that they lacked just a few years ago. Automated systems at restaurants monitor waiters&apos; movements, tracking every ticket, dish, and drink, searching for patterns that suggest efficacy as well as those correlated to theft. All of this enables the habitual centralization of power.
&gt;
&gt; _All under the guns of his ships (pg 208)_

---
&gt; I begin to reconsider the nature of my role as a leader. The wait for my approval is not resulting in any better decisions, and our priority should be reaching the best possible decision that could be made _in a time frame that allowed it to be relevant_.
&gt;
&gt; The practice of relaying decisions up and down the chain of command is premised on the assumption that the organization has the time to do so, or, more accurately, that the cost of the delay is less than the cost of the errors produced by removing a supervisor. The risk of acting too slowly were higher than the risks of letting competent people make judgement calls.
&gt;
&gt; _All under the guns of his ships (pg 209)_

---
&gt; A piece of this is the psychology of decision making. An individual who makes a decision becomes more invested in its outcome. Another factor was that, for all our technology, our leadership simply did not understand what was happening on the ground as thoroughly as the people who were there.
&gt;
&gt; The key reason for the success of empowered execution lay in what had come _before_ it: the foundation of shared consciousness.
&gt;
&gt; _All under the guns of his ships (pg 215)_

---

#### 12. Becoming a gardener

&gt; From a distance, the Task Force&apos;s fight in Iraq in 2004 looked like chess. But the chess metaphor quickly broke down. The enemy could move multiple pieces simultaneously or pummel us in quick succession, without waiting respectfully for our next move.
&gt;
&gt; Years later as Task Force commander, I began to view effective leadership in the new environment as more akin to gardening than chess. The move-by-move control that seemed natural to military operations proved less effective than nurturing the organization -- its structure, processes, and culture -- to function with &quot;smart autonomy&quot;. It allowed those forces to be enabled with a constant flow of &quot;shared consciousness&quot; from across the force, and it freed them to execute actions in pursuit of the overall strategy as best they saw fit.
&gt;
&gt; _Chess master to gardener: the leaders we now need (pg 225)_

---
&gt; Leading as a gardener meant that I kept the Task Force focused on clearly articulated priorities by explicitly talking about them and by leading by example. It was impossible to separate my words and my actions, because the force naturally listened to what I said, but measured the importance of my message by observing what I actually did.
&gt;
&gt; The gardener (pg 226)

---
&gt; For the same reasons, the O&amp;I was never canceled and attendance was mandatory. I felt that if the O&amp;I was seen as an occasional event not always attended by key leaders, it would unravel.
&gt;
&gt; I wanted the O&amp;I to be a balance of reporting key information and active interaction. That didn&apos;t come naturally, particularly across a digital medium. The participants came from different organizational cultures, were thousands of miles apart, and had never met in person. Getting candor under those conditions was not easy, but we made it work. When necessary, I would pre-plan questions or comments and plant them with trusted partners to help demonstrate to everyone what I wanted the O&amp;I to be.
&gt;
&gt; The gardener (pg 227)

---
&gt; When their turns came and their faces suddenly filled the screen I made it a point to greet them by their first name, which often caused them to smile in evident surprise. They were eight levels down the chain of command and many miles away -- how did the commanding general know their names? Simple: I had my team prepare a &quot;cheat sheet&quot; of the day&apos;s planned briefer so I could make one small gesture to put them at ease.
&gt;
&gt; At the conclusion, I&apos;d ask a question. The answer might not be deeply important, and often I knew it beforehand, but I wanted to show that I had listened and that their work mattered.
&gt;
&gt; For a young member, even if the brief had been terrible, I would compliment the report. Others would later offer them advice on how to improve -- but it didn&apos;t need to come from me in front of thousands of people. When we did it right, the people left the O&amp;I more confident about, committed to, and personally invested in our effort.
&gt;
&gt; The gardener (pg 228)

---
&gt; I adapted a practice I called &quot;thinking out loud&quot;, in which I would summarize what I&apos;d heard, describe how I processed the information and outline my first thoughts on what we should consider doing about it. After I did that, in a pointed effort to reinforce empowered execution, I would often ask the subordinate to consider what action might be appropriate and tell me what he or she planned to do.
&gt;
&gt; Thinking out loud can be a frightening prospect for a senior leader. Ignorance on a subject is quickly obvious, and efforts to fake expertise are embarrassingly ineffective. I found, however, that asking seemingly stupid questions or admitting openly &quot;I don&apos;t know&quot; was accepted, even appreciated.
&gt;
&gt; The gardener (pg 229)

### Conclusion

Leading a team of teams is a formidable task. The heroic &quot;hands-on&quot; leader who relies on personal competence and will power will be overwhelmed by accelerating speed, swelling complexity and interdependence. We must learn to lead differently.

Creating and leading a truly adaptive organization requires building, leading and maintaining a culture that is flexible but also durable.

The primary responsibility of the new leader is to maintain a holistic, big picture view, avoiding a reductionist approach, no matter how tempting micromanaging may be.

As the world becomes more complex, the importance of leaders will only increase. Even AIs are unlikely to provide the will, moral courage and compassion that good leaders offer. Persuading teams to network with other teams will always be difficult, but this is a culture that can be planted and if maintained, can flourish.</content:encoded><category>thoughts</category><category>learning</category><category>soft-skill</category></item><item><title>Coroutine Launch vs Async</title><link>https://htswe.github.io/blog/coroutine-launch-vs-async/</link><guid isPermaLink="true">https://htswe.github.io/blog/coroutine-launch-vs-async/</guid><description>If you are new to coroutine or looking for the continuation, you could start from the previous article.</description><pubDate>Fri, 20 Oct 2023 00:00:00 GMT</pubDate><content:encoded>If you are new to `coroutine` or looking for the continuation, you could start from the previous article.

* [Coroutine Builders](/tech/coroutine-builders/)

In this article, we will look at `launch` and `async` for making network requests.

### Network Request using `launch`

We could use `launch` for network request in both sequentially and concurrently.

For sequentially,

```kotlin
fun performNetworkRequestsSequentially() {
    uiState.value = UiState.Loading

    viewModelScope.launch {
        try {
            val oreo = mockApi.getAndroid(27) // get oreo first
            val pie = mockApi.getAndroid(28) // then pie
            val a10 = mockApi.getAndroid(29) // then android10

            val result = listOf(oreo, pie, a10)
            uiState.value = UiState.Success(result)
        } catch(exception: Exception) {
            uiState.value = UiState.Error(&quot;Failed&quot;)
        }   
    }
}
```

For concurrently,

```kotlin
fun performNetworkRequestsConcurrently() = runBlocking&lt;Unit&gt; {
    launch {
        val result1 = networkCall(1)
    }

    launch {
        val result2 = networkCall(2)
    }
}

suspend fun networkCall(number: Int): String {
    delay(500)
    return &quot;Result $number&quot;
}
```

The above code runs the network calls in parallel. However, those results are not accessible outside `launch` coroutine since the return for `launch` is a `Job`.

To access both results, we will need to use `join()` and a shared mutable state.

```kotlin
fun performNetworkRequestsConcurrently() = runBlocking&lt;Unit&gt; {
    val resultList = mutableListOf&lt;String&gt;()

    val job1 = launch {
        val result1 = networkCall(1)
        resultList.add(result1)
    }

    val job2 = launch {
        val result2 = networkCall(2)
        resultList.add(result2)
    } 

    job1.join()
    job2.join()

    print(&quot;Result list: $resultList&quot;)
}

suspend fun networkCall(number: Int): String {
    delay(500)
    return &quot;Result $number&quot;
}
```

Although it works in above code, `resultList` is a shared mutable state. A general rule in concurrent programming is to avoid shared mutable state whenever possible.

### Difference between `launch` and `async`

&gt; `launch` returns `Job`. `async{}` returns `Deferred` (`Job` with `Result`).

Using `async`, the same functionality could be achieved without a shared mutable state.

```kotlin
fun performNetworkRequestsConcurrently() = runBlocking&lt;Unit&gt; {
    val deferred1 = async {
        val result1 = networkCall(1)
        result1
    }

    val deferred2 = async {
        val result2 = networkCall(2)
        result2
    } 

    val resultList = listOf(
        deferred1.await(),
        deferred2.await()
    )

    print(&quot;Result list: $resultList&quot;)
}

suspend fun networkCall(number: Int): String {
    delay(500)
    return &quot;Result $number&quot;
}
```

We could also add optional parameter to `async(start = CoroutineStart.LAZY)` and change to `deferred1.start()` to start lazily.

Let&apos;s try a little different using `async` to reflect some UI states. We will having `Loading` as well as `Error`.

```kotlin
fun performNetworkRequestsConcurrently()
{
    uiState.value = UiState.Loading

    val oreoDeferred = viewModelScope.async {
        mockApi.getAndroid(27)
    }

    val pieDeferred = viewModelScope.async {
        mockApi.getAndroid(28)
    }

    val a10Deferred = viewModelScope.async {
        mockApi.getAndroid(29)
    }

    viewModelScope.launch {
        try {
            awaitAll(oreoDeferred, pieDeferred, a10Deferred)
            uiState.value = UiState.Success()
        } catch (exception: Exception) {
            uiState.value = UiState.Error(&quot;Network Request Failed&quot;)
        }
        
    }
}
```

Using `awaitAll` for all the `Deferred` objects, we could make our code works. But if we do not know the exact number of network requests?

### Sequential unknown network requests

Imagine if we do not know the exact number of network requests and we want to make them run in sequential.

```kotlin
fun performNetworkRequestsSequentially() {
    uiState.value = UiState.Loading

    viewModelScope.launch {
        try {
            // this Api could return any number of android versions
            val recentVersions = mockApi.getRecentAndroidVersions()
            val recentFeatures = recentVersions.map { androidVersion -&gt; 
                mockApi.getAndroid(androidVersion.apiLevel)
            }
            uiState.value = UiState.Success(recentFeatures)
        } catch(exception: Exception) {
            uiState.value = UiState.Error(&quot;Failed&quot;)
        }   
    }
}
```

## Concurrent unknown network requests

What about concurrent style if we do not know the exact number of network requests?

```kotlin
fun performNetworkRequestsConcurrently()
{
    uiState.value = UiState.Loading
    viewModelScope.launch {
        try {
            val recentVersions = mockApi.getRecentAndroidVersions()
            val versionFeatures = recentVersions.map { androidVersion -&gt;
                async {
                    mockApi.getAndroid(androidVersion.apiLevel)
                }
            }.awaitAll()
            uiState.value = UiState.Success(versionFeatures)
        } catch (exception: Exception) {
            uiState.value = UiState.Error(&quot;Failed&quot;)
        }
    }
}
```

### Conclusion

Making network requests are often the usecase for `coroutine` and we look into it using `launch` and `async`. We also demonstrates sequential and concurrent request handling, highlighting the differences between the two approaches.

While `launch` will return `Job`, the use of `async` to obtain `Deferred` with wrapped results, simplifying result access.

We also explores handling both known and unknown sequential and concurrent network requests, emphasizing the flexibility and efficiency of coroutines in managing such scenarios. We hope this article provides a valuable understanding of how coroutines can effectively handle diverse network request scenarios.

Next, we will look into some useful higher-order functions from `coroutine`.</content:encoded><category>kotlin</category><category>asynchronous</category><category>coroutine</category></item><item><title>Coroutine Builders</title><link>https://htswe.github.io/blog/coroutine-builders/</link><guid isPermaLink="true">https://htswe.github.io/blog/coroutine-builders/</guid><description>Let&apos;s take a look at a simple kotlin program with a coroutine builder.</description><pubDate>Sun, 15 Oct 2023 00:00:00 GMT</pubDate><content:encoded>### Coroutine Builders

There are 3 coroutine builders:

1. `launch`
2. `async`
3. `runBlocking`

### Basic usage of `coroutine`

Let&apos;s take a look at a simple kotlin program with a coroutine builder.

```kotlin
fun main() {
    GlobalScope.launch {
        delay(500)
        println(&quot;printed from within Coroutine&quot;)
    }
    println(&quot;main end&quot;)
}
```

This will just print out the &quot;main end&quot; without waiting for the other print statement inside coroutine block. If we want the message to appear, one way is to add `Thread.sleep(&gt;500)`.

```kotlin
fun main() {
    GlobalScope.launch {
        delay(500)
        println(&quot;printed from within Coroutine&quot;)
    }
    Thread.sleep(1000)
    println(&quot;main end&quot;)
}
```

```bash
printed from within Coroutine
main ends
```

### `runBlocking`

The `Thread.sleep(ms)` is ugly, to avoid that, Coroutine has a builder for it called `runBlocking`. This will force the process to wait before it could end.

```kotlin
fun main() {
    runBlocking {
        launch {
            delay(500)
            println(&quot;printed from within Coroutine&quot;)
        }        
    }
}
```

This could be expressed as

```kotlin
fun main() = runBlocking {
    launch {
        delay(500)
        println(&quot;printed from within Coroutine&quot;)      
    }
}
```

This works okay if we do not plan to access the result from the coroutine inside `launch`. If we are expecting the result from coroutine, we could use the `Job` as Coroutine returns.

```kotlin
fun main() = runBlocking {
    launch {
        networkRequest()
        print(&quot;result received&quot;)
    }
    println(&quot;end of runBlocking&quot;)
}

suspend fun networkRequest(): String {
    delay(500)
    return &quot;Result&quot;
}
```

```bash
end of runBlocking
result received
```

When the above code runs, we noticed that `launch` is another coroutine and doesn&apos;t block the print statement for &quot;end of runBlocking&quot;. If we want the `launch` coroutine print statement to appear first, then we may need to use `Job`.

```kotlin
fun main() = runBlocking {
    val job = launch {
        networkRequest()
        print(&quot;result received&quot;)
    }
    job.join()
    println(&quot;end of runBlocking&quot;)
}

suspend fun networkRequest(): String {
    delay(500)
    return &quot;Result&quot;
}
```

```bash
result received
end of runBlocking
```

### `launch` with `LAZY`

Another way is to make the `launch` coroutine to `LAZY` type.

```kotlin
fun main() = runBlocking {
    val job = launch(start = CoroutineStart.LAZY) {
        networkRequest()
        print(&quot;result received&quot;)
    }
    // since it is LAZY, we could do other works
    delay(200)
    job.start()
    println(&quot;end of runBlocking&quot;)
}

suspend fun networkRequest(): String {
    delay(500)
    return &quot;Result&quot;
}
```

In this case, we could choose to `start` the `Job` anytime.

### Conclusion

In Kotlin, coroutine builders like `launch`, `async`, and `runBlocking` serve distinct purposes in managing asynchronous tasks. 

While `launch` creates non-blocking coroutines, it doesn&apos;t halt the calling code. `runBlocking` forces the program to wait for coroutine completion but might not be ideal for result-dependent tasks.

Handling coroutine results is achieved through the returned `Job` from `launch`. Utilizing `job.join()` ensures specific order of execution.

The `CoroutineStart.LAZY` option with `launch` enables controlled coroutine start, allowing the program to perform other tasks before explicitly initiating the coroutine with `job.start()`.

Understanding these builders provides flexibility in managing asynchronous operations in Kotlin, ensuring effective handling of concurrent tasks while maintaining code clarity.

Next topic, we will look at Coroutine that runs sequentially and concurrently as well as the difference between `launch` and `async`.</content:encoded><category>kotlin</category><category>asynchronous</category><category>coroutine</category></item><item><title>Quick peek into KMM (Kotlin Multiplatform Mobile)</title><link>https://htswe.github.io/blog/peek-into-kmm/</link><guid isPermaLink="true">https://htswe.github.io/blog/peek-into-kmm/</guid><description>Kotlin team is very ambitious and have been improving the experience of developers especially if you are working on Android. Together with Google, JetBrains who developed Kotlin makes many new tools…</description><pubDate>Thu, 23 Feb 2023 00:00:00 GMT</pubDate><content:encoded>### Introduction

Kotlin team is very ambitious and have been improving the experience of developers especially if you are working on Android. Together with Google, JetBrains who developed Kotlin makes many new tools and languages to increase productivity of developers. One of the shiny things that I have been curious for a long time is the idea of writing Kotlin code to build apps in both Android, iOS and Desktop. It is very tempting for someone who is already familiar with a language.

### Kotlin Multiplatform Mobile (KMM)

In September 2022, Kotlin team announced that KMM is in [Beta](https://kotlinlang.org/docs/components-stability.html). It is almost there, they said, but expects some migration steps may be required. KMM stable version will be coming in 2023 (which is this year). In mobile development, users expect us to support both iOS and Android. This expectation translates for most organization to hire 2 developers for each line of code to be written. The ongoing support and bug fix are also going to be expensive, not mentioning that both apps are expected to have same sets and functionality at the same time.

Any delay on one side of OS caused the other side to delay. Hence, cross platform development (Flutter from Google, React Native from Facebook) become popular.

### What to try

There is a great [documentation](https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html) and video in (Youtube)[https://www.youtube.com/watch?v=2yd6rVJdICU] on how to get started from Kotlin team.

But I found this video much easier to understand - probably, it is short and straightforward.
&lt;div class=&quot;video-embed&quot;&gt;&lt;iframe src=&quot;https://www.youtube.com/embed/ri6XfKmnC8w&quot; title=&quot;YouTube video&quot; loading=&quot;lazy&quot; allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt;&lt;/div&gt;

But I really feel the documentation is so good that you could just skip the video. Maybe I am already familiar with mobile development.

The tool `kdoctor` is awesome. In most experiment, setting development environment (ie. installing necessary tools) has been painful sometimes. `kdoctor` checks our system and guide us what to do next.

My experience tells me that when it comes to install environment, it is also good to find environment switcher. `jenv` is one of the tools we could use if we like to have multiple `Java Runtime Environment (JRE)`. `jenv` allows us to switch different `JRE` within some command line without the needs to upgrade or downgrade the environment. This becomes handy if we are experimenting a lot of things and we want to keep things cleaner.

### What I think about it

It felt great to write Kotlin codes (mostly). If you are Android developer, you will feel home since we have to run for both Android and iOS app from **Android Studio**. `Gradle` is the build tool which Android developer are already familiar with.

If you are totally new to iOS and installing Xcode, it seems scary at first. But the template code that comes with creating new project makes it easy to understand. Well, if you understand some basic SwiftUi, it is easier.

The most important thing in my opinion is the understanding of the project structure. There are 3 main directory (`modules` in Gradle vocabulary) that you should know.

![image-center](https://kotlinlang.org/docs/images/basic-project-structure.png)

The concept is pretty much similar to React Native. When you have platform specific code (eg. Android permission, iOS keychain), you write those codes in their specific module. As much as possible, you keep codes in Shared module.

I will look more into what is sharable in future post. Based on the documentation, there is an example of using `Kotlin Coroutine` and `Ktor` for networking and serialization. Excellent example, I must say that. It demonstrates that networking utility library is available for KMM. Not sure if you like it. It seems that you have to learn a new utility library for things that you used to. I understand some well known libraries such as `Retrofit`, `Gson`, `Dagger` are already battle tested and ready for production. The good news is that some libraries are now moving to support `KMM`. It depends on the success of `KMM` to motivate more libraries to support cross platform. React Native has in fact moved into open source to get more support from community to build utility libraries. And endorsement from Kotlin team will be crucial too so that the developers will not have to struggle to find right library.

### Conclusion

If you are mobile developer or your business product is on mobile, you will be paying attention. Cross platform has some pros and cons, nevertheless, it has a place in today. If you are picking up Flutter, Dart is the language and both your developers need to learn that. React Native is in JavaScript/TypeScript, so it has its target audience. `KMM`, in my opinion, is targeting existing native mobile developers who are writing codes in `Kotlin` and `Swift`. Both languages are like cousins who looks very similar.

Will I use KMM when it is stable? Maybe not in existing codebase. But it is perfect for a pet project or personal project which doesn&apos;t need to use a lot of extensive features from each platform. How about you?</content:encoded><category>learning</category><category>mobile</category></item><item><title>Image compression (Part 1) - Image Quality</title><link>https://htswe.github.io/blog/image-compression-part-1/</link><guid isPermaLink="true">https://htswe.github.io/blog/image-compression-part-1/</guid><description>One of the biggest challenge for most mobile app developer is to make the distributed app file size small (apk for android or ipa for iOS). As mobile apps are distributed as a bundle installer (like…</description><pubDate>Sun, 24 Jul 2022 00:00:00 GMT</pubDate><content:encoded>### Introduction

One of the biggest challenge for most mobile app developer is to make the distributed app file size small (`apk` for android or `ipa` for iOS). As mobile apps are distributed as a bundle installer (like a `zip` file) with all resources embedded that require to run the app successfully, the file size will grow over time. It is often found that the _images_ are occupying the biggest bulk of the app size. Moreover, a lot of images are also sending down to the users via the internet connection constantly in some of the apps such as e-commerce and social media apps.

It is therefore important to choose the correct image size and quality that is suitable for the user.

### Quality vs File Size

It is a simple math actually.

&gt; Better quality needs bigger file size.

We maybe tempted to choose for higher quality images, but wait a minute. Let&apos;s imagine a user uploads an eight-megapixel photo from a mobile device. If another user with same screen resolution would want to see the image, it makes sense to display in same resolution and same size as the original image. But what about a user with whose screen is only half or a quarter of that size? What if the image is just a thumbnail? Does it even make sense to transmit full eight-megapixel photo across the internet?

Usually, we use a variety of image compression algorithms to help us with saving the file size. Typically, the compressor will ask us to define a number for image quality. As the value gets lower, so does the file size and the image quality.

&gt; Choosing the value is hard.
&gt; Too low will result in bad image artifacts and user will complain about lack of image quality. Too high will cause us to send larger file unnecessarily.

For a small set of image files, we may rely on the designer to judge on image quality as we adjust the image compression level, but this approach will not work in large scale - for example, what if we have 15 millions users uploading images everyday. Sadly, most developers today will simply choose a quality setting for all images in their service.

Based on [imgmin](https://github.com/rflynn/imgmin#even-more-detail) project, some of the websites are just applying the compression factors between 75 to 100.

```
Google Images thumbnails:  74-76
Facebook full-size images: 85
Yahoo frontpage JPEGs:     69-91
Youtube frontpage JPEGs:   70-82
Wikipedia images:          80
Windows live background:   82
Twitter user JPEG images:  30-100, apparently not enforcing quality
```

This approach is not the best answer, and _It is still a million-dollar question - how do we find the right value, per image, at scale?_

### What reduces image quality

Human eye is pretty sensitive to a number of things when viewing the images including _edges_ and _gradients_. If there is an error with an edge between two expected values or mismatch, our brain will notice it.

|                                   Original                                    |                     Loss of edges after heavy compression                     |
| :---------------------------------------------------------------------------: | :---------------------------------------------------------------------------: |
| ![](https://upload.wikimedia.org/wikipedia/commons/b/bd/Sego_lily_cm-150.png) | ![](https://upload.wikimedia.org/wikipedia/commons/6/6d/Sego_lily_cm-150.jpg) |

Most image compression algorithms break the pixel data into BLOCKS of pixels (`blocking`) and quantized to reduce the number of unique colors in the image (`quantization`). Then the image will be modified based on the **_locality_** of image.

For example, JPG will group pixels into 8x8 blocks and attempt to find the similar colors for that region. This usually works because image tends to have a local regions of interest. If we look at one corner and the other corner in a random image, we found there is little or none correlation. However, in a photograph, there tends to have gradient and similar colors across the blocks. The result of `blocking` process makes the nearby pixels not sharing the same colors in photograph and we will start noticing the edges between the blocks.

### Measure Image Quality

Although our brain could instinctively recognize the bad image quality, it cannot help when we are automating the processing of images that the user uploads. It is important to have a mathematical, measurable, and programmable concept of image quality.

Today, there are two - `peak signal-to-noise ratio (PSNR)` and `structural similarity index measure (SSIM)`.

#### PSNR

It expresses the relationship between max possible power of a signal and the power of corrupting noise. In simple term, it measures how much the values of original image differ from the compressed image. But there is a few problems with PSNR measurement. It could be slightly biased toward over-smoothed (blurry) image. It means that if part of the texture is also removed, scores could be high.

In addition, PSNR metric relies strictly on numeric comparison and does not consider biological factor of human vision system. Therefore, the compression result might be good from numeric values, but to human eye, it is a bad quality.

#### SSIM

SSIM was developed to address the shortfall of PSNR and take human perception into account when considering the compression quality of images. This is done by looking at the similarity of edges between the source and the compressed image. SSIM might look like a better quality measurement, but it is more complicated to compute.

The image below show the calculated PSNR and SSIM side by side.

![image-center](https://miro.medium.com/max/1400/1*G-xmi8robr1JrfBcCoLwGQ.jpeg)

We notice the image quality is different even thought PSNR is the same.

The idea of measuring image quality using `PSNR` and `SSIM` is to show that we could automate the image compression quality if needed. In many development, what most developers are doing is to have designer or artist to hand-check the quality of a few samples and then choose a compression level for all of the rest of the images based on that.

### Applying practically

It is now becoming obvious that different images will require different export settings depending on the measurement results. For example, a picture of sunrise over a mountain is going to be different from a picture of pencil drawn image of sunrise. How do you achieve that in development environment?

Creating a cloud-compute resource to iteratively find the ideal quality is a straightforward path, but it means we need the time and financial resources to achieve that.

Imagine we have some images stored in our cloud backend and the user will download and display those images from their mobile devices or their computers. Where should the resizing occur?

Sending full resolution image to the device and resizing it before rendering is easiest in term of developer workload. But we are sending a lot of extra bits and bytes to the user who will not use them or see them. It is like throwing the money into the sea.

A better solution is to resize the image in our cloud, cache the resized image somewhere, so that we could send the smaller image to the smaller screen device. In most scenarios, I have seen 3 sizes - one for thumbnail, one for super high resolution for full screen and some in between. Android developer uses the same concept with - `ldpi`, `mdpi`, `hdpi`, `xhdpi`, etc, to serve the different resolutions for different screen sizes.

### Conclusion

In summary, images are important in every application and probably the largest data chunk (maybe after video). Sending appropriate sized image has multiple benefits: less data needed for users, little to none resizing needed (less GPU footprint), faster decoding and loading of images and better user experience for our users. In next article, we will compare the image formats such as `JPG`, `PNG` and `WebP`.</content:encoded><category>learning</category><category>mobile</category></item><item><title>Image compression (Part 2) - Choosing image format</title><link>https://htswe.github.io/blog/image-compression-part-2/</link><guid isPermaLink="true">https://htswe.github.io/blog/image-compression-part-2/</guid><description>There is an array of image algorithms and formats out there. Each has unique strength and trade-off that we need to consider. Let&apos;s look into the most commonly used image format - PNG, JPG, GIF and W…</description><pubDate>Sun, 24 Jul 2022 00:00:00 GMT</pubDate><content:encoded>### Introduction

There is an array of image algorithms and formats out there. Each has unique strength and trade-off that we need to consider. Let&apos;s look into the most commonly used image format - `PNG`, `JPG`, `GIF` and `WebP`.

### Interesting history

In 1985, Unisys filed a [patent][lzw-patent] for `LZW` compression algorithm. A few years later, CompuServe invented 89a format (later became `GIF`) and uses `LZW` as its backbone without realizing the patent.Unisys didn&apos;t care about it until 1993, when animated image became a sensation on the web HTML `IMG` tag. Unisys started to enforce its patent and eventually reached to court agreement in 1994, collecting royalties from all software that uses 89a graphic format. In the months following this decision, a group of seven engineers developed an entirely new, patent-free format known as `PNG`. Within a few week, `PNG` is supported by Netscape browser. In 2004, the patent on `LZW` finally expired, the debate of `GIF` (including how to pronounce it) vs `PNG` continued.

`JPG` has been a standard for some time. In 2013, Google and a set of open source contributors created a new image codec algorithm called `WebP`, which aimed to compress images smaller than `JPG` while keeping same quality. Although the saving (5% - 30%) were not so huge, it was massive for companies that operates in big image business (shopping, social media and image hosting). `WebP` initially faced adaption problem - Mozilla&apos;s Firefox openly [rejected][mozilla-reject-webp] it. Mozilla also open-sourced a new [`MozJPEG`][mozjpeg] codec to rebuke `WebP` adaption. But it didn&apos;t hold out long. In 2015, Mozilla had a change of heart and accepted `WebP`, saying that at the end of the day,

&gt; Sure, technology decisions often are the result of personal predilection, political scheming, and inter-company rivalries. But cold hard data still can win the day.
&gt; Mozilla

This statement said a lot of technology adaption, developer mentality and the benefit to the end users. We do have a lot of bias and we must fight for acceptance and approval among a world of engineers who are generally skeptical by nature.

### PNG

`PNG` refers to `Portable Network Graphics`. It is a _loseless_ image format that uses Gzip style compressor to make the file size smaller. Since it is _loseless_, the compressed quality will be identical to original.

One of the biggest attraction of `PNG` is that it supports **transparency**. On top of `red`, `green` and `blue` channel, there is `alpha` channel that defines which pixels to alpha-blend during rendering. It becomes very attractive to the web and mobile app where we could retain the background color while rendering the image on the top. However, we are also paying to have this fourth color channel as it will increase our file size.

Additionally, the `PNG` format allow for chunks of `metadata` in a file. This makes some image editors adding extra data to the file. Due to that, `png` could be bloated with junk that is useless to the user. It is therefore important that we **\*strip** out this unneeded data.

The good news is that there are a lot of tools out there - eg. PNGCrush, PunyPNG, TruePNG, etc.

### JPG

If transparency is not needed for the image, the `JPG` format will be a much better option. `JPG` stands for `Joint Photographic Experts Group`. Some calls it `JPEG` or `JPG` for short. `JPG` is a format built for photographic images and does not support transparency.

It is a _lossy_ compression by a quality metric which allows to trade off between file size and image quality. The compression format is built on block encoding. The image is broken into small `8x8` blocks, and various transformation are applied to each block.

Much like `PNG`, `JPG` can also include meta data blocks, which means the editor or camera could add some junks into the file. Most mobile devices now come with hardware `JPG` encoders and decoders hence they could be rendered significantly faster over an equivalent `PNG` file.

There are many tools out there that could further optimize the `JPG` file format, including Google&apos;s [Guetzli](https://github.com/google/guetzli) and [MozJPEG](https://github.com/mozilla/mozjpeg).

### GIF

`GIF` is another format that supports the transparency, alongside with _animation_. The `GIF` has two stages of compression, a `lossy palletization` to reduce the color pallette for the entire image to only **256** colors and followed by `lossless LZW` compression. Limiting to 256 color results in an aggressive quality reduction at the benefit of better compression sizes. `GIF` tends to be pretty well supported on the web, but not native platforms.

### WebP

The `WebP` format offers a middle ground between `JPG` and `PNG`. `WebP` supports both _loseless_ and _lossy_ compression mode. We could get both of best worlds from `JPG` and `PNG`. While it sounds like the crystal ball, there are a few caveats with `WebP` - mainly, it is not 100% supported across all image browsers. For example, chrome 23 and above supports `WebP` while chrome 4 to 8 does not support (old browsers). Likewise for many other well-known web browsers such as Firefox, Safari and Edge, etc.

For mobile development, Android is natively supported (yeah!) for `WebP`, otherwise we have to include a library for it. In addition to that, the advanced nature of lossy compression mode means that the performance of decompression on image load is a little slower than with `JPG` or `PNG`.

### Conclusion

Given all the information above, it is now pretty clear which image format to choose -

![flow](/assets/images/image-compression.drawio.svg)

In the next post, we will look at `Vector Drawable`.

[lzw-patent]: https://cs.stanford.edu/people/eroberts/cs201/projects/1999-00/software-patents/lzw.html
[mozilla-reject-webp]: https://arstechnica.com/information-technology/2011/05/mozilla-rejects-webp-image-format-google-adds-it-to-picasa/
[mozjpeg]: https://github.com/mozilla/mozjpeg
[facebook-webp-adpation]: https://www.cnet.com/tech/services-and-software/facebook-tries-googles-webp-image-format-users-squawk/
[mozilla-accept-webp]: https://www.cnet.com/tech/services-and-software/why-mozilla-had-a-change-of-heart-about-webp-images/</content:encoded><category>learning</category><category>mobile</category></item><item><title>Image compression (Part 3) - Vector Graphic like SVG</title><link>https://htswe.github.io/blog/image-compression-part-3/</link><guid isPermaLink="true">https://htswe.github.io/blog/image-compression-part-3/</guid><description>Typically, the images are arranged in 2D grid (x and y of the pixels), and each pixel represents the colors of image itself. When we view those from a distance, the edge disappears and our eyes see a…</description><pubDate>Sun, 24 Jul 2022 00:00:00 GMT</pubDate><content:encoded>### Introduction

Typically, the images are arranged in 2D grid (`x` and `y` of the pixels), and each pixel represents the colors of image itself. When we view those from a distance, the edge disappears and our eyes see a smooth color gradients. This is called `raster` format. What if instead of sending the final image, we send around some `codes` on how to draw the image? This concept is **vector** image format. It contains a number of commands and when executed procedurally, generates a final output image.

### Benefit

Let&apos;s think of technical drawing (like a building) that primarily consist of lines. Instead of telling every line points, we only need a `start` and `stop` point. We could then just draw it, hence we saved a lot of data drawing that line with just two points. It is like a form of compression.

Second, the vector image could be scaled very well with high accuracy. Drawing a millimeter line is the same as drawing a meter line. It becomes a huge win if we need the image for both thumbnail or full screen. It will serve very well across millions of devices with different resolutions and sizes.

### Price

After we discussed about the benefit, what is the price to pay? **Load Time**. This vector image expect the client to do the computation and the rendering. If the client device is fast, then the image rendering will be fast. It saves on the wire, but will incur more client-side overhead to reconstruct the image when it is rendered.

### SVG

One commonly used vector format is `SVG`. It stands for `Scalable Vector Graphics`. We could think `SVG` as a file format that stores image description in very low memory and generate a high quality, resolution independent image on the client.

&lt;svg width=&quot;400&quot; height=&quot;180&quot;&gt;
  &lt;rect x=&quot;50&quot; y=&quot;20&quot; width=&quot;150&quot; height=&quot;150&quot; style=&quot;fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9&quot; /&gt;
  Sorry, your browser does not support inline SVG.  
&lt;/svg&gt;

```
&lt;svg width=&quot;400&quot; height=&quot;180&quot;&gt;
  &lt;rect x=&quot;50&quot; y=&quot;20&quot;
  width=&quot;150&quot;
  height=&quot;150&quot;
  style=&quot;fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9&quot; /&gt;
  Sorry, your browser does not support inline SVG.
&lt;/svg&gt;
```

One of the limitation of `SVG` format is that it can only represent a certain type of image quality (only suitable for simple image and colors). If we are thinking of a picture of sunset with flowers, for instance, may not be the best candidate as the compression benefit yields less than processing it on client&apos;s device computation power.

### Conclusion

Vector images are great for things like logos, icons, technical drawings or simple image patterns, whereas raster images are best suited for photos and other rich information images.</content:encoded><category>learning</category><category>mobile</category></item><item><title>Discover what people want</title><link>https://htswe.github.io/blog/discover-what-people-want/</link><guid isPermaLink="true">https://htswe.github.io/blog/discover-what-people-want/</guid><description>&quot;Got a minute? Bad news&quot;. I sighed. Someone from my team has resigned. Sounds familiar? The next logical question that many of us asked is why the person wants to leave. If it is for a better career…</description><pubDate>Thu, 02 Jun 2022 00:00:00 GMT</pubDate><content:encoded>### I am quitting

&quot;Got a minute? Bad news&quot;. I sighed. Someone from my team has resigned. Sounds familiar? The next logical question that many of us asked is why the person wants to leave. If it is for a better career or having dream comes true, it is wonderful for this old friend. We are all happy that the person has found a better opportunity. But what if it is an unhappy reason?

### Why care?

&gt; With great power comes great responsibility.
&gt;
&gt; - _Peter Parker principle_

Some leaders do not care. To them, employee might be just a tool or simply a resource headcount. What they do not realize is that people are smart and people know well if you are genuine about their interest. In general, people trust and follow good leader. And good leader understands what the people need or want.

### People

Being a good leader is tough.

&gt; You cannot lead people you don&apos;t understand.

As a leader, you have to motivate the people, encourage to pursue certain goals and to engage in certain works. People will not put full effort and whole heart that they don&apos;t find it valuable. Hence, understanding what people want is the core of leadership. So, is it all? Humans are complicated - _they change over time_. The &quot;wants&quot; may also shift as they are going through their life.

One biggest challenge is that **even when you try asking people what they want, they still don&apos;t tell you**.

![image-center](https://images.pexels.com/photos/167964/pexels-photo-167964.jpeg)

### Basic human needs/wants

There are some basic things that people reliably want/need. The most two basic needs that are fundamental to everyone - **safety** and **self esteem**. People want others to think and feel that their existence mean something and matter to someone. Once those basic things are met, depending on individual, the wants/needs could be

1. **Material** - Some will say &quot;more money&quot; as this may provide them safety to buy a better house in safer neighborhood.
2. **Mastery** - People want to feel growth and get better at what they are doing
3. **Achievement** - An accomplishment will provide the motivation and validate their existence
4. **Affiliation** - As human, people want to feel belonged, loved and cared by others for their contributions.
5. **Autonomy** - people want to be trusted and have the ability to choose what is important and decide their own developments.
6. **Morality** - Desire to feel that the work they do is bigger than themselves.

We could use the above 6 things to measure how the team is doing and adjust based on individual. Have you tried asking what people value? In reality, most people are not even aware about themselves and might say easy things like &quot;more money, more bonus&quot;. But for the leadership, part of it to listen what the people said and the other is watching the behavior and going deeper.

The biggest question that most leaders will face is how to figure it out if the someone is not saying it.

### Trust

Psychologically, everyone tend to judge others based on - **competence** and **warmth**.

#### competence

It means whether people can trust that you could deliver. They will observe and decide on what you did. People will also look at your true intention as well. Do you really mean what you said? If it is a good competent leader, people will feel that they are surrounded by competent people and have someone who care about them.

#### warmth

Without having authority or dictate, no power to change compensation or promotion, the only way to get out is to help people to solve their problems. People don&apos;t trust because you are in the management. As a leadership, you have to slowly break down the ice over time, find out the problem that is hindering the people and fix it. You have to show your humanity side and prove your true intention to help people. Having similarity and familiarity will help to bond with people well.

![image-center](https://images.pexels.com/photos/461049/pexels-photo-461049.jpeg)

### Conclusion

In summary, we explore the reality that many leaders face: **the desire to discover what people want**. We realize that even when intentions are good, many people may not have the self-awareness to articulate what they want. We also list down the common needs/wants based on the research and some tips on how to build trust with the people. It is an invitation to continue learning even if we found out what the people want as those could also be changed over the times.</content:encoded><category>thoughts</category><category>learning</category><category>soft-skill</category></item><item><title>How to compare with others</title><link>https://htswe.github.io/blog/how-to-compare-with-others/</link><guid isPermaLink="true">https://htswe.github.io/blog/how-to-compare-with-others/</guid><description>Why did he get the dream school and not me?</description><pubDate>Mon, 30 May 2022 00:00:00 GMT</pubDate><content:encoded>&gt; Why wasn&apos;t I the one who get promoted?

&gt; Why did he get the dream school and not me?

### It is in our DNA

&quot;Stop comparing with others&quot;, said our parent, teacher, mentor, manager, coach and many others. But it turns out there are more nuisance on how we keep ourselves moving forward and how we could handle our emotion along with comparing with others. There has been done [research][research-on-monkey] on monkeys to find out if monkeys compare themselves with others. The answer is of course monkeys do. They compare what food the other monkey is getting or eating it, and if they have a better food than others, they feel satisfied. So are the human beings. We compare everything everyday. We all do and it is in our DNA.

But is it healthy? Should we compare with others?

### The truth

It is a myth that the less you compare yourself to others, the better. Often the opposite is true:

&gt; We don&apos;t compare ourselves enough.

Yes, that is right. In reality, we tend to compare our **weaknesses** to other people&apos;s **strength**. When we see someone who is good at sport, we wish we could do the same. When we hear someone get promoted at his/her work to manage 200 people, we question our career choice. Moreover, we tend to picture top 10% who are more successful in the field that we are not currently good at and we forget or ignore about the bottom 10% to compare.

![image-center](https://images.pexels.com/photos/5310566/pexels-photo-5310566.jpeg)

But have we thought about the price that the person has paid or going to pay for the success? The one who get promoted to manage 200 people is now having meetings back to back and didn&apos;t have time to enjoy creative works. Instead of having person to person meeting, she has to spend her time to manage teams. Would it be the kind of success that we would embrace? **Finding ways to curate our inputs is often much more useful.**

### Two types of envy

Envy is defined as a feeling of discontent over someone&apos;s possessions, quality or luck. There are two types of envy:

1. _malicious envy_ -&gt; it is a kind of destructive thought. Creating trouble so as to make the life worse for someone. A mental model with &quot;zero-sum&quot;, in order to gain something, someone must lose it.
2. _benign envy_ -&gt; thoughts such as &quot;I am inspired by what they&apos;ve done&quot; or &quot;I haven&apos;t done what they&apos;ve done yet&quot;.
   If we could aware of our own thoughts and move from malicious envy to benign envy, it could move us to a healthier place.

### Avoid social media

![image-center](https://images.pexels.com/photos/267389/pexels-photo-267389.jpeg)

Unless we could live in a jungle with no one, we could not escape from social media. Social media such as Facebook, Linkedin, Instagram and many other platforms are known to be toxic as they represent top 10% of success. It amplifies the glory while ignore our usual self. Pause and think, if you are seeing posts from someone, the algorithm has chosen to highlight the best parts of your friends&apos; life and your friends have chosen to share the best parts of their happy life.. Be cautious about social media.

&gt; If you are feeling down or blue, better to stay away.

Instead, we could plan of doing something that could help us to recover. For example, how about playing some games with friends? Reading books? Exercise?

### Conclusion

In recent study, 75% of people reported that they assess self-worth by comparing with others. Are we one of them? It is inevitable that we will have to live these big emotions such as envy (we wish we could have it) and jealousy (we wish to have it instead of someone else) sometimes. How do we deal with it? While we know it is the human nature, if it stuck in our mind for a long time, then it is not a healthy thing anymore. In this case, we have to ask ourselves if we would want to spend our time and energy on thinking about it. Instead we should divert our thoughts to some energy to drive a better outcome for ourselves.

[research-on-monkey]: https://www.researchgate.net/publication/312160617_Do_monkeys_compare_themselves_with_others</content:encoded><category>thoughts</category><category>learning</category><category>soft-skill</category></item><item><title>Late initialization</title><link>https://htswe.github.io/blog/late-init/</link><guid isPermaLink="true">https://htswe.github.io/blog/late-init/</guid><description>Sometimes, we want to initialize the properties of the class after it is created, but in a separate member function instead of using lazy</description><pubDate>Fri, 27 May 2022 00:00:00 GMT</pubDate><content:encoded>Sometimes, we want to initialize the properties of the class after it is created, but in a separate member function instead of using [`lazy`](/tech/lazy-initialisation/)

Let&apos;s take a look at below code. `Box` interface has a function `setUp` that initializes instances. Suppose we want to reuse a library that creates and manipulates `Box`. This library requires subclass initialization in `setUp()` instead of in a constructor.

```kotlin
interface Box {
  fun setUp()
}

class ToyBox: Box {
  private var items: String? = null
  override fun setUp() {
    items = &quot;cars, trains, lego&quot;
  }
  fun checkToy(toy: String): Boolean =
    items?.contains(toy) ?: false
}

val toyBox = ToyBox()
toyBox.setUp()
toyBox.checkToy(&quot;lego&quot;)
```

As you notice, in `ToyBox` class, we could not just define `items` as `String` because that would requires us to provide the initial value which is not `null`. We may be tempted to initialize with an empty `String`, but it is a bad practice because we will not know if empty is the real value of `items`. We use `null` to indicate that it has not yet initialized.

If we make `items` as optional (`String?`), it means we must check for `null` in all member functions, eg. in `checkToy()`, we have to make sure that `items` is not `null` before we could do `contains()` function call. However, we know in our mind that we will call `setUp()` function to initialize, so `null` check is unnecessary in reality.

The `lateinit` property fixes this problem. Let&apos;s take a look at the same code with `lateinit`.

```kotlin
interface Box {
  fun setUp()
}

class ToyBox: Box {
  lateinit var items: String? = null
  override fun setUp() {
    items = &quot;cars, trains, lego&quot;
  }
  fun checkToy(toy: String): Boolean =
    toy in items
}

val toyBox = ToyBox()
toyBox.setUp()
toyBox.checkToy(&quot;lego&quot;)
```

Now, the `checkToy()` does not need to worry if `items` is going to be `null` anymore. It is safely defined as non-nullable property.

### Limitation

`lateinit` could be used on a property inside the body of a class, a top-level property, or local `var`.

However,

- `lateinit` could only be used on `var` property, not a `val`.
- The property must be non-nullable type
- The property could not be a primitive type
- `lateinit` could not be used used in `abstract` class or `interface`
- `lateinit` is not allowed for custom `get()` or `set()`
- The IDE would not be able to detect if we forget to initialize or there will be no compile-time error

### Conclusion

The `lateinit` is a better way of expression in Kotlin if we are sure that the property will be initialized later by a function, and not by constructor. It converts the property into non-nullable, which has both benefits and pitfalls. Since we would not be able to detect it during compile time, the only time that we could find out is in runtime. `::items.isInitialized` might give some helps, we should take caution about it.</content:encoded><category>kotlin</category></item><item><title>Lazy initialization</title><link>https://htswe.github.io/blog/lazy-initialisation/</link><guid isPermaLink="true">https://htswe.github.io/blog/lazy-initialisation/</guid><description>So far, we have two ways to initialize properties:</description><pubDate>Thu, 26 May 2022 00:00:00 GMT</pubDate><content:encoded>So far, we have **two** ways to initialize properties:

1. Store the initial value at the point of definition, or in the constructor
2. Define a custom getter that computes the property for each access

But what if there is a third usecase where it would be costly to initialize and we might not need to use it. For example, an heavy IO computation, network requests and database access are costly operations. If we follow the above two ways, it could make application take longer for start-up time and performing unnecessary work that is never used or not required to use it immediately.

This usecase becomes so frequent that Kotlin has added a built-in solution - `lazy`.

### `Lazy` concept

The concept isn&apos;t new or unique to Kotlin. Laziness could be implemented within other languages, whether or not there is built-in solution. Kotlin provides this concept using [property delegation](/tech/property-delegate/).

```kotlin
val iAmLazy: String by lazy { &quot;I am lazy&quot; }

print(iAmLazy)
```

Without `lazy` initialization, we&apos;d be forced to make them `vars`, producing less reliable code.

```kotlin
class LazyInt(val init: () -&gt; Int) {
  private var iAmLazy: Int? = null
  val value: Int
    get() {
      if (iAmLazy == null)
        iAmLazy = init()
      return iAmLazy!!
    }
}

val later = LazyInt {
  print(&quot;hi&quot;)
  100
}
// first time call
print(later.value) // hi 100
print(later.value) // 100
```

### Conclusion

It is true that sometimes we need to construct the properties that could be costly for initialization. Often, we could not be sure that property will be used in the program at all. This concept of `lazy` initialization was designed to prevent unnecessary initialization.</content:encoded><category>kotlin</category></item><item><title>Property Delegation Tools</title><link>https://htswe.github.io/blog/property-delegate-tools/</link><guid isPermaLink="true">https://htswe.github.io/blog/property-delegate-tools/</guid><description>The standard library contains special property delegation properties. Map is one of the few types in Kotlin library. Each property identifier becomes a String key for the map, and the property&apos;s type…</description><pubDate>Thu, 12 May 2022 00:00:00 GMT</pubDate><content:encoded>The standard library contains special property delegation properties. `Map` is one of the few types in Kotlin library. Each property identifier becomes a `String` key for the map, and the property&apos;s type is captured in the associated value:

```kotlin
class Student(map: MutableMap&lt;String, Any?&gt;) {
  var name: String by map
  var age: Int by map
  var id: String by map
}

val aStudent = mutableMapOf&lt;String, Any?&gt;(
  &quot;name&quot; to &quot;Jeep&quot;,
  &quot;age&quot; to 23,
  &quot;id&quot; to &quot;X231322&quot;
)
```

### Property Setter vs Delegate Observable

We might remember using `set` to set a new value to the `var`.

```kotlin
var name: String
  set(value) {
    print(&quot;name: $value&quot;)
    field = value
  }

var age: Int
  set(value) {
    print(&quot;age: $value&quot;)
    field = age
  }
```

While property setter works fine, Delegates, on the other hand, allows for accessing to the property and its old value.

```kotlin
class Student {
  var log = &quot;&quot;
  var surname: String by observable(&quot;x&quot;) { prop, old, new -&gt;
    log += &quot;${prop.name}: $old -&gt; $new&quot;
  }
}

val student = Student()
student.surname = &quot;Lee&quot;
print(student.log) // surname: x -&gt; Lee
```

`observable` takes two arguments:

1. initialValue, &quot;x&quot; in this case
2. a function to invoke when there is `onChange` event occurs.

### delegate vetoable

it is very similar to `observable` in delegate, but it can veto the modification of the value of property. For example, we might have some rule that the student surname must be more than one character for some reasons.

```kotlin
fun surnameLengthCheck(
  property: KProperty&lt;*&gt;,
  old: String,
  new: String
) = return new.length &gt; 1

class Student {
  var surname: String by Delegates.vetoable(&quot;Lee&quot;, ::surnameLengthCheck)
}

val student = Student()
student.surname = &quot;Tan&quot;
student.surname = &quot;x&quot;

print(student.surname) //Tan and x is rejected because it fails surnameLengthCheck
```

### delegate notNull

The last function in `delegate` is `nonNull`. It returns on property delegate for read/write with a non-`null` value. It is initialized not during the object construction time, but later time. It tries to read the property before the initial value has been assigned.

### Conclusion

As we can see `delegates` function in the kotlin standard library could be used to guard or trace about the setting of new value. `notNull`, `observable` and `vetoable` could be used to customize for setting or tracing new value.</content:encoded><category>kotlin</category><category>advanced</category></item><item><title>Property Delegation</title><link>https://htswe.github.io/blog/property-delegate/</link><guid isPermaLink="true">https://htswe.github.io/blog/property-delegate/</guid><description>In Kotlin, we could connect a property to a delegate with the by keyword:</description><pubDate>Fri, 06 May 2022 00:00:00 GMT</pubDate><content:encoded>In Kotlin, we could connect a property to a delegate with the `by` keyword:

```kotlin
class Readable(val n: Int) {
  val value: String by BasicRead()
}

class BasicRead {
  operator fun getValue(
    r: Readable,
    property: KProperty&lt;*&gt;
  ) = &quot;value: ${r.n}&quot;
}
```

The delegate&apos;s class must contain a `getValue()` function if the property is a `val` (read only). If the property is `var` (read/write), both `getValue()` and `setValue()` functions must be present.
Because `getValue()` returns a `String`, the type of `value` must also be `String`.

The second parameter `property` is a special type [`KProperty`][kproperty], and this provides reflective information about the delegated property.

If the delegated property is a `var`, it must handle both reading and writing, so the delegate class requires both `getValue()` and `setValue()`.

```kotlin

class ReadWritable(var n: Int) {
  var msg = &quot;&quot;
  var value: String by BasicReadWrite()
}

class BasicReadWrite {

  operator fun getValue(
    rw: ReadWriteable,
    property: KProperty&lt;*&gt;
  ) = &quot;getValue: ${rw.n}&quot;

  operator fun setValue(
    rw: ReadWritable,
    property: KProperty&lt;*&gt;,
    newString: String
  ) {
    rw.n = newString.toIntOrNull() ?: 0
    rw.msg = &quot;setValue to ${rw.n}&quot;
  }

}

val x = ReadWritable(11)
print(x.value) //getValue: 11

x.value = 99
print(x.value) //getValue: 99
print(x.msg) //setValue to 99
```

### Using `ReadOnlyProperty` interface

The above example doesn&apos;t implement an `interface`. The class can be used as a delegate if it follows the convention of having necessary function(s) with signature(s). However, we could also implement the `ReadOnlyProperty` -

```kotlin
class ReadableByInterface(val n: Int) {
  val value: String by BasicReadWithInterface()
  // SAM conversion
  val valueSam: String by ReadOnlyProperty { _, _ -&gt; &quot;getValue: $n&quot; }
}

class BasicReadWithInterface : ReadOnlyProperty&lt;ReadableByInterface, String&gt; {
  override operator fun getValue(
    r: ReadableByInterface,
    property: KProperty&lt;*&gt;
  ) = &quot;value: ${r.n}&quot;
}
```

Implementing `ReadOnlyProperty` communicates us that `BasicReadWithInterface` can be used as a delegate and ensures a proper `getValue()` definition. Likewise, we could use `ReadWriteProperty` interface to implement to become a delegate, ensuring proper `getValue()` and `setValue()` definitions.

### Extension Function as Delegate

`getValue()` and `setValue()` can be written as extension functions as well.

```kotlin
class Addition(val a: Int, val b: Int) {
  val sum by Sum()
}

class Sum

operator fun Sum.getValue(
  r: Addition,
  property: KProperty&lt;*&gt;
) = r.a + r.b

val addition = Addition(10, 20)
print(addition.sum) // 30
```

Why is this important? Using extension, we could use existing class that we are unable to modify or inherit and still delegate a property with it.

### Summary

The delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively with zero boilerplate code.

With delegate, we could just implement once, add them to a library and reuse them later. The most common property that we use often is `lazy` where the value is computed only on first access.

[kproperty]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-property/</content:encoded><category>kotlin</category><category>advanced</category></item><item><title>Operator Overloading</title><link>https://htswe.github.io/blog/operator-overloading/</link><guid isPermaLink="true">https://htswe.github.io/blog/operator-overloading/</guid><description>Back in the school while I was learning C++, operator overloading was one of the topics in academic. But in practice, I rarely overload operators. However, in Kotlin, we do use the overload operators…</description><pubDate>Thu, 28 Apr 2022 00:00:00 GMT</pubDate><content:encoded>Back in the school while I was learning C++, operator overloading was one of the topics in academic. But in practice, I rarely overload operators. However, in Kotlin, we do use the overload operators, without noticing.

```kotlin
val list: List = listOf(&apos;a&apos;, &apos;b&apos;, &apos;c&apos;, &apos;d&apos;, &apos;e&apos;, &apos;f&apos;)
print(list[0]) //a
print(list.get(2)) //c
print(&apos;d&apos; in list) //true
print(list.contains(&apos;e&apos;)) //true
```

Accessing list elements using _square bracket_ calls the overloaded operators `get()` and `set()`, while `in` calls `contains()`.

### What is operator overloading

&gt; In programming, _overloading_ means adding extra meaning to something that is already exists.

For example, operator overloading allows us to use `+` to do something meaningful for our custom data type. This concept was popular back in C++ days, but because C++ had no garbage collection, writing overloaded operators were difficult. Java deemed operator overloading as &quot;bad&quot; and didn&apos;t allow it in Java. Python language demonstrated the simplicity of operator overloading with the support of garbage collection. It constraints us to a **limited** set of operators, so as C++ did. Scala experimented with allowing to invent own operators, but the feature was abused by some programmers and created incomprehensible code. Kotlin simplified the process, but restricts the choice to a reasonable and familiar set of operators.

### How it looks

In order to overload operator, Kotlin uses the keyword `operator`.

```kotlin
data class Num(val n: Int)

operator fun Num.plus(rhs: Num) =
  Num(n + rhs.n)

Num(4) + Num(4) // Num(8)
Num(4).plus(Num(2)) // Num(6)
```

What if we want to make `n` as `private` in the data class `Num`? In this case, the extension function could not access to `n` for `rhs`. We could consider defining an operator as member function then it will be fine.

```kotlin
data class Car(private val wheels: Int) {
  operator fun plus(anotherCar: Car) =
    Car(wheels + anotherCar.wheel)
}

Car(4) + Car(6) // Car(10)
```

### Equality

Invoking `==` (equality) or `!=` (inequality) calls the `equals()` member function. `data class` automatically redefine `equals()` to compare the stored data, but if we don&apos;t redefine `equals()` for non-`data` classes, the default version compares **_reference_** rather than contents.

```kotlin
class A(val i: Int)
data class D(val i: Int)

fun main() {
  // normal class
  val a = A(1)
  val b = A(1)
  val c = a

  print(a == b) // false
  print(a == c) // true

  // data class
  val d = D(1)
  val e = D(1)

  print(d == e) // true
}

class E(var v: Int) {
  override fun equals(other: Any?) = when {
    this === other -&gt; true // same object in memory will result true
    other !is E -&gt; false // must be same type
    else -&gt; v == other.v // stored data
  }

  override fun hashCode(): Int = v

  override fun toString() = &quot;E($v)&quot;
}

val a = E(1)
val b = E(2)
```

### Arithmetic operators

Let&apos;s try arithmetic operators (eg. `+`, `-`) as extension to `class E`.

```kotlin
// Unary operators
operator fun E.unaryPlus() = E(v) // +a
operator fun E.unaryMinus() = E(-v) // -a
operator fun E.not() = this // !a

// Increment/decrement
operator fun E.inc() = E(v + 1) // a++
operator fun E.dec() = E(v - 1) // a--

// Binary
operator fun E.plus(e: E) = E(v + e.v) // a + b
operator fun E.minus(e: E) = E(v - e.v) // a - b
operator fun E.times(e: E) = E(v * e.v) // a * b
operator fun E.div(e: E) = E(v / e.v) // a / b
operator fun E.rem(e: E) = E (v % e.v) // a % b

// Augmented assignment
operator fun E.plusAssign(e: E) { v += e.v } // a += b
operator fun E.minusAssign(e: E) { v -= e.v } // a -= b
operator fun E.timesAssign(e: E) { v *= e.v } // a *= b
operator fun E.divAssign(e: E) { v /= e.v } // a /= b
operator fun E.remAssign(e: E) { v %= e.v } // a %= b
```

### Invoke

Placing parentheses after an object generates a call to `invoke()`. The `invoke()` operator makes an object look like a function.

```kotlin
class Cost {
  operator fun invoke() = &quot;invoke()&quot;
  operator fun invoke(i: Int) = &quot;invoke($i)&quot;
  operator fun invoke(i: Int, j: String) = &quot;invoke($i, $j)&quot;
  operator fun invoke(i: Int, j: String, k: Double) = &quot;invoke($i, $j, $k)&quot;
}

val cost = Cost()
cost() //&quot;invoke()&quot;
cost(1) //&quot;invoke(1)
cost(2, &quot;hey&quot;) //invoke(2, hey)
cost(3, &quot;you&quot;, 1.5) //invoke(3, you, 1.5)
```

### Conclusion

Operator overloading is not an essential feature, but is an excellent example of how a language is more than just a way to manipulate the underlying computer. With overloading, we have been able to express the abstractions, so other humans have an easier time to understand the code without getting bogged down in needless details.</content:encoded><category>kotlin</category><category>advanced</category></item><item><title>Generics in Kotlin</title><link>https://htswe.github.io/blog/generics-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/generics-kotlin/</guid><description>I love template in C++ in the olden day. In many good languages that I had chance to come across, such as TypeScript, Java (it was added later) and Kotlin, they too also have the Generic code. Generi…</description><pubDate>Thu, 21 Apr 2022 00:00:00 GMT</pubDate><content:encoded>I love template in C++ in the olden day. In many good languages that I had chance to come across, such as TypeScript, Java (it was added later) and Kotlin, they too also have the Generic code. Generic code works with types that are &quot;_specified later_&quot;.

### Base object (OOP) approach

Ordinary classes and functions work with specific types (eg. `String`, `Int`, `MyCustomClass`). If I want the same code to work across more types, the rigidity (inflexibility) could be overwhelming. From Object Oriented Programming (OOP) concept, we might recall _Polymorphism_ to solve this. The idea is that we could write a function that will take **base** class object as a parameter. We could call the function with an object of any class that is derived from that **base** class. Now, our function is more general, and could be used in more places.

The downside of it that this might lead to very limiting because we must inherit from that single hierarchy.

### What about an interface instead of an object?

Let us consider what if our function takes an interface instead of **base** object? It could loosen the single hierarchy limitation. Anything that implement the interface is able to replace the function parameter. Using interface, we could cut across class hierarchy.

However, sometimes, even an interface is too restrictive because it forces us to work only with that interface. The good news is that we could make our code even more general if it works with any type that is yet to be specified. This unspecified type is a **_generic type_** parameter.

### Wait, how about `Any`?

Oh ya. We have `Any` data type. It is the root of the Kotlin class hierarchy and every Kotlin class has `Any` as a superclass (remember Base object approach). So we could make our function to take `Any` as argument type and it could work. If `Any` works for you and it is simpler solution, use it.

&gt; Simplicity is what we aim for in software development.

### Generics

The question that most of us ask ourselves is &quot;when should we use generic&quot;. Duplicated code is a good candidate for conversion into a generic function or type. The way to make generic is by using `&lt;&gt;` and a placeholder like `T` to represent unknown type.

```kotlin
fun &lt;T&gt; giveMeBack(arg: T): T {
  return arg
}

giveMeBack(1) // 1
giveMeBack(&quot;echo&quot;) // echo
```

### Preserve Type Info

Code within generic class and functions can&apos;t know the type of `T` - this is called **\*erasure**. Generics can be thought of a way to preserve type information for the return value. Let&apos;s take an example.

```kotlin
class Toy {
  override fun toString() = &quot;Toy&quot;
}

class ToyBox(private var toy: Toy) {
  fun put(aToy: Toy) { toy = aToy }
  fun get(): Toy = toy
}
```

In the above code, when we call `get()` of `ToyBox`, the result comes back as type `Toy`. And we think this box could be used not only for `Toy`, but also any other thing. Could we make `Box` more generic?

```kotlin
class Book {
  override fun toString() = &quot;Book&quot;
}

open class Box&lt;T&gt;(private var obj: T) {
  fun put(aObj: T) { obj = aObj }
  fun get(): T = obj
}

val toy: Toy = Box(Toy()).get()
val book: Book = Box(Book()).get()
```

`Box&lt;T&gt;` is to ensure that we could only `put()` a `T` type only and when we call `get()` on that `Box`, the result comes back as type `T`.

### Generic extension function

Let&apos;s do some advanced stuff. We could make `map()` for `Box` by defining a generic extension function.

```kotlin
fun &lt;T,R&gt; Box&lt;T&gt;.map(f:(T) -&gt; R): List&lt;R&gt; {
  return listOf(f(get()))
}

val bookX = Box(Book()).map { it.toString() + &quot;X&quot; } //[bookX]
```

### Type Eraser

In Java, generics are not part of the original language - they were added [later](https://docs.oracle.com/javase/1.5.0/docs/guide/language/index.html). Forcing generics into Java without breaking the existing code required a crucial compromise: _the generic types are only available during compilation but are not preserved at runtime_. Hence the types are **_erased_**.

```kotlin
val strings = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)
val anyType: List&lt;Any&gt; = listOf(&quot;a&quot;, 3, 1.5)
useList(strings)
useList(anyType)

fun useList(list: List&lt;Any&gt;) {
  if (list is List&lt;String&gt;) { // &lt;- uncomment this and you will see an error
    // do something
  }
}
```

Since the type information has been erased at runtime, If we uncomment the check, we will see an error - &quot;Cannot check for instance of erased type: List&lt;String&gt;&quot;.
If the eraser didn&apos;t happen, the list might look like this:

| a | b | c | String |
| a | 3 | 1.5 | Any |

Because generic types are erased, type information is not stored in the `List`. Instead both `strings` and `anyType` are just `List`, with no additional type information.

| a | b | c |
| a | 3 | 1.5 |

### Why Kotlin chose to erase type

There could be possibly two reasons.

1. Java compatibility
2. Overhead - storing generic type info significantly increases the memory occupied by a generic `List` or `Map`. For example, a standard `Map` consists of many `Map.Entry` objects, and `Map.Entry` is a generic class. Thus, if generics were reified everywhere by default, each key and value of every `Map.Entry` would contain additional type info.

### What if we want to retain type information

To retain type information for function arguments, add the `reified` keyword.

```kotlin
fun &lt;T: Any&gt; a(kClass: KClass&lt;T&gt;) {
  // do something with kClass
}

fun &lt;T: Any&gt; b() = a(T::class)
```

When the function `b()` call the the function `a()`, it won&apos;t compile because the type information `T` is erased when this code runs and `T::class` is not recognized. In Java, we could solve it by passing type information into the function by hand (very inelegant):

```kotlin
fun &lt;T: Any&gt; c(kClass: KClass&lt;T&gt;) = a(kClass)

class K

val kc = c(K::class)
```

Even though `c()` could invoke the function `a()`, it seems redundant to pass explicit type information (`KClass&lt;T&gt;`). In elegant way, we expect the complier knows the type `T` and could silently pass it for us. Kotlin offers us with `reified`. The only catch is that the function must be `inline`.

```kotlin
inline fun &lt;reified T: Any&gt; d() = a(T:class)
```

The function `d()` produces the same result as `c()`, but `d()` doesn&apos;t require the class reference as an argument.

What else could `reified` do? It allows the use of `is` with a generic parameter type.

```kotlin
inline fun &lt;reified T&gt; check(t: Any) = t is T

check&lt;String&gt;(&quot;1&quot;) //true
check&lt;Int&gt;(&quot;1&quot;) //false
```

### Variance `in` or `out`

Combining generics and inheritance is possible and the result produces two dimensions of change. Let&apos;s say we have a `Box&lt;T&gt;` and want to assign it to `Box&lt;U&gt;` where `T` and `U` have an inheritance relationship. In this case, we must place the constraints `in` or `out` variance annotations, depending on the usage.

```kotlin
class Box&lt;T&gt;(private var obj: T) {
  fun put(aObj: T) { obj = aObj }
  fun get(): T = obj
}

class BoxIn&lt;in T&gt;(private var obj: T) {
  fun put(aObj: T) { obj = aObj }
}

class BoxOut&lt;out T&gt;(private var obj: T) {
  fun get(): T = obj
}
```

`BoxIn` uses `in` constraint to strictly indicate the intention and only allows the `T` as input into the class. Likewise, `out` constraint will only the `T` to go out, but not allowed to come in. Then what do we want that?

```kotlin
open class Fruit
class Apple : Fruit()
class Orange : Fruit()
```

Both `Apple` and `Orange` are subtypes of `Fruit`. But is there any relation between `Apple` and `Orange`? A `Box` of `Apple` should be able to assign to `Box` of `Fruit` or `Box` of `Any`(because `Any` is the supertype in Kotlin). But we do not want `Box` of `Orange` to be put into `Box` of `Apple`, violating the pureness of `Apple` in the `Box`. Worse if we allow `Box` of `Any` into `Box` of `Apple`, there is no type safety at all.

So we want to prevent the use of `put()` such that no one can put a `Orange` into an `BoxOut&lt;Apple&gt;`.

```kotlin
val boxAppleOut: BoxOut&lt;Apple&gt; = BoxOut(Apple())
val boxFruitOut: BoxOut&lt;Fruit&gt; = boxAppleOut
val boxAnyOut: BoxOut&lt;Any&gt; = boxFruitOut
```

With no `put()` allowed in `out` constraint, we could ensure that no one will intentionally or accidentally put wrong type. Therefore, it preserves the pureness of the type. In this example above,

- `Box&lt;T&gt;` is _invariant_.
- `BoxOut&lt;out T&gt;` is _covariant_.
- `BoxIn&lt;in T&gt;` is _contravariant_.

### Conclusion

The generic topic is usually a bit confusing to most people especially you are totally new to template language. But it can make code really elegant and easy to work with once you understand how it works. You could avoid a lot of duplications with the help from generic. To understand more, you could also read the [Kotlin Generic](https://kotlinlang.org/docs/generics.html).</content:encoded><category>kotlin</category><category>advanced</category></item><item><title>Scope function</title><link>https://htswe.github.io/blog/scope-function/</link><guid isPermaLink="true">https://htswe.github.io/blog/scope-function/</guid><description>When I started doing Kotlin, the one that confused me the most was scope functions. However, once I understand what it is, it becomes my most favorite Kotlin feature. It makes code clear, concise and…</description><pubDate>Wed, 20 Apr 2022 00:00:00 GMT</pubDate><content:encoded>When I started doing Kotlin, the one that confused me the most was `scope` functions. However, once I understand what it is, it becomes my most favorite Kotlin feature. It makes code clear, concise and so easy to read. If you are still not sure what I am talking about, read on.

&gt; Scope functions create a temporary scope wherein you could access an object without using its name.

There are five scope functions in Kotlin: `let()`, `apply()`, `with()`, `run()` and `also()`. They are designed to work with a lambda and do not require an `import`. All five scope works almost the same, but differ in

1. accessing the `context` object (`it` vs `this`)
2. what it returns

Let&apos;s look into some of the use cases for each of those five scope functions.

### `let()`

`let()` function is probably the most widely used in Kotlin to provide null safety call. As the name implies, it lets/allows to execute the block ONLY with non-null value when it use with `?` operator.

```kotlin
var aValue: Int? = null
aValue?.let { print(it) } // nothing will happen since aValue is null

aValue = 10
aValue?.let { print(it) } // 10
```

Another thing worth to mention here is the usage of `it` as context object. On the above example, `it` represents `aValue` which is no longer a `null`.

### `apply()`

It is pretty self explanatory. `apply()` is used to apply whatever in the block to the object properties.

```kotlin
class MyObj() {
  val name: String
  val color: String
}

val myObj = MyObj().apply {
  this.name = &quot;Hello Object&quot;
  color = &quot;blue&quot; // `this` can be hidden
}

print(myObj) // {name: Hello Object, color: blue}
```

### `with()`

If `apply()` mutates the properties of the object, `with` allows us to access the properties without repeating the object name.

```kotlin
print(myObj.name)
print(myObj.color)

with(myObj) {
  print(name) //this.name = name
  print(color)
}
```

### `run()`

`run()` combines `let()` and `with()`. Imagine that you want to invoke some functions of the object, provided that the object itself is not `null`.

```kotlin
myObj?.run {
  print(name) // this.name = name
}
```

### `also()`

Last, but not least `also()` can be used when we have to perform additional operations.

```kotlin
val list = mutableListOf&lt;Int&gt;(1, 2, 3)
list.also {
  it.add(4)
  it.remove(2)
}

print(list) // [1, 3, 4]
```

### Conclusion

Scope functions that access the context object using `this` produce cleanest syntax since we can omit `this` keyword within the scope. For those scope functions using `it`, we could rename to any lambda argument, so we can improve the readability if `it` keyword is too confusing.

Most importantly, check and align with the teammates on which scope functions is being agreed and used across the project codebase.</content:encoded><category>kotlin</category></item><item><title>Resource Cleanup</title><link>https://htswe.github.io/blog/better-to-cleanup/</link><guid isPermaLink="true">https://htswe.github.io/blog/better-to-cleanup/</guid><description>Using try, catch and finally blocks for resource cleanup is tedious and error-prone. In fact, Kotlin has a library functions that could help us to manage cleanup for us.</description><pubDate>Tue, 05 Apr 2022 00:00:00 GMT</pubDate><content:encoded>Using `try`, `catch` and `finally` blocks for resource cleanup is tedious and error-prone. In fact, Kotlin has a library functions that could help us to manage cleanup for us.

As we know, `finally` clause cleans up resources regardless of how `try` block exits. But what if an exception can happen while closing the `finally` clause. On top of that, if one exception is thrown inside a `try` and another while closing the resource, the latter shouldn&apos;t conceal the former. Ensuring proper cleanup becomes very messy.

To reduce this complexity, Kotlin&apos;s `use()` guarantees proper cleanup of closable resources, liberating you from handwritten cleanup code. `use()` rethrows all exceptions, so we must still deal with those exceptions.

We can find `use()` in Java documentation for `AutoClosable`. For example, to read lines from a `File` we apply `use()` to a `BufferedReader`.

```kotlin
fun main() {
  DataFile(&quot;test.txt&quot;)
    .bufferedReader()
    .use { it.readLines().first() }
}
```

`use()` ensures resource cleanup at the point the resource is created, rather than forcing us to write cleanup code when we are finished with the resource.</content:encoded><category>kotlin</category></item><item><title>Extension lambdas</title><link>https://htswe.github.io/blog/extension-lambdas/</link><guid isPermaLink="true">https://htswe.github.io/blog/extension-lambdas/</guid><description>Any fool can write code that a computer can understand. Good programmers write code that humans can understand.</description><pubDate>Tue, 05 Apr 2022 00:00:00 GMT</pubDate><content:encoded>&gt; Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

&gt; &lt;cite&gt;&lt;a href=&quot;https://martinfowler.com/&quot;&gt;Martin Fowler&lt;/a&gt;&lt;/cite&gt;

An extension lambda is like an extension function. It defines a lambda instead of a function.

```kotlin
val a: (String, Int) -&gt; String = { str, n -&gt;
  str.repeat(n)
}

val b: String.(Int) -&gt; String = {
  this.repeat(it)
}

a(&quot;Rambo&quot;, 2) // RamboRambo

&quot;Rambo&quot;.b(2) //RamboRambo
b(&quot;Rambo&quot;, 2) //RamboRambo
```

Both `a` and `b` yield same result. `a` is an ordinary lambda like the ones we usually see in a lot of places. It takes two params - `String` and `Int`, then returns a `String`. The lambda body also has two params `str` and `n`, followed by the arrow `-&gt;`.

`b` moves the `String` param outside the parenthesis and it changes similar to extension function `String.(Int)`. Just like extension function, the object of the type being extended, becomes the receiver and `this` is now referring to `String`. There is one interesting thing about it too. While we could use `&quot;Rambo&quot;.b(2)`, `b` can also be called using the traditional form `b(&quot;Rambo&quot;, 2)`.

&gt; Kotlin documentation usually refers **extension lambdas** as **_function literals with receiver_**. The term **_function literals_** encompasses both lambdas and anonymous functions.

### Extension Lambda with multiple parameters

Like an extension function, an extension lambda can have multiple parameters:

```kotlin
val zero: Int.() -&gt; Boolean = {
  this == 0
}

val one: Int.(Int) -&gt; Boolean = {
  this % it == 0
}

val two: Int.(Int, Int) -&gt; Boolean = { arg1, arg2 -&gt;
  this % (arg1 + arg2) == 0
}
```

### Extension Lambda with function reference

Using `::` we can pass a function reference when an extension lambda is expected.

```kotlin
fun f1(n: Int) = n + 3
fun Int.f2() = this + 3

fun Int.d1(f: (Int) -&gt; Int) = f(this) * 2
fun Int.d2(f: Int.() -&gt; Int) = f() * 2

fun main() {
  5.d1(::f1) // (5+3)*2 = 16
  5.d2(::f1) // (5+3)*2 = 16

  5.d1(Int::f2) // (5+3)*2 = 16
  5.d2(Int::f2) // (5+3)*2 = 16
}
```

A reference to an extension function has the same type as an extension lambda: `Int::f2` has the type `Int.() -&gt; Int`.

### Extension Lambda in Kotlin library

The Kotlin standard library contains a number of functions that work with extension lambdas. For example, `StringBuilder` is a modifiable object that produces an immutable `String` when you call `toString()`. In contract, the more modern [`buildString()`][build-string-func] accepts an extension lambda. It creates its own `StringBuilder` object, applies the extension lambda to that object, then calls `toString()` to produce the result:

```kotlin
fun original(): String {
  val sb = StringBuilder()
  sb.append(&quot;123:&quot;)
  (&apos;a&apos;..&apos;f&apos;).forEach { sb.append(it) }
  return sb.toString()
}

fun clean() = buildString {
  append(&quot;123:&quot;)
  (&apos;a&apos;..&apos;f&apos;).forEach { sb.append(it) }
}

fun evenCleaner() =
  (&apos;a&apos;..&apos;f&apos;).joinToString(&quot;&quot;, &quot;123:&quot;)


original() // 123:abcdef
clean() // 123:abcdef
evenCleaner() // 123:abcdef
```

The `original()` is usually what we used to do for `StringBuilder`. Using `buildString()` in `clean()`, we do not even need to create a `StringBuilder` and makes everything much more succinct. If we dig even deeper, we can even find more direct solution that will skip the builder altogether.

So we ask what other standard library functions similar to `buildString()` that uses extension lambdas. We found `Lists` and `Maps`.

```kotlin
val chars: List&lt;String&gt; = buildList {
  add(&quot;English:&quot;)
  (&apos;a&apos;..&apos;z&apos;).forEach { add(&quot;$it&quot;) }
}

val charMap: Map&lt;Char, Int&gt; = buildMap {
  (&apos;a&apos;..&apos;z&apos;).forEachIndexed { n, ch -&gt;
    put(ch, n) // {a=0, b=1, ... , z=25}
  }
}
```

### Writing Builder using Extension Lambda

The post is getting long and probably, we will end with this good piece. We already know the [Builder][builder-design-pattern] pattern has several benefits:

1. It creates in multi-steps process, easier to construct if the object is complex.
2. It produces different variations with the same code
3. It separates common construction code from specialized code, making it easier to write &amp; read.

Implementing builders using extension lambdas provide **additional** benefits, which is the creation of a _Domain-Specific-Language_ (DSL). The goal of DSL is syntax that is comfortable and sensible to a user who is a domain expert rather than programming expert. This allows that user to produce working solution knowing only a small subset of the surrounding language while at the same time benefitting from the structure and safety of that language.

```kotlin
open class Recipe : ArrayList&lt;RecipeUnit&gt;()

open class RecipeUnit {
  override fun toString() = &quot;${this::class.simpleName}&quot;
}
```

```kotlin
open class Operation : RecipeUnit()
class Toast: Operation()
class Grill: Operation()
class PutOnPlate: Operation()
```

```kotlin
open class Ingredient : RecipeUnit()
class Bread : Ingredient()
class Butter : Ingredient()
class Jam : Ingredient()
```

```kotlin
open class Sandwich : Recipe() {
  fun execute(op: Operation): Sandwich {
    add(op)
    return this
  }
  fun grill() = execute(Grill())
  fun toast() = execute(Toast())
  fun putOnPlate() = execute(PutOnPlate())
}
```

```kotlin
fun sandwich(fillings: Sandwich.() -&gt; Unit): Sandwich {
  val sandwich = Sandwich()
  sandwich.add(Bread())
  sandwich.toast()
  sandwich.fillings() // lambda magic here
  sandwich.putOnPlate()
  return sandwich
}

val butterJamSandwich = sandwich {
  add(Butter()) // i want butter
  add(Jam()) // i also want jam
}
```

`sandwich()` gives us the basic ingredients and operations required to make **any** toasted sandwich. The beauty here is when we want different variant type of sandwich, the `fillings` extension lambda allows the caller to configure the `Sandwich` in numerous different ways, but with no constructor for each configuration. How awesome it is.

I found one of my coworkers wrote an Android extension of `SpannableText` which allows you to specify underline, italic, bold, foreground colors, etc using this extension lambda in DSL approach. It looks cleaner and easier to use it.

[build-string-func]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/build-string.html
[builder-design-pattern]: https://en.wikipedia.org/wiki/Builder_pattern</content:encoded><category>kotlin</category><category>functional programming</category><category>advanced</category></item><item><title>Nothing</title><link>https://htswe.github.io/blog/nothing/</link><guid isPermaLink="true">https://htswe.github.io/blog/nothing/</guid><description>What is Nothing in Kotlin? Does it even exist? A Nothing return type indicates a function that never returns. This is usually a function that always throws an exception.</description><pubDate>Mon, 04 Apr 2022 00:00:00 GMT</pubDate><content:encoded>What is `Nothing` in Kotlin? Does it even exist? A `Nothing` return type indicates a function that never returns. This is usually a function that always throws an exception.

Here is an example.

```kotlin
fun infinity(): Nothing {
  while (true) {}
}
```

As you can see, we are planning to loop forever. Hence it will only make sense if we tell the caller that we shall return `Nothing`. `Nothing` is a built-in Kotlin type with no instances. In our codebase, there is one function we do it very often. Yes, `TODO()` which has a return type of `Nothing` and throws `NotImplementedError` when it is invoked.

```kotlin
fun willDoLater() = TODO()
fun willDoLaterWithCustomMsg = TODO(&quot;later, ok?&quot;)

willDoLater() // will return &quot;NotImplementedError: An operation is not implemented.&quot;
willDoLaterWithCustomMsg() // will return &quot;NotImplementedError: An operation is not implemented: later, ok?&quot;
```

### Cousins of `Nothing`

We could also assign both `null` or `none` to a `var` or `val` of a nullable type. This is allowed because the type of both `null` and `none` is `Nothing?` (nullable `Nothing`).

```kotlin
val a: Nothing? = null
var b: String? = null
b = &quot;abc&quot;
b = none
print(b) // null
```

![image-center](https://images.pexels.com/photos/3656309/pexels-photo-3656309.jpeg)</content:encoded><category>kotlin</category></item><item><title>Check Instructions</title><link>https://htswe.github.io/blog/check-instructions/</link><guid isPermaLink="true">https://htswe.github.io/blog/check-instructions/</guid><description>Check Instructions are like assert - they act like a constraints that must be met before it could proceed. Usually, they are used to validate function arguments and results. Check instructions typica…</description><pubDate>Wed, 30 Mar 2022 00:00:00 GMT</pubDate><content:encoded>_Check Instructions_ are like **assert** - they act like a constraints that must be met before it could proceed. Usually, they are used to validate function arguments and results. Check instructions typically throw exceptions when they fail. They are easier to write and produce more comprehensible code.

### `require()`

This `require()` acts like preconditions and normally used to validate function arguments, so it typically appears at the beginning of function bodies. These tests cannot be checked at _compile_ time. Preconditions are relatively easy to include in our code, but sometimes they can be turned into **_unit tests_**.

```kotlin
data class DayOfMonth(val dayNo: Int) {
  init {
    require(dayNo in 1..31) {
      &quot;Day of month is out of range. Input: $dayNo&quot;
    }
  }
}

DayOfMonth(10) //DayOfMonth(dayNo=15)
DayOfMonth(35) //IllegalArgumentException: Day of month is out of range. Input: 35
```

### `requireNotNull()`

The `requireNotNull()` tests its first argument and returns that argument if it is not `null`. Otherwise, it produces an `IllegalArgumentException`.

```kotlin
fun doubleIt(n: Int?): Int {
  requireNotNull(n) {
    &quot;the input cannot be null&quot;
  }
  return n * n
}

doubleIt(null) // IllegalArgumentException the input cannot be null&quot;
```

### `check()`

The `check()` is identical to `require()` except that it throws `IllegalStateException`. It is typically used at the end of a function, to verify that the results are valid.

```kotlin
val myFile = DataFile(&quot;test.txt&quot;)

fun modifyContent(canModify: Boolean) {
  if (canModify)
    myFile.writeText(&quot;OK&quot;)

  check(myFile.exists()) {
    &quot;${myFile.name} does not exist!&quot;
  }
}

modifyContent(false) //IllegalStateException: test.txt does not exist!
```

### `assert()`

To avoid commenting and uncommenting `check()` statements, `assert()` allows us to enable and disable `assert()` checks. `assert()` comes from Java. Assertions are disabled by default, and are only engaged if we explicitly turn them on using a command line flag. In Kotlin, this flag is `-ea`.

Usually, the recommendation is to use `require()` and `check()` which are always available without special configuration.</content:encoded><category>kotlin</category></item><item><title>Kotlin Exception Handling</title><link>https://htswe.github.io/blog/exception-handling-in-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/exception-handling-in-kotlin/</guid><description>If debugging is the process of removing software bugs, then programming must be the process of putting them in.</description><pubDate>Tue, 29 Mar 2022 00:00:00 GMT</pubDate><content:encoded>### Failure is always a possibility

&gt; If debugging is the process of removing software bugs, then programming must be the process of putting them in.

&gt; &lt;cite&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Edsger_W._Dijkstra&quot;&gt;Edsger W. Dijkstra&lt;/a&gt;&lt;/cite&gt;

Kotlin finds basic errors when it analyzes the program. Errors that could not be detected at **compile** time must be dealt with at **runtime**. We can throw `exception` and here we will look at `catch` exceptions. Improved error handling is a better way to increase code reliability.

### Beware of Exception Subtypes

The `testMyCode()` function throws `IllegalArgumentException` when incorrect `code` is provided.

```kotlin
fun testMyCode(code: Int) {
  if (code &lt; 0) {
    throw IllegalArgumentException(&quot;Code must be positive&quot;)
  }
}

fun main() {
  try {
    testMyCode(&quot;-100&quot;.toInt())
  } catch (e: IllegalArgumentException) {
    print(e.message) // Code must be positive
  }

  try {
    testMyCode(&quot;0&quot;.toInt(1))
  } catch (e: IllegalArgumentException) {
    print(e.message) // the result will be not our code: It will be something like
    // radix 1 was not in valid range 2..36
  }
}
```

What happens to our second block? why is the exception throwing an error which we do not recognize? It comes from `toInt()` [function][toint] where the library function could also throw the `IllegalArgumentException`. How could we avoid it? Well, we can define our own `Exception` such as `IncorrectInputException` and throws using own exception instead.

```kotlin
class IncorrectInputException(message: String): Exception(message)

fun testMyCode(code: Int) {
  if (code &lt; 0) {
    throw IncorrectInputException(&quot;Code must be positive&quot;)
  }
}

fun main() {
  try {
    testMyCode(&quot;-100&quot;.toInt())
  } catch (e: IncorrectInputException) {
    print(e.message) // Code must be positive
  }

  try {
    testMyCode(&quot;0&quot;.toInt(1))
  } catch (e: IncorrectInputException) {
    print(e.message) // the result will be not our code: It will be something like
    // radix 1 was not in valid range 2..36
  }
}
```

[toint]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-int.html</content:encoded><category>kotlin</category></item><item><title>Companion Object</title><link>https://htswe.github.io/blog/companion-object/</link><guid isPermaLink="true">https://htswe.github.io/blog/companion-object/</guid><description>If you don&apos;t need to tie member functions to the object, consider for companion object. Regular class elements can access the elements of the companion object, but the companion object elements canno…</description><pubDate>Mon, 28 Mar 2022 00:00:00 GMT</pubDate><content:encoded>### Companion Object

If you don&apos;t need to tie member functions to the object, consider for `companion` object. Regular class elements can access the elements of the companion object, but the companion object elements cannot access the regular class elements.

```kotlin
class WithCompanion {
  companion object {
    val i = 3
    fun doubleIt() = i * 2
  }
  fun tripleIt() = i + doubleIt()
}

fun WithCompanion.Companion.quadrupleIt() = doubleIt() + doubleIt()

val wc = WithCompanion()
wc.tripleIt() // 9
WithCompanion.i // 3
WithCompanion.doubleIt() // 6
WithCompanion.quadrupleIt() // 12
```

As you can see, you can access to member of companion object using class name `WithCompanion.i` and `WithCompanion.doubleIt()`.

&gt; One thing to note is that ONLY one companion object is allowed per class.

### Named and Default

```kotlin
class withNamed {
  companion object Named {
    fun s() = &quot;from Named&quot;
  }
}

class withDefault {
  companion object {
    fun s() = &quot;from Default&quot;
  }
}

withNamed.s() // from Named
withNamed.Name.s() // from Named

withDefault.s() // from Default
withDefault.Companion.s() // from Default [Default Name is &quot;Companion&quot;]
```

One thing to note is that Kotlin assigns the name `Companion` if you don&apos;t give the companion object a name. And of course, you can still access its elements without using the name.

### Single piece of storage

```kotlin
class Computer {
  companion object {
    private var n: Int = 0
  }

  fun increase() = ++n
}

val a = Computer()
val b = Computer()

a.increase() // 1
b.increase() // 2
```

Even if we have two separate objects of `Computer`, when we call the function `increase()` for both `a` and `b`, the value of `n` is sharing the same memory. `n` is a single piece of storage. Likewise, `increase()` function shows that you can access the `private` members of the `companion object` from the surrounding class.

### Factory Method Pattern

A common use for a companion object is controlling object creation -- this is the _Factory Method_ pattern. Suppose you like to only allow the creation of `Lists` of `Book` objects, and not individual `Book` objects.

```kotlin
class Book
private constructor (private val id: int) {
  override fun toString(): String = &quot;Book#$id&quot;
  companion object Factory {
    fun create(size: Int) =
      List(size) { Book(it) }
  }
}

Book.create(0) // []
Book.create(3) // [Book#0, Book#1, Book#2]
```

Firstly, the `Book` constructor is `private`, so the only way for you to create is via the `create()` factory function.</content:encoded><category>kotlin</category></item><item><title>Inner class</title><link>https://htswe.github.io/blog/inner-class/</link><guid isPermaLink="true">https://htswe.github.io/blog/inner-class/</guid><description>Inner class is like nested class, but an object of inner class maintains a reference to the outer class. inner has implicit link to outer class.</description><pubDate>Fri, 25 Mar 2022 00:00:00 GMT</pubDate><content:encoded>### Inner class

Inner class is like nested class, but an object of inner class maintains a reference to the outer class. `inner` has implicit link to outer class.

```kotlin
class House(private sqm: Int) {
  open inner class Room(name: String) {
    fun callOuter() =
      &quot;Room $name is part of House $sqm in size&quot;
  }

  private inner class BedRoom : Room(&quot;Master&quot;)
  fun masterRoom(): Room = BedRoom()
}
```

- The function `callOuter()` which is a member of `Room` class is able to access `sqm` without qualification.
- Because `BedRoom` inherits from `Room`, `BedRoom` must also be `inner` class. Nested classes cannot inherit from `inner` classes.
- `inner data` class is not allowed.

### Qualified `this`

We usually use `this` in a class to represent the current object. It is useful when we are accessing to the property or the member function. How would it work in inner class? To clear up on this confusion, Kotlin provides the qualified `this` syntax followed by `@` symbol and the name of the _target_ class.

```kotlin
class House(name: String = &quot;House&quot;) {
  inner class Room(name: String = &quot;Room&quot;) {
    fun whichIsWhich() {
      print(this.name) // Room
      print(this@Room.name) // Room
      print(this@House.name) // House
    }
  }
}
```

### Local &amp; Anonymous Inner Class

Class defined inside member function are called _local inner class_. It can be created anonymously, using an `object` expression. In that case, the `inner` keyword is not used, but is implied.

```kotlin

fun interface Pet {
  fun speak(): String
}

object Pet {

  // local inner class
  fun dog(): Pet {
    val word = &quot;Bark!&quot;
    class Dog : Pet {
      override fun speak() = word
    }
    return Dog()
  }

  // anonymous inner class
  fun cat(): Pet {
    val word = &quot;Meow~&quot;
    return object : Pet {
      override fun speak() = word
    }
  }

  // using SAM conversion
  fun bird(): Pet {
    val word = &quot;Chirp&quot;
    return Pet { word }
  }
}

print(Pet.dog().speak()) // Bark!
print(Pet.cat().speak()) // Meow~
print(Pet.bird().speak()) // Chirp
```

### Summary

In Kotlin, file can contain multiple top level classes and functions. Therefore, it is quite rare for a need to use local classes. But if we need it, it is basic and straightforward. For example, it is reasonable to create a simple `data class` that is used inside a function. If a local class is getting complex, you can always convert to a regular class.</content:encoded><category>kotlin</category></item><item><title>Object Object Object</title><link>https://htswe.github.io/blog/kotlin-object/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-object/</guid><description>The object keyword in Kotlin defines something like class. But you cannot create instance of an object, as there is only one. Remember [Singleton pattern][singleton].</description><pubDate>Thu, 24 Mar 2022 00:00:00 GMT</pubDate><content:encoded>### What is object

The `object` keyword in Kotlin defines something like `class`. But you cannot create instance of an `object`, as there is only one. Remember [_Singleton_ pattern][singleton].

```kotlin
object One {
  val n = 1
}

print(One.n) // 1
```

### Interesting things about `object`

If you want to confine the `object` within the current file, you can make it as `private`. However, you cannot provide a parameter list for an `object`. Naming conventions is a little different for creating instance of `object`. What happens when you create an `object`? Kotlin defines the `class` and create a single instance of that class. Therefore, instead of starting a lower-case for first letter for instance of class, we use the upper-case for first letter, just like the class.

```kotlin
open class School(val noOfStudents: Int)

object University: School(1000)

interface SchoolOpening {
  fun open(): String
}

object OpenSchool: SchoolOpening {
  override fun open() = &quot;Time to open&quot;
}
```

### Nested Object

`Object` could not be placed inside functions, but it can be nested inside other `object` or class.

```kotlin
object Outer {
  object Nested {
    val a = &quot;Outer.Nested.a&quot;
  }
}
```

[singleton]: https://en.wikipedia.org/wiki/Singleton_pattern</content:encoded><category>kotlin</category></item><item><title>Nested class</title><link>https://htswe.github.io/blog/nested-class/</link><guid isPermaLink="true">https://htswe.github.io/blog/nested-class/</guid><description>A nested class enables us to group more logically, hence it makes it more readable and refined structure. A nested class is simply a class within the namespace of outer class.</description><pubDate>Wed, 23 Mar 2022 00:00:00 GMT</pubDate><content:encoded>### Nested Class

A nested class enables us to group more logically, hence it makes it more readable and refined structure. A nested class is simply a class within the namespace of outer class.

```kotlin
class Outer(private val code: String) {
  class Inner {
    fun hello() = &quot;hello&quot;
  }
}
```

### Local Class

A local class is the class that is nested inside function. Within function, one thing to take note is that we couldn&apos;t have `interface`. The local classes are not visible outside the function, so we cannot return them.

```kotlin
fun thisIsLocal() {
  open class Animal
  class Dog : Animal()

  val aDog: Animal = Dog()
}
```

### Class inside Interface

Class can be nested inside `interface`.

```kotlin
interface Item {
  val type = Type
  data class Type(val type: String)
}

class Hammer(material: String) : Item {
  override val type = Item.Type(material)
}
```

### Nested Enum

`enum` are class, so they can be nested inside other class.

```kotlin
class FootballClub(
  val name: String,
  val size: Size = Small
) {
  enum class Size {
    Large,
    Medium,
    Small
  }

  fun grow() : FootballClub {
    val newSize = values()[
      (size.ordinal - 1).coerceAtLeast(Large.ordinal)
    ]

    return FootballClub(name, newSize)
  }
}
```</content:encoded><category>kotlin</category></item><item><title>Sealed class in Kotlin</title><link>https://htswe.github.io/blog/sealed-class-in-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/sealed-class-in-kotlin/</guid><description>To constrain a class hierarchy, we have to declare the superclass sealed. Without the constraint, our code will look like this:</description><pubDate>Tue, 22 Mar 2022 00:00:00 GMT</pubDate><content:encoded>To constrain a class hierarchy, we have to declare the superclass `sealed`. Without the constraint, our code will look like this:

```kotlin
open class Transport

data class Train(
  val line: String
): Transport()

data class Bus(
  val number: String
): Transport()

fun travel(transport: Transport) =
  when (transport) {
    is Train -&gt; &quot;Train ${transport.line}&quot;
    is Bus -&gt; &quot;Bus ${transport.number}&quot;
    else -&gt; &quot;Unknown transport&quot;
  }
```

If you are looking at `travel()` method, you will notice there is a potential trouble. Imagine if we have another `Transport` type, the `travel()` method will not tell you that you need to modify it to detect for new `Transport` type. If you have a lot of `Transport` types, then it could become a maintenance nightmare. This whole situation can be improved using `sealed` keyword. When defining `Transport`, replace `open class` with `sealed class`.

```kotlin
sealed class Transport

data class Train(
  val line: String
): Transport()

data class Bus(
  val number: String
): Transport()

fun travel(transport: Transport) =
  when (transport) {
    is Train -&gt; &quot;Train ${transport.line}&quot;
    is Bus -&gt; &quot;Bus ${transport.number}&quot;
  }
```

&gt; all direct subclasses of a `sealed` class must be located in the same file as the base class. Although Kotlin forces you to exhaustively check all possible types in a `when` expression, the `when` in `travel()` no longer requires an `else` branch.

### Subclasses

When a class is `sealed`, you can easily iterate through its subclasses:

```kotlin
sealed class Android
class Samsung : Android()
class Huawei : Android()
open class LG : Android()
class LG_One : LG()


fun main() {
  Android::class.sealedSubclasses.map { it.simpleName }
  // Samsung, Huawei, LG
}
```

`Android::class` will produce a class object and you can access properties and member functions of that class object to discover information. One of the properties of class objects is `sealedSubclasses`, which expects that `Android` is a `sealed` class (otherwise it produces an empty list).

`sealedSubclasses` uses _reflection_, which requires that the dependency `kotlin-reflection.jar` be in the classpath. Reflection is a way to dynamically discover and use characteristics of a class. `sealedSubclasses` can be an important tool when building polymorphic systems. It can ensure that new classes will automatically be included in all appropriate operations. Because it discovers the subclasses at runtime, however, it may have a performance impact on your system.</content:encoded><category>kotlin</category></item><item><title>Downcasting</title><link>https://htswe.github.io/blog/downcasting-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/downcasting-kotlin/</guid><description>Downcasting is to discover the specific type of a previously upcast object. Upcast is always safe because the base class cannot have a bigger interface than the derived class. Every base class member…</description><pubDate>Thu, 10 Mar 2022 00:00:00 GMT</pubDate><content:encoded>_Downcasting_ is to discover the specific type of a previously upcast object. _Upcast_ is always safe because the base class cannot have a bigger interface than the derived class. Every base class member is guaranteed to exist and is therefore safe to call. Although object-oriented programming is primarily focused on upcasting, there are situations where downcasting can be a useful and expedient approach.

Downcasting happens at **runtime**, and is also called **_run-time identification (RTII)_**.

```kotlin
interface Base {
  fun f()
}

class Derived1: Base {
  override fun f() {}
  fun g() {}
}

class Derived2: Base {
  override fun f() {}
  fun h() {}
}

fun main() {
  val b1: Base = Derived1() // upcast
  b1.f()
  //b1.g() // error, g() cannot access in b1

  val b2: Base = Derived2() // upcast
  b2.f()
  //b2.h() // error, h() cannot access in b2
}
```

As we can see, we cannot access `b1.g()` and `b2.h()` since both `b1` and `b2` are upcast to base.

### Smart Cast

**_Smart Cast_** is automatic downcast. This is keyword checks whether an object is a particular type. Any code within the scope of that check assumes that it is that type:

```kotlin
fun main() {
  val b1: Base = Derived1()
  if (b1 is Derived1) // scope within the check
    b1.g()
}
```

### The `as` keyword

The `as` keyword forcefully casts a general type to a specific type. A failing `as` cast throws a `ClassCastException`. A plain `as` is called an `unsafe cast`.

When a safe cast `as?` fails, it doesn&apos;t throw an exception, but instead returns `null`.

```kotlin
interface Creature

class Dog : Creature {
  fun bark() = &quot;woof!&quot;
}

class Human : Creature {
  fun talk() = &quot;hello&quot;
}

fun dogBarkSafely(c: Creature) =
  (c as? Dog)?.bark() ?: &quot;Not a dog&quot;


dogBarkSafely(Dog()) // woof!
dogBarkSafely(Human()) // Not a dog
```

### Discovering Types in Lists

```kotlin
val group: List&lt;Creature&gt; = listOf(
  Dog(), Human(), Dog()
)

val dog = group.find { it is Dog } as Dog?
dog?.bark()
```

The code above can be written using `filterIsInstance()`, which produces all elements of a specific type.

```kotlin
val dogs : List&lt;Human&gt; = group.filterIsInstance&lt;Human&gt;()
```

`filterIsInstance` is more readable than using `filter()`. The difference between `filter()` and the `filterIsInstance()` is the return values. `filter` returns a `List` of `Creature` whereas `filterIsInstance` returns the target.</content:encoded><category>kotlin</category></item><item><title>How I should work remote/hybrid more effectively</title><link>https://htswe.github.io/blog/how-to-work-remote-effectively/</link><guid isPermaLink="true">https://htswe.github.io/blog/how-to-work-remote-effectively/</guid><description>Recent statistics from many [sources][hybrid-work-study] are indicating that a majority of employees desire (and also expect) some kind of remote/hybrid work arrangement after the post-covid era.</description><pubDate>Mon, 07 Mar 2022 00:00:00 GMT</pubDate><content:encoded>## Background

Recent statistics from many [sources][hybrid-work-study] are indicating that a majority of employees desire (and also expect) some kind of remote/hybrid work arrangement after the post-covid era.

Whether you support it or against it, the reality is that we will have to work with people who could not be sitting in the same office room with us and hence it is important that we need to know how to work more effectively with our team mates and clients (if applicable) remotely across the different locations and timezones.

## 1. Embrace Remote First Culture

Back when I was working in a consultant firm before the pandemic, I had an opportunity to work with a client who was in another country. We brought all stakeholders into a conference room whenever we need to have a regular call with the client to clarify our backlog user stories.

We put a microphone in the middle of the room and put one of our teammate screen onto the projector. Each of us takes turn to talk to microphone while surrounding it. And yes, you guess it right. It was a terrible experience. Not only the communication is **unclear** to everyone, but also put some of us **disengaged** in the conversation.

### Tip 1: Everyone join from own device.

Conduct all meetings online **_unless_** everyone in the team is in the same room. Sometimes, we may be tempted to host the meeting in a room with most/some of the team mates while others will join from remotely. No, not a good idea. We all may want to sit in the same room.

Each of us join the meeting as individual from our devices. It appears to everyone that we are all on the same level of communication. The communication is much clear and also fairer to everyone in the team, be it remote or in office.

### Tip 2: Turn on Video Cam, please!

&lt;iframe width=&quot;382&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/mU9VYcQWSOc&quot; title=&quot;YouTube video player&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt;

Have you tried doing a sharing or presentation to a screen? I once have done doing about 30 minutes of sharing to a group of 20+ people. In the beginning, with some chit chats, it was fine. Then it comes silence. You get a little panicked when things are silent. So you try to talk continuously to break the silence, you get tired very soon. You pause it, ask if anyone has question. You get silence again. You start to doubt that the topic doesn&apos;t interest people and you start to feel it is just a waste of everyone time. And you know when you are talking to a digital wall for 30 minutes, it will drain your energy and dishearten you.

From that experience onwards, I know I need to turn on the video cam even if I am not talking. Listening attentively is a skill and respect that my team mate fully deserved. Visual cues are as good as verbal and gives a lot of signal to the speaker. People will remember you. You will be connected to the team. Be kind and supportive to your team mate.

### Tip 3: Involve everyone.

In a physical meeting, many conversation might be happening at same time. In virtual, we have to take our turn to speak so everyone can listen. In a team, we have people who are talking a lot while some by nature or by seniority, may keep silent. It is important to call them out and gives the opportunity to share/speak up. Encourage them to do so that they will feel that they are also part of the team.

## 2. Over communicate

![image-center](https://images.pexels.com/photos/2962135/pexels-photo-2962135.jpeg)
It is funny that we like to assume other people will think like us. Even in normal days while working inside the same office, when you make a survey on the biggest challenge in the most organizations, **communication** is always at the top of the list. I have some suggestions:

1. **_Keep it simple_** - over communicate does not mean communicating everything. It means communicating the right things with right amount with clarity. when you write it down, it will help to clear your thoughts. keep it simple and do not bring too much noises.
2. **_Regular sync-up_** - even your team may not have things to discuss today, having a reserved time-slot is always an good opportunity when you need it. Nobody enjoys adhoc meeting or call too often. Set a regular time to catch up with the team. Give the time back is much better than disrupting their work flow.
3. **_Share the note_** - After the lengthy discussion, people tend to forget. Write down the note as you discuss. Read agreed action items before ending the call. Share the notes so that people can recall when they need it.

## 3. Buddy system

![image-center](https://images.pexels.com/photos/10653957/pexels-photo-10653957.jpeg)

Work could be long, hard and sometimes lonely. You do not have to suffer alone. If your workplace already have the buddy system in place, use it.

Find someone who shares the same context with you. Have a chat and learn to support each other. You will feel belonging and a meaningful friendship that could last for long.

&gt; If you want to walk fast, walk alone. But if you want to walk far, walk together.

&gt; &lt;cite&gt;&lt;a href=&quot;https://quotefancy.com/quote/1439954/Ratan-Tata-If-you-want-to-walk-fast-walk-alone-But-if-you-want-to-walk-far-walk-together&quot;&gt;Ratan Tata&lt;/a&gt;&lt;/cite&gt;

### Bonus Tip: Batch meeting.

In remote work environment, it is rare for us to work solo on our own. We have to meet people, it could be 1:1, discussion with your team mates, or your line of management. Do not split the meeting all across the day and time. It is much better that you have full 3 hours block than 3 blocks of 1 hours each. You can accomplish more with batch meeting. Check your calendar again and all you need is to **ask** the organizer.

[hybrid-work-study]: https://siepr.stanford.edu/publications/policy-brief/hybrid-future-work</content:encoded><category>agile</category></item><item><title>Another choice for middle ground (Composition Vs Inheritance)</title><link>https://htswe.github.io/blog/another-choice-for-middle-ground/</link><guid isPermaLink="true">https://htswe.github.io/blog/another-choice-for-middle-ground/</guid><description>Both composition and inheritance place sub objects inside the new class. With composition, the sub object is explicit whereas the sub object with inheritance is implicit.</description><pubDate>Thu, 17 Feb 2022 00:00:00 GMT</pubDate><content:encoded>Both composition and inheritance place sub objects inside the new class. With composition, the sub object is explicit whereas the sub object with inheritance is implicit.

Class delegation is midway between composition and inheritance. Like composition, we have to place the member inside our class. Like inheritance, it exposes the interface of the sub object.

Let’s see this:

```kotlin
interface Control {
    fun up(speed: Int): String
    fun down(speed: Int): String
    fun left(speed: Int): String
    fun right(speed: Int): String
}

class DroneController: Control {
    override fun up(speed: Int) = &quot;up $speed&quot;
    override fun down(speed: Int) = &quot;down $speed&quot;
    override fun left(speed: Int) = &quot;left $speed&quot;
    override fun right(speed: Int) = &quot;right $speed&quot;
}
```

What if we want a super drone controller that can speed 2 times while going up and down? What about inheriting `DroneController`? But it doesn’t work because `DroneController` is not `open`.

We can create an instance of `DroneController` as a property and explicitly delegate all the exposed member functions to that instance.

```kotlin
class SuperDroneController: Control {
    private val controller = DroneController()

    // delegate
    override fun up(speed: Int)
        = controller.up(speed) + &quot;2x&quot;
    override fun down(speed: Int)
        = controller.down(speed) + &quot;2x&quot;
    override fun left(speed: Int) = controller.left(speed)
    override fun right(speed: Int) = controller.right(speed)
}
```

It is called [Delegation Design Pattern](https://en.wikipedia.org/wiki/Delegation_pattern) which allows object composition to achieve the same code reuse as inheritance.

### Kotlin `by` keyword

For the `SuperDroneController` example, in Kotlin language, we can remove the boilerplate code with the keyword `by`.

```kotlin
class SuperDroneController(dController: DroneController) :
    Control by dController {

    override fun up(speed: Int)
        = dController.up(speed) + &quot;2x&quot;
    override fun down(speed: Int)
        = dController.down(speed) + &quot;2x&quot;
}
```

### Use case: Multiple Class inheritance

Kotlin doesn’t support multiple class inheritance, but you can simulate it using class delegation. For example, you want to produce a button by combining a class that draws a rectangle and another class that manages mouse events.

```kotlin
// a class drawing rectangle

interface Rectangle {
    fun draw(): String
}

class ButtonImage (val w: Int, val h: Int) : Rectangle {
    override fun draw() =
        &quot;drawing with $w and $h&quot;
}
```

Next is the mouse event manager.

```kotlin
interface MouseManager {
    fun click(): Boolean
}

class UserInput : MouseManager {
    override fun click() = true
}
```

Finally, here is our `Button`.

```kotlin
class Button(image: Rectangle, input: MouseManager) :
    Rectangle by image, MouseManager by input

fun main() {
    val buttonImage = ButtonImage(10, 5)
    val userInput = UserInput()

    button = Button(buttonImage, userInput)
    button.draw()
    button.click()
}
```

### Summary

Inheritance can be constraining. We cannot inherit a class when the superclass is not `open` or our class is already extending another class. Class delegation can help us with that.

Usually, there are 3 choices: _inheritance_, _composition_ and _class delegation_. Try **_composition_** first. it is the simplest one and solves most of use cases. If you really need a hierarchy of type, then go for inheritance. If none of them can work, then think about class delegation.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Another look in Inheritance</title><link>https://htswe.github.io/blog/another-look-in-inheritance/</link><guid isPermaLink="true">https://htswe.github.io/blog/another-look-in-inheritance/</guid><description>We touched a bit on Inheritance concept. Inheritance is sometimes used to add functions to a class as a way of reuse for a new purpose.</description><pubDate>Mon, 03 Jan 2022 00:00:00 GMT</pubDate><content:encoded>We touched a bit on Inheritance concept. Inheritance is sometimes used to add functions to a class as a way of reuse for a new purpose.

But is this always a good choice?

Class delegation is midway between composition and inheritance. Like composition, we have to place the member inside our class. Like inheritance, it exposes the interface of the sub object.

```kotlin
open class Heater {
    fun heat(temp: Int) = &quot;Heating to $temp&quot;
}

class Aircon: Heater() {
    fun cool(temp: Int) = &quot;Cooling to $temp&quot;
}

fun warmingUp(heater: Heater) {
    heater.heat(70)
}

fun upAndDown(aircon: Aircon) {
    aircon.heat(70)
    aircon.cool(20)
}

val heater = Heater()
val aircon = Aircon()
warmingUp(heater)
warmingUp(aircon)
upAndDown(aircon)
```

The code above is seen logical. Since `Heater` cannot do all the functions we want, we need to create `Aircon` who inherits `Heater` and then add some extra cooling functions. However, you might recall in Upcasting that when you upcast, you lose some info.

&gt; Liskov Substitution Principle says functions that accept a base class must be able to use the objects of derived classes without knowing it. It is all substitutability.

`warmingUp()` takes `heater` as argument and also accept `aircon` due to _Liskov Substitution Principle_. You might lose some useful info about `aircon` during upcasting. Although modern OO programming allows the addition of functions during inheritance, this can be a “code smell”. It might negatively impact a later maintainer of the code as _technical debt_.

### Alternative

What we really wanted in previous example is a `Heater` class with `cool()` function, so that `upAndDown` function works. Why not extension function? It does the same thing without inheritance.

```kotlin
fun Heater.cool(temp: Int) = &quot;Cooling to $temp&quot;

fun upAndDown(heater: Heater) {
    aircon.heat(70)
    aircon.cool(20)
}
```

### Interface by Convention

An extension function can be considered as creating an interface containing a single function.

```kotlin
class X
fun X.f() {}

class Y
fun Y.f() {}

callF(x:X) = x.f()
callF(y:Y) = y.f()
```

Although both `X` and `Y` has a member function `f()`, but we don’t get polymorphic behaviour. `callF()` have to make separately for `X` and `Y`. The “interface by convention” is extensively used in Kotlin libraries, especially when dealing with collections.

### Members vs Extension

There are cases where you are forced to use member functions rather than extensions. If a function must access a `private` member, you have no choice but to make it a member function:

```kotlin
class Z(var i: Int = 0) {
    private var j = 0
    fun inc() {
        i++
        j++
    }
}

fun Z.dec() {
    i--
    //j--
}
```

the variable `j` is not accessible since it is a private member of the class. The main drawback of the extension function is that they cannot be overridden.

### Summary

Languages like C++ and Java allow inheritance unless you specially disallow it. Kotlin assumes that you won’t be using inheritance – it actively prevents inheritance and polymorphism unless they are intentionally allowed using the `open` keyword.

&gt; Often, functions are all you need. Sometimes objects are very useful. Objects are one tool among many, but they’re not for everything.

Consider whether you need inheritance at all, and apply the maxim _Prefer extension functions and composition to inheritance_.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Composition</title><link>https://htswe.github.io/blog/composition/</link><guid isPermaLink="true">https://htswe.github.io/blog/composition/</guid><description>One of most compelling arguments for object oriented programming is code reuse.</description><pubDate>Mon, 03 Jan 2022 00:00:00 GMT</pubDate><content:encoded>One of most compelling arguments for object oriented programming is **_code reuse_**.

When i was a noob, when I heard the word &quot;reuse&quot;, I thought it was &quot;copying code&quot;. Copying seems an easy solution, but in reality, it doesn&apos;t work very well. As time passes, the requirements change. Applying the changes to all the duplicate codes become a maintenance nightmare. The question of &quot;Did you find all the copies?&quot; is always haunting me? And then you wish the reused code can be changed in just one place.

In object-oriented programming, we will reuse code by creating new classes, but instead of creating them from scratch, we use existing classes that someone has already built and debugged. The trick is to use the classes without dirtying the existing code.

Inheritance is one way to achieve this. Inheritance creates a new class as a _type of_ an existing class. You add code to the form of the existing class without modifying the original. Inheritance is a _cornerstone of object-oriented programming_.

### Composition

You can also choose a simpler approach, by creating objects of existing classes inside the new class. It is called _composition_. The new class is composed of objects of existing codes.

Composition is a _has-a_ relationship. &quot;A house is a building and has a room&quot; can be expressed:

```kotlin
interface Building
interface Room

interface House : Building {
    val room: Room
}
```

If your house has two rooms, the composition makes it easy to change:

```kotlin
interface House: Building {
    val room_one: Room
    val room_two: Room
}
```

### What to pick? Composition or Inheritance

Both composition and inheritance put object inside the new class. **Composition** has explicit objects while **Inheritance** has implicit objects.

**Composition** provides the functionality of an existing class, but not its interface. Usually you embed an object to use its features. To hide the object completely, you can make the object `private`.

```kotlin
class Existing {
    fun f1() = &quot;feature1&quot;
    fun f2() = &quot;feature2&quot;
}

class CompositionClass {
    private val existing = Existing()
    fun operation() = existing.f1() + existing.f2()
}
```

The users of `CompositionClass` will not have any idea that it is using the `Existing()` since we hide it under `private`. In case we find a better way to do the operation with another different class, we can modify it without impacting the user of `CompositionClass`.

If `CompositionClass` inherited `Existing`, the client now has to cast `CompositionClass` to `Existing`. The inheritance makes the relationship explicit. If you want to change `Existing`, you will break code that relies upon the connection.

### Summary

If you stuck with your code using inheritance, then give a try using composition. Sometimes, it might make your code cleaner. If you think your code need changes in near future, go with composition first because it will allow you to swap the underlying objects without breaking any of the clients.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Polymorphism</title><link>https://htswe.github.io/blog/polymorphism/</link><guid isPermaLink="true">https://htswe.github.io/blog/polymorphism/</guid><description>One of the Object Oriented Programming concept is the ability of polymorphism. The word, polymorphism is an ancient Greek term. It means many forms. In programming context, polymorphism means an obje…</description><pubDate>Wed, 22 Dec 2021 00:00:00 GMT</pubDate><content:encoded>One of the **Object Oriented Programming** concept is the ability of _polymorphism_. The word, _polymorphism_ is an ancient Greek term. It means **_many forms_**. In programming context, _polymorphism_ means an object or its members have multiple implementations.

Let&apos;s consider an object `Pet`. The `Pet` class says that all pets can `speak()`. `Dog` and `Cat` override the `speak()` member function.

```kotlin
open class Pet {
  open fun speak() = &quot;Pet&quot;
}

class Dog : Pet() {
  override fun speak() = &quot;Woff&quot;
}

class Cat : Pet() {
  override fun speak() = &quot;Meow&quot;
}

fun talk(pet: Pet) = pet.speak()

talk(Dog())
talk(Cat())
```

`talk()` doesn’t know the exact type of `Pet` it receives. Despite that, when you call `speak()` through a reference to the base-class `Pet`, the correct subclass implementation is called, and you get the desired behaviour.

Polymorphism occurs when a parent class reference contains a child class instance. **_When you call a member on that parent class reference, polymorphism produces the correct overridden member from the child class._**

### Binding

Connecting a function call to a function body is called _binding_. Ordinarily, you don’t think much about binding because it happens **_statically, at compile time_**.

With polymorphism, the same operation must behave differently for different types—but the compiler cannot know in advance which function body to use. The function body must be determined **_dynamically, at runtime_**, using _dynamic binding_.

Dynamic binding is also called _late binding_ or _dynamic dispatch_. Only at runtime can Kotlin determine the exact `speak()` function to call. Thus we say that the binding for the polymorphic call `pet.speak()` occurs dynamically.

### Summary

Dynamic binding isn’t free. The additional logic that determines the runtime type slightly impacts performance compared to static binding. To force clarity, Kotlin defaults to closed classes and member functions. To inherit and override, you must be explicit (`open`).

A language feature such as the `when` statement can be learned in isolation. Polymorphism cannot—it only works in concert, as part of the **_larger picture_** of class relationships. To use object-oriented techniques effectively, you must expand your perspective to include not just members of an individual class, but also the commonality among classes and their relationships with each other.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Upcasting class</title><link>https://htswe.github.io/blog/upcasting-class/</link><guid isPermaLink="true">https://htswe.github.io/blog/upcasting-class/</guid><description>Taking an object reference and treating it as a reference to its base type is called upcasting.</description><pubDate>Wed, 15 Dec 2021 00:00:00 GMT</pubDate><content:encoded>What is upcasting?

&gt; Taking an **object** reference and treating it as a reference to its **base** type is called upcasting.

The term _upcast_ refers to the way inheritance hierarchies are traditionally represented with the base class at the top and derived classes fanning out below.

Inheritance and adding new member functions is the practice in [Smalltalk](https://en.wikipedia.org/w/index.php?title=Smalltalk&amp;action=view&amp;section=3#Object-oriented_programming), one of the first successful object-oriented languages in Smalltalk, everything is an object and the only way to create a class is to inherit from an existing class, often adding new member functions. Smalltalk heavily influenced Java, which also requires everything to be an object.

### Kotlin&apos;s way

Kotlin frees us from these constraints. We have stand-alone functions so everything doesn&apos;t need to be contained within the classes. _Extension functions_ allow us to add functionality without inheritance. Indeed, requiring the `open` keyword for inheritance makes it a very conscious and intentional choice, not something to use all the time.

### why upcast

Let&apos;s imagine this. We have 3 objects (`Circle`, `Square` and `Triangle`) that inherit the `Shape`. And we have a function -

```kotlin
fun show(shape: Shape) = print(shape.toString)
```

```mermaid
graph BT
B(Circle) --&gt; D(Shape)
C(Square) --&gt; D
A(Triangle) --&gt; D
```

When we pass a `Circle`, `Square` or `Triangle` as an argument of type `Shape` in the `show()`, we cast up the inheritance hierarchy. In the process of upcasting, we lose the specific information about whether an object is of type `Circle`, `Square` or `Triangle`. It becomes nothing more than a `Shape` object.

Treating a specific type as a more generic type is the entire point of inheritance. The mechanics of inheritance exist solely to fulfil the goal of upcasting to the base type. Because of this abstraction (aka _everything is a `Shape`_), we can write a single `show` function of writing one for each of every type of elements. Upcasting is a way to reuse the code for objects.

### Composition over inheritance

Indeed, in virtually every case where there&apos;s inheritance without upcasting, inheritance is being misused -- it&apos;s unnecessary, and it makes the code needlessly complicated. The misuse is the reason for the maxim in Software Design:

&gt; Prefer [composition over inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance)

If the point of inheritance is the ability to substitute a derived type for a base type, what happens to the extra member functions: `color()` in `Square` and `rotate()` in `Triangle`?

_Liskov Substitution Principle_ says that after upcasting, the derived type can be treated exactly like the base type. This means that any member functions added to the derived class are, in effect, &quot;trimmed&quot;. They still exist, but because they are not part of base class interface, they are unavailable.

### Summary

Upcasting is a way to reuse the code for objects. One important thing to take note is that after the upcast, you can only call members of the base type.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Abstract or Interface</title><link>https://htswe.github.io/blog/abstract-or-interface/</link><guid isPermaLink="true">https://htswe.github.io/blog/abstract-or-interface/</guid><description>An abstract class is like an ordinary class except one or more functions or properties is incomplete - ie. a function without implementation or a property without initialisation.</description><pubDate>Thu, 09 Dec 2021 00:00:00 GMT</pubDate><content:encoded>An _abstract class_ is like an ordinary class except one or more functions or properties is incomplete - ie. a function without implementation or a property without initialisation.

```kotlin
abstract class myAbstract {
    abstract val x: Int
    val y: Int

    abstract fun f(): Int
    abstract fun g(n: Int)
}
```

All functions and properties declared in an _interface_ are abstract by default, which makes an interface similar to an _abstract class_.

```kotlin
interface myInterface {
    val x: Int
    fun f(): Int
    fun g(n: Int)
}
```

### What is the difference between abstract class and interface?

1. The difference is that an _abstract class_ can contain **_state_**, while an interface cannot. State is the data stored inside properties.

```kotlin
interface myInterface {
    val x: Int
    // val x: Int = 10 won&apos;t work
}
```

2. Both interface and abstract class can contain functions with implementation.

```kotlin
interface Parent {
    val f(): Int
    fun g() = &quot;hello ${f()}&quot;
}

class Hello: Parent {
    override fun f() = 100
}

print(Hello().g()) // hello 100
```

3. In Kotlin, a class can only inherit from a single base class. Java works the same too. The original Java designers decided that C++ multiple inheritance was a bad idea. The main complexity and dissatisfaction at that time came from multiple _state_ inheritance. Java solves this by introducing interfaces, which cannot contain state. Java allows multiple interface inheritance, but forbids multiple state inheritance. Kotlin follows.

```kotlin
interface Animal
interface LandAnimal : Animal
interface WaterAnimal : Animal

class Turtle: Animal, WaterAnimal
```

### Summary

You might wonder why we need interfaces when abstract class can do more than what an interface could. The answer is multiple inheritance. Both are designed to solve different problem and knowing what to use will make the programmer life easier.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Ask for inheritance</title><link>https://htswe.github.io/blog/ask-for-inheritance/</link><guid isPermaLink="true">https://htswe.github.io/blog/ask-for-inheritance/</guid><description>Inheritance is a mechanism for creating a new class by reusing and modifying an existing class.</description><pubDate>Thu, 02 Dec 2021 00:00:00 GMT</pubDate><content:encoded>Inheritance is a mechanism for creating a new class by reusing and modifying an existing class.

In order to do this, in Kotlin, the base class must be `open`. A non-`open` class doesn’t allow inheritance – it is `closed` by default. This differs from most other object-oriented languages.

For example, in Java, a class is inheritable automatically unless you explicitly forbid by declaring it as `final`.

```kotlin
open class Solider {
  val id: String = 1
  val age: Int = 25
}

class Corporal: Solider()
class Sergeant: Solider()
```

**Inheritance** gets interesting when you start _overriding_ functions, which means redefining a function from a base class to do something different a derived class.

```kotlin
open class Solider {
  protected var energy = 0
  open fun reportTo() = &quot;General&quot;
  fun energyLevel() = &quot;Energy: $energy&quot;
}

class Corporal: Solider() {
  override fun reportTo() = &quot;Sergeant&quot;
  fun serviceYear() = 10
}
```

### Summary

Kotlin imposes an additional constraint when overriding functions. Just like base class, you cannot `override` function from a base class unless it is defined as `open`. Inheritance and overriding cannot be accomplished in Kotlin without clear intentions.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Primary Constructor vs Secondary Constructor</title><link>https://htswe.github.io/blog/primary-constructor-vs-secondary-constructor/</link><guid isPermaLink="true">https://htswe.github.io/blog/primary-constructor-vs-secondary-constructor/</guid><description>A constructor is a special function that creates a new object. Using var or val in the parameter list makes them accessible from outside the object.</description><pubDate>Thu, 02 Dec 2021 00:00:00 GMT</pubDate><content:encoded>A `constructor` is a special function that creates a new object. Using `var` or `val` in the parameter list makes them accessible from outside the object.

```kotlin
class Hero(val name: String)

val hero = Hero(&quot;superman&quot;)
print(hero.name)
```

In the case above, Kotlin wrote the constructor code fro us. For more customization, we can use the `init` section. `init` section is executed during the object creation:

```kotlin
class Hero(val name: String) {
  private val about: String
  init {
    about = &quot;$name is a brave hero&quot;
  }
  fun toString() = about
}

val superman = Hero(&quot;superman&quot;)
print(superman.toString())
```

### Secondary constructor

When you are creating an object, sometimes, you might require several ways to construct. You may use named and default arguments - they are easier approach, but sometimes, you must create multiple overloaded constructors.

In Kotlin, overloaded constructors are called _secondary constructors_. To create a secondary constructor, use the `constructor` keyword followed by a parameter list that’s distinct from all other primary and secondary lists.

```kotlin
class SampleSecondary(i: Int) {
  init {
    print(&quot;Primary $i&quot;)
  }
  constructor(s: String) : this(s.first()) {
    print(&quot;Secondary $s&quot;)
  }
}
```

### Summary

A constructor is the combination of its constructor parameter list – initialized before entering the class body and the `init` section executed during object creation. Kotlin allows multiple `init` sections, which are executed in definition order. But having multiple sections, may produce maintenance issues for programmers who are accustomed to a single `init` section.</content:encoded><category>kotlin</category><category>object oriented programming</category></item><item><title>Making recursion more efficient with tailrec</title><link>https://htswe.github.io/blog/making-recursion-more-efficient/</link><guid isPermaLink="true">https://htswe.github.io/blog/making-recursion-more-efficient/</guid><description>Recursion is the programming technique of calling the function within the same function. A recursive function uses the result from the previous recursive call. The perfect example for recursion is fi…</description><pubDate>Wed, 24 Nov 2021 00:00:00 GMT</pubDate><content:encoded>### What is recursion?

_Recursion_ is the programming technique of calling the function within the same function. A recursive function uses the result from the previous recursive call. The perfect example for recursion is `fibonacci(n)`.

If we have to describe in the code:

```kotlin
fun fibonacci(n: Long) : Long {
  return when (n) {
    0L -&gt; 0
    1L -&gt; 1
    else -&gt;
      fibonacci(n - 1) + fibonacci(n - 2)
  }
}
```

### Tail Recursion

While it is easy to read the recursive function, it&apos;s expensive. When calling a function, the information about that function and its arguments are stored in `call stack`. When you call a recursive function, each recursive invocation adds a frame to the call stack. This can easily produce a `StackOverflowError` which means it runs out of memory.

To prevent call stacks overflows, functional languages (including Kotlin) use a technique call _tail recursion_. The goal is to reduce the size of the call stack. The way to do is by using the keyword `tailrec`. Under the right conditions, this will convert recursive calls into iteration, eliminating call-stack overhead. This is a **complier optimisation** , but it doesn&apos;t work for all recursive calls.

To use `tailrec` successfully, recursion must be the final operation, which means there can be no extra calculations on the result of the recursive call before it is returned.

Remember that `fibonacci` implementation - it is terribly inefficient because the previously-calculated results are not reused. Thus, the number of operations grows exponentially.

With tail recursion, the calculations become dramatically more efficient.

```kotlin
fun fibonacci(n: Int): Long {
  tailrec fun fibonacci(
    n: Int,
    current: Long,
    next: Long
  ): Long {
    if (n == 0) return current
    return fibonacci(
      n - 1,
      next,
      current + next
    )
  }

  return fibonacci(n, 0L, 1L)
}
```

We use the local function to conceal the `fibonacci` function so that the user cannot put other values in those defaults, which produce incorrect results. The only function that the user can see is `fibonacci(n)`.

## Summary

While it is easy to read, it&apos;s expensive. When calling a function, the information about that function and its arguments are stored in `call stack`. When you call a recursive function, each recursive invocation adds a frame to the call stack. This can easily produce a `StackOverflowError` which means it runs out of memory.

Use `tailrec` technique wherever applicable to make the function more efficient.</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Elegant Local Function</title><link>https://htswe.github.io/blog/elegant-local-function/</link><guid isPermaLink="true">https://htswe.github.io/blog/elegant-local-function/</guid><description>What exactly is local function? It was new to me in Kotlin and thought it is interesting to dig deeper. In a normal class, we have many functions within a class - the functions have names so that we…</description><pubDate>Sat, 20 Nov 2021 00:00:00 GMT</pubDate><content:encoded>What exactly is local function? It was new to me in Kotlin and thought it is interesting to dig deeper. In a normal class, we have many functions within a class - the functions have names so that we know which functions are linked to each other.

&gt; Local functions are the functions with names that are defined within other functions.

So what is it for? Well, local functions reduce duplication by extracting the repetitive code. Moreover, they are only visible within the surrounding function, so they don’t mess up your code readability.

Let’s see an example :

```kotlin
fun doPrint() {
  val buffer = StringBuilder()

  fun printWarning(message: String) =
    buffer.appendLine(&quot;Warning: $message&quot;)

  printWarning(&quot;Your attention please&quot;)
  val num = 123
  printWarning(&quot;Do not use the line number: $num&quot;)

  val result = buffer.toString()
  // Warning: Your attention please
  // Warning: Do not use the line number: 123
}
```

Notice that `printWarning()` has access to `buffer` - because local functions are _closures_, so you don’t have to pass additional parameters.

### With Function Reference

You can refer to a local function using a function reference:

```kotlin
class Event(
  val title: String,
  val location: String
)
```

```kotlin
events = listOf(
  Event(&quot;Kotlin&quot;, &quot;Room A&quot;),
  Event(&quot;Swift&quot;, &quot;Room B&quot;)
)

fun mustAttend(event: Event): Boolean {
  if (event.title.contains(&quot;Kotlin&quot;) {
    return true
  }
  return false
}

val result = events.any(::mustAttend)
// true
```

### With anonymous function

The function `mustAttend()` is only used once, so you might inclined to define as a `lambda`. An alternative is using _anonymous_ function.

&gt; Anonymous functions are defined within other functions - but no name. They are similar to lambdas, but use the fun keyword.

```kotlin
events.any(
  fun(event: Event): Boolean {
    if (event.title.contains(&quot;Kotlin&quot;) {
      return true
    }
    return false
  }
)
```

## Summary

If a lambda becomes too complicated and hard to read, replace it with a local function or an anonymous function.

```kotlin
fun usingAnonymous: (Int) -&gt; Int {
  val func = fun(i:Int) = i + 1
  val result = func(1) // 2
}
```

```kotlin
fun usingLambda(): (String) -&gt; String {
  val func2 = { s: String -&gt; &quot;$s!&quot; }
  return func2(&quot;abc&quot;)
}
```

```kotlin
fun usingRef(): () -&gt; String {
  fun greet() = &quot;Hi!&quot;
  return ::greet
}
```

```kotlin
fun usingRefCompact() = fun() = &quot;Hi!&quot;
```

```kotlin
fun usingLambdaCompact() = { &quot;Hi!&quot; }
```</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Folding and Reducing List</title><link>https://htswe.github.io/blog/folding-and-reducing-list/</link><guid isPermaLink="true">https://htswe.github.io/blog/folding-and-reducing-list/</guid><description>fold() combines all elements of a list, in order to generate a single result. Here is how we can use fold() to calculate the sum -</description><pubDate>Sat, 20 Nov 2021 00:00:00 GMT</pubDate><content:encoded>`fold()` combines all elements of a list, in order to generate a single result. Here is how we can use `fold()` to calculate the sum -

```kotlin
val list = listOf(1, 2, 3, 4)
list.fold(0) { sum, n -&gt;
  sum + n
}
// 10
```

`foldRight()` processes elements starting from right to left, as opposed to `fold()` which processes the elements from left to right. This example demonstrates the difference:

```kotlin
val list = listOf(&apos;a&apos;, &apos;b&apos;, &apos;c&apos;, &apos;d&apos;)

list.fold(&quot;x&quot;) { acc, ele -&gt;
  &quot;$[acc] + $ele&quot;
} // [[[[x] + a] + b] + c] + d

list.foldRight(&quot;x&quot;) { acc, ele -&gt;
  &quot;$[acc] + $ele&quot;
} // [[[[x] + d] + c] + b] + a
```

### Reduce List

`fold()` and `foldRight()` take an explicit accumulator value as the first argument. Sometimes, the first element can act as an initial value. `reduce()` and `reduceRight()` behave like `fold()` and `foldRight()` but use the first and last element respectively as the initial value:

```kotlin
val chars = &quot;a b c d&quot;.split(&quot; &quot;)

chars.fold(&quot;x&quot;) { acc, ele -&gt; &quot;$acc $ele&quot; }
// x a b c d
chars.reduce { acc, ele -&gt; &quot;$acc $ele&quot; }
// a b c d

chars.foldRight(&quot;x&quot;) { acc, ele -&gt; &quot;$acc $ele&quot; }
// a b c d x
chars.reduceRight { acc, ele -&gt; &quot;$acc $ele&quot; }
// a b c d
```

### Running List

`runningFold()` and `runningReduce()` produce a `List` containing all the intermediate steps of the process. The final value in the `List` is the result of the `fold()` or `reduce()`:

```kotlin
val list = listOf(1, 2, 3, 4)

list.runningFold(10) { sum, n -&gt;
  sum + n
} // [10, 11, 12, 13, 14]

list.runningReduce { sum, n -&gt;
  sum + n
} // [11, 12, 13, 14]
```</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Sequence: lazy evaluation</title><link>https://htswe.github.io/blog/sequence-lazy-evaluation/</link><guid isPermaLink="true">https://htswe.github.io/blog/sequence-lazy-evaluation/</guid><description>What is Sequence? A Kotlin Sequence is like a List, but you can only iterate. You cannot index into Sequence. And this restriction produces very efficient chained operations.</description><pubDate>Wed, 17 Nov 2021 00:00:00 GMT</pubDate><content:encoded>What is `Sequence`? A Kotlin Sequence is like a `List`, but you can only iterate. You cannot index into `Sequence`. And this restriction produces very efficient chained operations.

In other functional programming languages, Kotlin `Sequence` are called `streams`. Since Java 8 has `Stream` library, Kotlin has to choose another name to keep interoperability with Java.

### List vs Sequence

The operation on Lists are performed eagerly - they always happen immediately. When chaining List operation, the first result must be done before starting the next.

```kotlin
list.listOf(1, 2, 3, 4)
  .filter { it % 2 == 0 }
  .any { it &gt; 0 }
```

![eager evaluation](/assets/images/eager-evaluation.png)

In this example, `filter()` operation from `1` to `n` must be completed before it can go to `any()` operation. Eager evaluation is intuitive and straightforward, but can be **_suboptimal_**. If you look carefully on the above example, it would make more sense to stop after encountering the first element that will satisfies the `any()`. This optimization might be much faster than evaluating every element and then search for a single match.

&gt; Eager evaluation is called horizontal evaluation.

The alternative to _eager evaluation_ is _lazy evaluation_ : a result is computed only when needed.
![lazy evaluation](/assets/images/lazy-evaluation.png)

&gt; Performing lazy operations on sequence is called vertical evaluation.

With lazy evaluation, an operation is performed on an element only when that element’s associated result is requested. If the final result of a calculation is found before processing the last element, no further elements are processed.

This lazy evaluation optimization is simply done by converting `List` to `Sequence` using `asSequence()`.

```kotlin
list.listOf(1, 2, 3, 4)
  .asSequence()
  .filter { it % 2 == 0 }
  .any { it &gt; 0 }
```

### Two types of operation

There are two categories of `Sequence` operations: _intermediate_ and _terminal_. Intermediate operations return another `Sequence` as a result. `filter()` and `map()` are intermediate operations.

Terminal operations return a non-Sequence. To do this, a terminal operation executes all stored computations. For example, `any()` is the terminal operation that returns `Boolean`.

### Size of Sequence

`Collections` are a known size, discoverable through their `size` property. `Sequences` are treated as if they are **infinite**.

So what happen if we want to get some items - `takeIf` can be used, followed by a terminal operation like `toList()` or `sum()`.

```kotlin
items.takeIf { it % 2 == 0 }.toList()
```

## Summary

Sequences are a part of the language standard library and allow lazy evaluation of large amount of data (in millions), as opposed to collections, which compute and evaluate operations on a data set _eagerly_.</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Some awesome functions in Kotlin Map</title><link>https://htswe.github.io/blog/some-awesome-functions-kotlin-map/</link><guid isPermaLink="true">https://htswe.github.io/blog/some-awesome-functions-kotlin-map/</guid><description>Maps are extremely useful programming tools, and there are numerous ways to construct them. Let’s recap what we learned in List.</description><pubDate>Tue, 16 Nov 2021 00:00:00 GMT</pubDate><content:encoded>### Map

`Maps` are extremely useful programming tools, and there are numerous ways to construct them. Let’s recap what we learned in `List`.

```kotlin
data class Person(val name: String, val age: Int)

val names = listOf(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charles&quot;)
val ages = listOf(10, 10, 20)

fun people(): List&lt;Person&gt; =
  names.zip(ages) { name, age -&gt;
    Person(name, age)
  }
```

### Filter or Group By

Based on the previous, what if you want to find out all the persons who are 10 years old? You may tempt to use `filter()` to do this.

```kotlin
people().filter { it.age == 10 }
```

You can also do this by using `groupBy()`.

```kotlin
val map = people().groupBy(Person::age)
// map[10]
```

Which one is preferred? I think `groupBy()` might be a better candidate as you only have to write only once. With `filter()`, you might have to write another filter if you want to find people who are 20 years old, for example.

If you only need two groups, then `partition()` function is more direct because it divides the contents into two lists based on the predicate. `groupBy()` is appropriate when you need more than two resulting groups.

### AssociateWith or AssociateBy

`associateWith()` allows to take a list of keys and build a `Map` by associating each of these keys with a value created by its parameter.

Example:

```kotlin
val result: Map&lt;Person, String&gt;
  = people().associateWith { it.name }
/* result will be
mapOf(
  Person(&quot;Alice&quot;, 10) to &quot;Alice&quot;,
  Person(&quot;Bob&quot;, 10) to &quot;Bob&quot;,
  Person(&quot;Charles&quot;, 20) to &quot;Charles&quot;
)
*/
```

`associateBy` is the reverse of `associateWith`.

```kotlin
val result: Map&lt;Person, String&gt;
  = people().associateBy { it.name }
/* result will be
mapOf(
  &quot;Alice&quot; to Person(&quot;Alice&quot;, 10),
  &quot;Bob&quot; to Person(&quot;Bob&quot;, 10),
  &quot;Charles&quot; to Person(&quot;Charles&quot;, 20)
)
*/
```</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Zipping and Flattening List</title><link>https://htswe.github.io/blog/zipping-and-flattening-list/</link><guid isPermaLink="true">https://htswe.github.io/blog/zipping-and-flattening-list/</guid><description>We love List. In fact, many of our work involve using List to store many piece of information. We then apply different operations on List to make it what we need for our application.</description><pubDate>Tue, 16 Nov 2021 00:00:00 GMT</pubDate><content:encoded>### List Manipulation

We love `List`. In fact, many of our work involve using `List` to store many piece of information. We then apply different operations on `List` to make it what we need for our application.

Have you worked with two `Lists`? _Zipping_ and _flattening_ are two common operations that manipulate `Lists`.

### Zipping

`zip()` combines two `Lists` by mimicking the behavior of the zipper on your jacket, pairing adjacent `List` element.

```kotlin
val a = listOf(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;)
val b = listOf(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;)

a.zip(b)
// [(&quot;1&quot;,&quot;x&quot;), (&quot;2&quot;,&quot;y&quot;), (&quot;3&quot;,&quot;z&quot;)]
```

`zip()` can perform interesting operation on those `Pair` as well.

```kotlin
data class Person (val name: String, val age: Int)

val names = listOf(&quot;alice&quot;, &quot;bob&quot;, &quot;charlie&quot;)
val ages = listOf(20, 30, 40)

names.zip(ages) { name, age -&gt;
  Person(name, age)
}
// array of person objects
```

**Q**: Do you need two lists to perform `zip()` operation?
You can use `zipWithNext()` on a single List to generate a list of `Pair`.

```kotlin
val alphabets = listOf(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;)
alphabets.zipWithNext()
// [(&quot;a&quot;,&quot;b&quot;), (&quot;b&quot;,&quot;c&quot;)]
```

### Flattening

![flattening](https://images.pexels.com/photos/5964531/pexels-photo-5964531.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=650&amp;w=940)

`flatten()` takes a `List` containing elements that are themselves `Lists`.

```kotlin
val nestedList = listOf(
  listOf(1, 2),
  listOf(3, 4)
)

nestedList.flatten()
// [1, 2, 3, 4]
```

Kotlin provides a combined operation called `flatMap()`, which performs both `map()` and `flatten()` with a single call. You can find `flatMap()` in most of the functional programming languages.

```kotlin
data class Book(val title: String, val authors: List&lt;String&gt;)

val books = listOf(
  Book(&quot;Gone with the wind&quot;, listOf(&quot;Margaret Mitchell&quot;),
  BooK(&quot;Harry Porter&quot;, listOf(&quot;JK Rowling&quot;)
)

books.map { it.authors }.flatten()
books.flatMap { it.authors }
// listOf(&quot;Margaret Mitchell&quot;, &quot;JK Rowling&quot;)
```</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Higher-Order Function</title><link>https://htswe.github.io/blog/higher-order-function/</link><guid isPermaLink="true">https://htswe.github.io/blog/higher-order-function/</guid><description>What is it? If you are coming from JavaScript, this concept may sound familiar to you. Otherwise, here is what it means.</description><pubDate>Mon, 15 Nov 2021 00:00:00 GMT</pubDate><content:encoded>What is it? If you are coming from JavaScript, this concept may sound familiar to you. Otherwise, here is what it means.

&gt; If a function can accept another function as arguments and produces functions as return values, then that programming language supports higher-order function.

### Using Lambda

In Kotlin, you can store a lambda in a reference.

```kotlin
val isPositive: (Int) -&gt; Boolean = { it &gt; 0 }

listOf(1, 0, -1).any(isPositive)
// true
```

### Using References

We talked about property references in replacement of lambda.

In the example below, we will also look at how you can make use of generic function as argument in higher-order function.

```kotlin
fun &lt;T&gt; List&lt;T&gt;.any(
  predicate: (T) -&gt; Boolean
): Boolean {
  for (element in this) {
    if (predicate(element))
      return true
  }
  return false
}

val ints = listOf(1, 0, -1)
ints.any( it &gt; 0 ) //true

val texts = listOf(&quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;)
texts.any( it.isBlank() ) // false
texts.any( String::isBlank ) // false
```

## Summary

Higher-order functions are an essential part of functional programming languages. In Kotlin, we have used it in many places using the built-in higher-order functions such as `filter()`, `map()` and `any()`.</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Is Kotlin truly functional</title><link>https://htswe.github.io/blog/is-kotlin-truly-functional/</link><guid isPermaLink="true">https://htswe.github.io/blog/is-kotlin-truly-functional/</guid><description>A truly functional programming language like Javascript allows us to assign the function as a variable. Take an example of this:</description><pubDate>Sun, 14 Nov 2021 00:00:00 GMT</pubDate><content:encoded>### Background

A truly functional programming language like Javascript allows us to assign the function as a variable. Take an example of this:

```javascript
// JavaScript
const square = function (number) {
  return number * number;
};
var x = square(4); // x gets the value 16
```

Can Kotlin do the same? We can save the lambda in a variable, but not the function. But there is alternative - which is **Member References** which we are going to look into it.

### Member References

_Member references_ for function, property and constructor can replace trivial lambdas that simply call the corresponding function, property or constructor.

A member reference uses a double colon to separate the class name from the function or property. For example, `Message::isRead` is a member reference.

```kotlin
data  class  Message(
  val sender: String,
  val text: String,
  val isRead: Boolean
)

val messages = listOf(
  Message(&quot;Sheldon&quot;, &quot;smart&quot;, true),
  Message(&quot;George&quot;, &quot;handsome&quot;, false)
)

val unread = messages.filterNot(Message::isRead)
// Message(&quot;George&quot;, &quot;smart&quot;, false)
```

### Property References

Property references are useful when specifying a non-trivial sort order.

```kotlin
val messages = listOf(
  Message(&quot;Sheldon&quot;, &quot;smart&quot;, true),
  Message(&quot;George&quot;, &quot;handsome&quot;, false),
  Message(&quot;Missy&quot;, &quot;beautiful&quot;, true)
)

// first unread, sorted by sender
messages.sortedWith(compareBy(Message::isRead, Message::sender))
```

### Function References

Suppose you want a list of messages which contains some important stuffs. That means you might now have a number of complicated criteria to decide what “important” means. You can put that logic in a lambda, but that lambda could easily become large and complex. The code is more understandable if you extract it into a separate function.

&gt; In Kotlin, you can’t pass a function where a function type is expected, but you can pass a reference to that function.

```kotlin
fun Message.isImportant(): Boolean =
  text.contains(&quot;Salary&quot;) || text.contains(&quot;Promotion&quot;)

val messages = listOf(
  Message(&quot;Boss&quot;, &quot;Salary Adjustment&quot;, false)
)

messages.any(Message::isImportant)
```

If there is a top-level function taking `Message` as its only parameter, you can pass it as a reference. When you create a reference to a top-level function, there’s no class name, so it’s written `::function`

```kotlin
fun ignore(message: Message) =
  message.isImportant.not()
  &amp;&amp; message.sender in setOf(&quot;Dan&quot;, &quot;Charles&quot;)

messages.filter(::ignore)
```

### Constructor References

You can create a reference to a constructor using the class name.

```kotlin
data class Student(
  val id: Int,
  val name: String
)

val names = listOf(&quot;Alice&quot;, &quot;Bob&quot;)
val students = names.mapIndexed { index, name -&gt;
  Student(index, name)
}

// same thing is achieved with
val usingRef = names.mapIndexed(::Student)
```

`mapIndexed` was introduced in Lambda. Function and constructor references can eliminate specifying a long list of parameters that are simply passed into a lambda. It is also more readable than lambda.

## Summary

Like Java, Kotlin has member references, which can replace simple Lambdas that only call a member function or return a member property, it can convert Lambda to member reference automatically when it’s possible. You can store Lambda in a variable, however, you can’t store a function in a variable. It’s not like in a truly functional language where each function is a variable.

Function references allow you to store a reference to any defined function in a variable to be able to store it and qualitative it. Keep in mind that this syntax is just another way to call a function inside the Lambda, underlying implementation are the same.</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Things that you might not know about Collections</title><link>https://htswe.github.io/blog/things-you-not-know-collections/</link><guid isPermaLink="true">https://htswe.github.io/blog/things-you-not-know-collections/</guid><description>Most functional programming has a great support for working with collections and so is Kotlin. If you are coding with Kotlin for sometimes, you might notice about map(), filter(), any() and forEach().</description><pubDate>Thu, 11 Nov 2021 00:00:00 GMT</pubDate><content:encoded>Most functional programming has a great support for working with collections and so is Kotlin. If you are coding with Kotlin for sometimes, you might notice about `map()`, `filter()`, `any()` and `forEach()`.

In Kotlin programming, we use collections extensively - `List`, `MutableList` and etc.

### 1. Am i a constructor?

![constructor](https://www.justwatch.com/images/backdrop/174496094/s640/bob-the-builder)

Take a look at this piece of code

```kotlin
val list = List(5) { &apos;a&apos; + it }
// output: [a, b, c, d, e]
```

This version of the `List` constructor has two parameters - the size of the `List` and a lambda that initializes each `List` element.

&gt; Remember that if a lambda is the last argument, it can be separated from the argument list.

Next, let’s look at `MutableList`. It can be initialized the same way.

```kotlin
val mutableList = MutableList(5, { it })
// [0, 1, 2, 3, 4]
```

Here is the interesting piece - both `List()` and `MutableList()` are not constructors in the Collections. They are **_functions_**. Their names begin with upper case intentionally, to make them look like constructor.

### 2. Filter(), the best option?

![filter](https://sebastien-arbogast.com/wp-content/uploads/2009/01/entrepreneur.gif)

`filter()` returns a group of elements satisfying the given predicate. What if you want the remaining of the group? It is `filterNot()` - that will do the work. In life, sometimes, you want us both - then how?

```kotlin
val list = listOf(-3, -1, 0, 1, 3)
val isPositive = { i: Int -&gt; i &gt; 0 }

// Option 1
val posOpt1 = list.filter(isPositive)
val negOpt1 = list.filterNot(isPositive)

// Option 2
val (posOpt2,negOpt2) = list.partition { it &gt; 0 }
```

`partition()` produces a `Pair` object containing `Lists`.

### 3. Collection function on non comparable elements

![collections](https://aatestlabs.com/assets/img/pages/michigan-product-testing.jpg)

In `List`, we have functions like `sum()` or `sorted()` for a list of comparable elements. But what happens when we have a list of non-comparable elements? we have counterparts - `sumBy()` and `sortedBy()`.

```kotlin
data class Product {
  val title: String,
  val price: Double
}

val products = listOf(
  Product(&quot;Pen&quot;, 2.5),
  Product(&quot;Ruler&quot;, 1.0)
)

products.sumByDouble { it.price } // 3.5
products.sortedByDescending { it.price }
```

We have two functions `sumBy()` and `sumByDouble()` to sum integer and double values respectively. `sorted()` and `sortedBy()` sort the collection in ascending order, while `sortedDescending()` and` sortedByDescending()` sort the collection in descending order.

## Summary

Even though we only talk about `List`, operations like the above are also available for other collections like `Set`.</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Why Lambda</title><link>https://htswe.github.io/blog/why-lambda/</link><guid isPermaLink="true">https://htswe.github.io/blog/why-lambda/</guid><description>To some people, lambda may seem like syntax sugar, but it is more than that. If you have to repeat some codes with minor modification, you can leverage on the power of lambda.</description><pubDate>Fri, 05 Nov 2021 00:00:00 GMT</pubDate><content:encoded>To some people, `lambda` may seem like syntax sugar, but it is more than that. If you have to repeat some codes with minor modification, you can leverage on the power of lambda.

Let’s take a look at an example. Imagine we have a function that takes a list of `Int` and returns a list of even number.

```kotlin
fun filterForEven(nums: List&lt;Int&gt;): List&lt;Int&gt; {
  val result = mutableListOf&lt;Int&gt;()
  for (i in nums) {
    if (i % 2 == 0) result += i
  }
  return result
}
```

Now, we have another function that takes a list of `Int` and returns a list of numbers which are positive number.

```kotlin
fun filterForPositive(nums: List&lt;Int&gt;): List&lt;Int&gt; {
  val result = mutableListOf&lt;Int&gt;()
  for (i in nums) {
    if (i &gt; 0) result += i
  }
  return result
}
```

Those two functions can be replaced with

```kotlin
nums.filter { it % 2 == 0 }
nums.filter { it &gt; 0 }
```

This `lambda` expression is clearer, more concise and avoids repetition. Both use the same `filter` function with different `predicate`.

This is one of the main shining example of functional programming, of which `map` and `filter` are great examples. _Functional programming_ usually solves problems in a small steps and trivial. However once you have a collection of these small, well-tested solutions, you can combine them with your code to create your code more robust and more quickly.

### Reusability of Lambda

You can store a lambda in a `val` or `var`. This allows us to reuse of the lambda by passing it as an argument. For example,

```kotlin
val isEven = { item: Int -&gt; item % 2 == 0 }
list.filter(isEven) // returns a list of even number
list.any(isEven) // returns if the list contains even number
```

### Accessibility outside scope

Another important quality of lambda is the ability to access/refer to the elements (variables) outside the lambda scope.

&gt; When a function “closes over” or “captures” the elements in its environment, we call it a closure

Take note that `lambda` and `closure` are two distinct features and not to mix it up. `lambda` is a low ceremony function with no name and minimum amount of code. You can read more here. `closure` is the concept that the functions that can access and modify properties defined outside the scope of the function.

When a language support `closure`, it will work like this:

val a = 10
nums.filter { it &gt; a }
Even though a is not within the scope of filter lambda, the function is able to access the value of a.

To demonstrate on the closure without lambda, consider the code below.

```kotlin
var x = 1

fun upX() {
  x++
}

main() {
  upX() // x will become 2
}
```

The function `upX()` is able to modify/access to the variable `x` even thought `x` is outside the scope of `upX().`

Summary
Lambda is not just a sugar syntax for function. It is small, but very useful when you are duplicating code with minimal modification. With many lambda functions on hand, your development will be clearer, more concise and easy/fast to develop.</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Kotlin Lambda</title><link>https://htswe.github.io/blog/kotlin-lambda/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-lambda/</guid><description>The unavoidable price of reliability is simplicity – C.A.R Hoare</description><pubDate>Wed, 03 Nov 2021 00:00:00 GMT</pubDate><content:encoded>&gt; The unavoidable price of reliability is simplicity – C.A.R Hoare

### Lambda

When you hear the word “Lambda”, what comes to your mind? The word _Lambda_ is used in many place with different context. We have AWS Lambda (serverless compute service), Python Lambda (small anonymous function) and Java 8 Lambda, etc. There might be many more depending on the context.

In Kotlin, Lambda is a low-ceremony function - it has no name, requires a minimal amount of code to create and you can insert it in other code.

Probably, the one that most programmers are familiar is map function. Usually, we transform from one object to another object in the map and it works normally with List. Let’s see an example.

```kotlin
val list = listOf(1, 2, 3, 4, 5)
val square = list.map({ n: Int -&gt; n*n })
print(square) // 1 4 9 16 25
```

The lambda is the code within that `{ }`. The parameter is separated from the function body by an arrow `-&gt;`.

### Shorter Lambda for Single function argument

If the lambda is the only function argument, or the last argument, you can omit the parentheses. So we can make something like:

````kotlin
...
val square = list.map { n * n }
...

### What about more than one function argument
If the function takes more than one argument, all except the last lambda argument must be in parenthesis. For example, `joinToString` will need the last argument as a lambda.
```kotlin
val list = listOf(2,4, 5, 10)
list.joinToString(&quot; &quot;) {&quot; $it &quot;)
print(list)
````

## Summary

In general, you can use a lambda anywhere you use a regular function, but if the lambda becomes too complex, it’s offer better to define a named function (normal function), for clarity.</content:encoded><category>kotlin</category><category>functional programming</category></item><item><title>Kotlin break &amp; continue</title><link>https://htswe.github.io/blog/kotlin-break-and-continue/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-break-and-continue/</guid><description>The earliest programming language that I was familiar with is [Assembly][assembly-wiki]. I use it to program for low level code like how i programmed for lift (elevator). I used CMP and JMP a lot. CM…</description><pubDate>Fri, 29 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Jump history

The earliest programming language that I was familiar with is [Assembly][assembly-wiki]. I use it to program for low level code like how i programmed for lift (elevator). I used `CMP` and `JMP` a lot. `CMP` is like if expression and `JMP` allows you to jump around.

```
MOV AX, 00 ;Initializing AX to 0
L20:
ADD AX, 01 ;Increment AX
JMP L20 ;repeats the statements
```

Then it comes to higher-level language like C. `goto` made the transition more comfortable. But as we accumulate more experience, however, the programming community discovered that unconditional jumps produce complicated and unmaintainable code. This created a lot of criticism against the usage of `goto` and most subsequent languages have avoided any kind of unconditional jump.

Here is a snippet of how `goto` is used in C program.

```c
main() {
  int i = 1;
  printf(&quot;hello&quot;);
  here:
  printf(&quot;%d&quot;, i);
  i++;
  if (i &lt;= 10) goto here;
  printf(&quot;bye&quot;);
}
```

### Kotlin break &amp; continue

Kotlin allows us to jump, but wait. You can only jump within a looping constructs - `for`, `while` and `do-while`. It provides a _constrained jump_ in the form of `break` and `continue`.

&gt; `break` and `continue` allow us to jump within a loop.

In the loop, `continue` allows us to jump to the **beginning** of a loop, while `break` jumps to the **end** of a loop. Here is an example.

```kotlin
fun main() {
  val result = mutableListOf&lt;Int&gt;()
  for (i in 1 until 10) {
    if (i == 5) continue
    if (i == 8) break
    result.add(i)
  }
  print(result) // 1 2 3 4 6 7
}
```

As you can see when `i == 5`, the complier jumps to the beginning of the loop again hence `5` is not added to `result` list. Likewise, when `i==8`, the complier jumps to the end of the loop.

## Label

Plain `break` or `continue` can jump no further than the boundaries of their local loop. _Label_ allows the `break` and `continue` jump to the boundaries of _enclosing_ loop, so you are not limited to the scope of current loop.

You can create a label by using `label@` where `label` can be any name. Here, i will call the label `outer`.

```kotlin
fun main() {
  val result = mutableListOf&lt;String&gt;()
  outer@ for (c in &apos;a&apos;..&apos;c&apos;) {
    for (i in 1..5) {
      if (i == 3) continue@outer
      if (&quot;$c$i&quot; == &quot;c2&quot;) break@outer
      result.add(&quot;$c$i&quot;)
    }
  }
  print(result) // a1 a2 b1 b2 c1
}
```

The labeled `continue` expression `continue@outer` continues back to the label `outer@`. The labeled `break` expression `break@outer` finds the end of the block named `outer@` and proceeds from there.

### Summary

&lt;div style=&quot;width:100%;height:0;padding-bottom:90%;position:relative;&quot;&gt;&lt;iframe src=&quot;https://giphy.com/embed/uTCAwWNtz7U2c&quot; width=&quot;100%&quot; height=&quot;100%&quot; style=&quot;position:absolute&quot; frameBorder=&quot;0&quot; class=&quot;giphy-embed&quot; allowFullScreen&gt;&lt;/iframe&gt;&lt;/div&gt;

`break` and `continue` tend to create complicated and unmaintainable code. Although these jumps are somewhat more civilized than `goto`, it might still interrupt program flow. Code without jumps is always easier to understand. Always think about other simpler and more readable solution. Both `break` and `continue` can be replaced with return if you extract the whole loop or the loop body into new function. In functional programming, you can also write code without using `break` and `continue`.

[assembly-wiki]: https://en.wikipedia.org/wiki/Assembly_language</content:encoded><category>kotlin</category></item><item><title>Elvis operator in Kotlin</title><link>https://htswe.github.io/blog/elvis-operator-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/elvis-operator-kotlin/</guid><description>This operator is a question mark followed by a colon (?:) with no space in between. It is named for an emoticon (short form of “emotion icon”) of the musician Elvis Presley, and is also a play on the…</description><pubDate>Thu, 28 Oct 2021 00:00:00 GMT</pubDate><content:encoded>This operator is a question mark followed by a colon (`?:`) with no space in between. It is named for an emoticon (short form of “emotion icon”) of the musician Elvis Presley, and is also a play on the words “else-if” (which sounds vaguely like “Elvis”)

![image-center](https://upload.wikimedia.org/wikipedia/commons/2/2d/PresleyPromo1954PhotoOnly.jpg)

A number of programming languages (eg. C#, TypeScript, etc) provide a _null coalescing operator_ that performs the same action as Kotlin’s Elvis operator.

In Elvis operator, if the expression on the left of `?:` is not `null`, that expression becomes the result. If the left-hand expression is `null`, then the expression on the right of the `?:` becomes the result.

```kotlin
val len1: Int = if (b != null) b.length else -1

val len2: Int = b?.length ?: -1
```

The `len1` is using `if-else` expression while `len2` is using Elvis operator. They both will result in the same.</content:encoded><category>kotlin</category></item><item><title>Kotlin Extension Properties</title><link>https://htswe.github.io/blog/kotlin-extension-properties/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-extension-properties/</guid><description>In Kotlin, just like [extension function][extension-is-a-magic], properties can have extension properties too. The syntax is similar to extension functions - the extended type comes right before the…</description><pubDate>Thu, 28 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Extension Properties

In Kotlin, just like [extension function][extension-is-a-magic], properties can have _extension_ properties too. The syntax is similar to extension functions - the extended type comes right before the function or the property name -

```kotlin
val String.indices: IntRange
  get() = 0 until length

print(&quot;hello&quot;.indices) // 0..4
```

One question that people usually confuse is whether to choose **function** or **property**. The simplest suggestion is

- **property** describes state
- **function** describe behavior
  Preferring a property over a function makes sense only if it is simple enough and improves readability.

We could also create extension properties on generic

&gt; [Kotlin Style Guide][kotlin-style-guide] recommends a function over a property if the function throws an exception.

If you are planning to make extension on [generic][kotlin-generic] property, it is possible. For example,

```kotlin
val &lt;T&gt; List&lt;T&gt;.firstOrNull: T?
  get() = if (isEmpty()) null else this[0]
```

If you do not wish to use generic, another way is to replace `T` with `*`. It is called **_star projection_**.

```kotlin
val List&lt;*&gt;.indices: IntRange
  get() = 0 until size
```

### Summary

While both extension function and extension properties can do mostly the same, we should try keeping close the Style Guide by Kotlin. The basic rule of thumb is to **_find out if it describes a behavior or state_**.

There is also additional set of guidelines that help us to decide if property is preferred over function:

- does not throw exception
- is cheap to calculate or cached on the first run
- returns same result on multiple invokes

[kotlin-style-guide]: https://kotlinlang.org/docs/coding-conventions.html

[kotlin-generic]: /tech/kotlin-generic/
[extension-is-a-magic]: /tech/extension-function-is-a-magic/</content:encoded><category>kotlin</category></item><item><title>Kotlin generic</title><link>https://htswe.github.io/blog/kotlin-generic/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-generic/</guid><description>The first time i was introduced to the term Generics was back in C++ STL (Standard Template Library) days. It was an idea to allow type (Int, String, Class, etc) to be a parameter to the class, funct…</description><pubDate>Thu, 28 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Generics Intro

The first time i was introduced to the term Generics was back in C++ STL (Standard Template Library) days. It was an idea to allow type (`Int`, `String`, `Class`, etc) to be a parameter to the class, function or interface. It is to allow programmer to write a general algorithm that will work with any data type by loosing type constraints.

A good example in Kotlin is the collection classes, such as `List`, `Set` and `Map`. These collections are able to hold any other objects regardless of their types.

### Kotlin universal type

Before we go into how the generic code looks like, one thing that we should aware is the universal type in Kotlin. The universal type is a type that is the parent of all other types. In Kotlin, it is called `Any`. As the name implies, `Any` allows any type of argument. If you have a function that returns a variety of types and they have nothing in common, `Any` could solve the problem.

### Generics Class

To define a generic type, we usually add angle bracket (`&lt;&gt;`) containing one or more generic placeholders and put this generic specification after the class name.

```kotlin
class GenericHolder&lt;T&gt; (
  private val value : T
) {
  fun getValue(): T = value
}

val usage1 = GenericHolder(1)
print(usage1.getValue()) // 1

val usage2 = GenericHolder(&quot;Hello&quot;)
print(usage2.getValue()) //&quot;Hello&quot;
```

You may now wonder why we are using the generic type `&lt;T&gt;`. Can’t we use the type `Any` instead? Well. Let’s see this example below.

```kotlin
class AnyHolder (
  private val value : Any
) {
  fun getValue(): Any = value
}

class Car {
  fun drive() = &quot;Vrooom&quot;
}

val usage = AnyHolder(Car())
val maybeCar = usage.getValue()

print(maybeCar.drive()) // won&apos;t compile
```

As you can see, `Any` does work for simple cases, but as soon as we want to use the underlying function of Car - it doesn’t work because the complier has lost track about a fact that it was a Car when it assigned to `Any`. Therefore, maybeCar is actually `Any` data type and not a Car anymore.

If we use the generic on the other hand, it retains the information that, in this example, we still know that it is a `Car`, which means we can perform the functions on the `Car` class.

### Generic Function

So far, we looked at Generic class. In function, there is not much different from the class. We specify a generic type parameter in an angle brackets before the function name:

`fun &lt;T&gt; something&lt;arg: T&gt;: T = arg`

On top of function, the generic can also be used in generic extension functions for collections. For example,

```kotlin
fun &lt;T&gt; List&lt;T&gt;.first(): T {
  if (isEmpty()) throw NoSuchElementException(&quot;Empty List&quot;)
  return this[0]
}
```

As you can see `first()` extension function for `List`, it can work with any kind of `List`. To return `T`, they must be generic function.

### Summary

One of the most compelling initial motivations for generics is to create collection classes, which you have seen in the `List` example. The `Any` works for simple cases, but lost some information during casting. Therefore, generic type are a better choice for programmer when writing classes or functions with maximum expressiveness by loosing type constraints.</content:encoded><category>kotlin</category></item><item><title>Management in Agile</title><link>https://htswe.github.io/blog/management-in-agile/</link><guid isPermaLink="true">https://htswe.github.io/blog/management-in-agile/</guid><description>There are many benefits that many organizations witness when they move into agile way of working - and here are some:</description><pubDate>Thu, 28 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Why Agile

There are many benefits that many organizations witness when they move into agile way of working - and here are some:

1. Less waiting time
2. Frequent delivery (Note: You need to invest in automated tests)
3. More feedback

### Management in Agile

&gt; No manager dislikes when the team wants to take responsibility.

There are some broad misleading for the role of the Manager. The best misconception about hiring a Manager is well described in this children book from [Hawtch-Hawtcher Bee Watcher][bee-watcher] in **_Dr Seuss characters_**.

![image-center](https://images.squarespace-cdn.com/content/v1/52f51a96e4b0ec7646cd474a/1454616851462-7DGCFAZ7U4LV4PXCEQPB/beewatcher1.jpg)

Taylorism said

&gt; No question that cost of production is lowered by separating the work of planning and the brain work as much as possible from the manual labour

This might be true back in industry age, but no longer applicable in today knowledge industry.

The role of Manager in today industry is becoming like a Teacher. He teaches the team, but allows the team to decides how to work. The manager builds capability to build a better and efficient team.

For example, the manager often does

1. avoiding Taylorism
2. giving space &amp; opportunity to people to make own decision
3. observing how things are going without giving directions
4. making way too the team to do their best
5. remove impediment from a team (eg. when the team asks if they can buy a book, instead of thinking the cost or worries about how people will spend money on buying what kind of books, remove the need for permission and see what happened.)

### What motivates people?

When we know carrot-stick approach doesn’t work anymore, what motivates people?

&lt;iframe width=&quot;640&quot; height=&quot;360&quot; src=&quot;https://www.youtube-nocookie.com/embed/1SfmmuC9IWs?controls=0&amp;showinfo=0&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;

https://youtu.be/1SfmmuC9IWs

1. Autonomy - people want to make decision
2. Mastery - people want to get better at stuffs
3. Purpose - people need a purpose

### Theory X - Theory Y

**Theory X**: Average human dislike work.
**Theory Y**: Average people are excited to work.
In agile self-managing team, we encourage more towards Theory Y.

### Summary

The role of the manager changes significantly for most organisations that are adopting Scrum. Traditionally managers are often involved in deciding what the actual work is and involved in deciding how to do it.

The decision of what the team is working on is not anymore within the control of the manager but instead is decided by the Product Owner. The manager has no role to play in this and should resist doing so.

The role of middle management is to [see the whole][systems-thinking] and build the capability of the organization to build great products.

[bee-watcher]: https://seuss.fandom.com/wiki/Hawtch-Hawtcher_Bee_Watcher
[systems-thinking]: https://less.works/less/principles/systems-thinking</content:encoded><category>scrum</category><category>less</category></item><item><title>Product Owner</title><link>https://htswe.github.io/blog/product-owner/</link><guid isPermaLink="true">https://htswe.github.io/blog/product-owner/</guid><description>Product Owner is responsible for the profitability of the product (ROI). In LeSS, there is only one product owner and one product backlog. Typically, PO is in the Product Management Unit. She acts as…</description><pubDate>Thu, 28 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Product Owner Role

**Product Owner** is responsible for the profitability of the product (ROI). In LeSS, there is only one product owner and one product backlog. Typically, PO is in the Product Management Unit. She acts as a connector, bringing teams and customers/users together so the teams become more [customer focused][customer-focused-page].

![image-center](https://less.works/img/framework/who-is-the-product-owner-in-different-types-of-development.png)

A LeSS Product Owner focuses on thinking hard about prioritization but collaborates with the teams on clarification. Further, she encourages and helps the teams enter into a direct conversation with true users and customers for clarification. She acts as a connector, not an intermediary.

### Reducing Wastes

There are a couple of wastes in product development.

1. Overproduction of features
2. Waiting delay
3. Handoff
4. Extra process
5. Partially done work
6. Task switching
7. Defects
8. Under-realising people’s potential
9. Knowledge scatter
10. Wishful thinking

### Single Product Backlog

The product backlog is organized in

- already done
- fine grained
- coarse grained
  A good Product Backlog must:
- have estimates for all items,
- have finer grained items at the top and coarser grained items further down, and
- be prioritized.
  In LeSS Huge, there is additional column - **Area**. You can filter the backlog by **Area**.

### Summary

The product backlog is very important with clear ownership and priority in LeSS agile. It also helps with the competing priorities within the organization.

[customer-focused-page]: https://less.works/less/principles/customer-centric</content:encoded><category>scrum</category><category>less</category></item><item><title>Backlog Refinement Mentality</title><link>https://htswe.github.io/blog/refinement-mentality/</link><guid isPermaLink="true">https://htswe.github.io/blog/refinement-mentality/</guid><description>It is the ongoing effort by the whole team needed within each sprint to refine items in the backlog to be ready to ready for future sprints. There are a number of key activities:</description><pubDate>Thu, 28 Oct 2021 00:00:00 GMT</pubDate><content:encoded>It is the ongoing effort by the whole team needed within each sprint to refine items in the backlog to be ready to ready for future sprints. There are a number of key activities:

- splitting bit items
- clarifying items
- estimating size

### Overall Product Backlog Refinement

In this refinement mode, team or representative(s) with product owner will be involved. The normal motivation for an overall PBR event is when the group may want to divide related items into (for example) two major areas and have (for example) four teams work on one area, and another four teams work on another area.

The key point for Overall refinement is **Short**. Do quick and lightweight item clarification for basic understanding.

### Multi-team Product Backlog Refinement

Multi-team PBR is the most important event in LeSS to drive effective Sprints with well-aligned, coordinated, and adaptive teams. Multi-team PBR is when multiple teams are (literally) in the same room at the same time doing PBR. Attendees include all members of all participating teams, and may also include subject-matter experts, users, customers, and the Product Owner. Big workshops are better with a skilled facilitator, and this is a great adjunct role for a Scrum Master.

### Single team Product Backlog Refinement

In LeSS, Single team PBR is not encouraged and should be rare. Since LeSS wants to encourage the group learning, weakens coordination and alignment, and reduces adaptiveness.

### Splitting

Traditionally, people tend to split of big features into all-at-once in equal piece at the beginning. In LeSS, we split the big feature and take a bite to start.

Another technique is using Impact Mapping to find out the impact of each choices. Story Mapping is also used in initial backlog refinement. There are many games available in the market for the team to try it out too.

### Important Mentality

During the refinement session, many think a lot, especially engineers in my experience. People tend to spend a lot of time talking about technology instead of the problem that needs to be solved. The best solution for the problem is “**_do minimum work that fulfils the requirements_**”</content:encoded><category>scrum</category><category>less</category></item><item><title>Sprint Ceremonies in LeSS</title><link>https://htswe.github.io/blog/sprint-ceremonies-in-leSS/</link><guid isPermaLink="true">https://htswe.github.io/blog/sprint-ceremonies-in-leSS/</guid><description>In the beginning of the sprint, the first sprint planning 1 take place. It is a short meeting with team representatives and product owner to decide what the teams are going to work on the sprint. It…</description><pubDate>Thu, 28 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Sprint Planning 1

In the beginning of the sprint, the first sprint planning 1 take place. It is a short meeting with team representatives and product owner to decide what the teams are going to work on the sprint. It is also a time to find out if there will be multiple teams who need to collaborate during the sprint.

### Sprint Planning 2

This session is usually longer and a lot of technical and more detailed discussions take place.

It is common for two teams to work on similar related features or work on different features that affect the same components. In that case, it can be useful to have a Multi-team Sprint Planning Two meeting. This is done by having the teams meet in the same physical location with each team conducting its own Sprint Planning Two. That way the teams can:

- have a shared design session,
- ask questions of one another at any time,
- coordinate shared work,
- find other opportunities to work together and learn from each other (e.g. cross-team pair programming).

**Notes**

- Items are features.
- Each task (subtask) has the maximum of 1 day.
- Tasks are created during the sprint planning.

### LeSS Sprint Review

At the end of sprint, all the teams present what has been done during the sprint. The main objective of the review is not to show what each team has done. It is to get feedback and focus more on discussion.

### Sprint Retrospective

Right after Sprint review, there will be individual group sprint retrospective. The team will reflect what has been done well, what went wrong and what to improve. Add actions and set a few items.

### Daily Scrum

The Daily Scrum in LeSS is done per team and is no different than in single-team Scrum.

The Team will spend 15 minutes together, during which each team member answers three questions:

- What did I do yesterday?
- What will I work on today?
- What is in my way?

In case, there might be scout from another team to find out if anything impact might happen if multiple teams are working on the same feature.</content:encoded><category>scrum</category><category>less</category></item><item><title>Definition of Done in LeSS</title><link>https://htswe.github.io/blog/definition-of-done-in-leSS/</link><guid isPermaLink="true">https://htswe.github.io/blog/definition-of-done-in-leSS/</guid><description>Are we done? Kind of. Definition of Done (DoD) is an agreed set of items that must be finished before we can consider the user story is done.</description><pubDate>Wed, 27 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Definition of Done

Are we done? Kind of. **Definition of Done (DoD)** is an agreed set of items that must be finished before we can consider the user story is done.

What if we are some undone work? For example, there are some items that need to be vested/tested by security team. We allocate some extra sprints before the release time to do undone work.

But it could be problematic if we uncovered something serious during the last sprint before the delivery.

&gt; One way to expand the DoD more.

In LeSS agile, we only have a set of DoD. Each feature team will have the ability to expand DoD to suit the needs.</content:encoded><category>scrum</category><category>less</category></item><item><title>Destructuring</title><link>https://htswe.github.io/blog/destructuring/</link><guid isPermaLink="true">https://htswe.github.io/blog/destructuring/</guid><description>Many times, you may encounter use cases where you need to return more than one item from a function. One way that people usually do is to create a custom object or class that contains those items.</description><pubDate>Wed, 27 Oct 2021 00:00:00 GMT</pubDate><content:encoded>Many times, you may encounter use cases where you need to return more than one item from a function. One way that people usually do is to create a custom `object` or `class` that contains those items.

### Pair and Triple

Another choice is to use `Pair` class. For example,

```kotlin
fun square(input: Int): Pair&lt;Int, String&gt; =
  if (input &lt; 0)
    Pair(input * input, &quot;negative input&quot;)
  else
    Pair(input * input, &quot;non-negative input&quot;)

val test = square(-5)
print(test.first) // 25
print(test.second) // negative input
```

Returning multiple values is great, but we’d like to a convenient way to unpack the results. As you can see, we can use `test.first` and `test.second` to access the component of a `Pair`. But we can also declare and initialize using a _destructuring declaration_.

```kotlin
val test = square(-5)

val (squareValue, inputType) = square(-5)
print(squareValue) // 25
print(inputType) // negative input
```

Similar to `Pair`, if you have 3 values, you can use `Triple`. But anything more than 3 values, you won’t find any other component.

### Data Class

&gt; It is intentional that the maximum is `Triple`. You should consider using special classes such as `data class` if you have more than 3 values.

The `data class` also supports destructuring.

```kotlin
data class Result(
  val value: Int,
  val type: String
)

fun square(input: Int): Result =
  if (input &lt; 0)
    Result(input * input, &quot;negative input&quot;)
  else
    Result(input * input, &quot;non-negative input&quot;)

val (value, type) = square(-5)
```

One important thing to take note for `data class` during destructuring is that we must assign values to the new identifiers in ==same order== that we define the properties in the class.

In case you do not need some of them, you can use underscore to skip it. For example,
`val (_, type) = square(-5)`
when we want to skip the first properties `value`.

### Bonus

There are some special extension function in Kotlin built-in library such as `List`. You can use `withIndex()` extension that returns a collection of `IndexedValues` which can be destructured.

```kotlin
val list = listOf(&apos;x&apos;,&apos;y&apos;,&apos;z&apos;)
for((index, value) in list.withIndex()) {
  print(&quot;$index:$value&quot;)
}
```

### Summary

The destructuring declarations is a useful feature to extract properties from objects and bind them to variables.

What impresses me is that I can extract multiple properties in one statement and it looks so neat and tidy.</content:encoded><category>kotlin</category></item><item><title>LeSS Agile?</title><link>https://htswe.github.io/blog/leSS-agile/</link><guid isPermaLink="true">https://htswe.github.io/blog/leSS-agile/</guid><description>1. To solve a customer’s problem, not writing code 2. Need constant feedback (eg. testing, customer’s feedback) Waterfall methodology never work.</description><pubDate>Wed, 27 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Purpose of Software Development

1. To solve a customer’s problem, not writing code
2. Need constant feedback (eg. testing, customer’s feedback)
   Waterfall methodology never work.

### Small organization becomes larger

Many companies starts from an idea, a bunch of people working together. They tried it in the market, many failed. Some manages to survive and get successful. The successful small company starts hiring people, later found out nothing delivered after some times. What happened next? The company hires managers - project managers. If delivered but have a lot of issues in customers, then the company will hire more QA. But customers said it is not the product they want. The company will start hire business analyst or someone who understand more about markets.

The root cause is to find out why the engineers cannot stick to the timeline instead of making organization larger.

&gt; Optimizing locally is much better than optimizing overall.

This is the difference between a FinTech startup and a bank - organization complexity.

Will switching to “Agile” solve this problem?

&gt; No. If you want different results, you will need a different system. The main point is to make things more simpler, not more complex system.

Traditional large groups are complicated - though not because they need to be, but they make illusion that it is necessary.

### Optimizing goal of an organization

1. To deliver the highest business value
2. Ability to adapt - what important today might not be important tomorrow. It doesn’t mean it is delivered. It means sooner than later.
3. learning organization - really optimized for learning. The team output is equal to the knowledge. The more the team learns, the more the team can deliver the goals.

### LeSS overview

Fixing Taylorism.

&gt; There is no question that the cost of production is lowered by separating the work of planning and the brain work as much as possible from manual labour

### LeSS / LeSS Huge

2-8 teams : LeSS framework
x&gt; 8 teams : LeSS Huge

![image-center](https://less.works/img/framework/why-less-framework.png)

1. Single product owner/ single product backlog
2. Each team has own backlog and one scrum master in the team.
3. Sprint planning 1 (half an hour) - which team is going to work on what feature
4. Sprint planning 2 (couple of hours) - sprint backlog is created
5. Mid of sprint will have product backlog refinement (for upcoming sprint)
6. Each day will have daily scrum
7. Sprint review for all team at once
8. Each team will have own retrospective
9. Finally, one overall retrospective

### Role

- Product Owner (1 person)
- Team
- Scrum Master
- Manager (improve capability of development system, decide structure and policies)

### LeSS Huge vs LeSS

There are a number of Area Product Owners to support the product owner.

![image-center](https://less.works/img/less-huge/less-huge-framework.png)

**Q: Should one engineer involve in multiple projects?**
A: No. You shouldn’t.

**Q: Who should involve in Overall Retrospective?**
A: Only managers will attend. Although there is downfalls that the whole team is not involved.

**Q: Who will involve in the product backlog refinement?**
A: Only people are needed.

**Q: How long is it for each sprint?**
A: Typically, 2 weeks including all the sprint ceremonies - it is important to time-box it.</content:encoded><category>scrum</category><category>less</category></item><item><title>Team</title><link>https://htswe.github.io/blog/team/</link><guid isPermaLink="true">https://htswe.github.io/blog/team/</guid><description>The team is formed at the own will. The aim is to form a self-organising team. Team will take over some of the responsibility from the manager. And responsibility comes with authority too. While duri…</description><pubDate>Wed, 27 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Forming a team

The team is formed at the own will. The aim is to form a self-organising team. Team will take over some of the responsibility from the manager. And responsibility comes with authority too. While during forming, some important things to take note:

1. Team needs to be balanced. Senior/Junior
2. Team needs to deliver end to end.
   Team is usually formed in 3 hours.

**Q: What if the team is remote?**
The best arrangement is to form a team locally. It is very painful if the team is spread across the globe. But will it work? it will - but just too painful. With globally spread team, there will be

- less coordination
- timezone difference
- lack of face to face communication

### System thinking

Let’s try this: We try to deliver as much as possible with two variables.

1. no of features/items/stories in backlog
2. no of issues/defects

**Q: what happen when we tell people to deliver as much as possible?**

A: No of issues will increase. People will cut corner. As issues rise, the people will need to fix on issues and less time to work on features. Will reduction of features eliminate issues entirely? No. The only way to eliminate the issues is when there is no features.

**Q: what could/might affect more issues?**

A: There are a couple of underlying reasons including:

1. level of requirements understanding by team
2. level of details (acceptance criteria) of requirement -&gt; frequency of requirements change -&gt; pressure to deliver on time
3. time between requirement written and delivered
4. legacy without poor documentation (knowledge gap)
5. quality (Low percentage of coverage unit test) -&gt; purpose of code unknown/ correctness of code -&gt; ease of change

The main point of system thinking is to slow down and think systematically. Avoid putting a lot of noise around the point as it doesn’t help what to focus.

System thinking will help us to find relationship between issues and in the organisational level. The variable needs to be very specific and simple. System modelling is to help understand each other, not about arguing who is right or wrong - [False Dichotomy][false-dichotomy].

&gt; A false dichotomy is typically used in an argument to force your opponent into an extreme position – by making the assumption that there are only two positions.

**Q: How do we encourage people to ask question?**

A: We start with a variable, continue with the question and discussion.

[false-dichotomy]: https://wiki.c2.com/?FalseDichotomy</content:encoded><category>scrum</category></item><item><title>Data class</title><link>https://htswe.github.io/blog/data-class/</link><guid isPermaLink="true">https://htswe.github.io/blog/data-class/</guid><description>One of main motivation of Kotlin is to reduce repetitive coding. One that many of us have spent a significant amount of time and effort is the class mechanism. However, creating classes that primaril…</description><pubDate>Mon, 25 Oct 2021 00:00:00 GMT</pubDate><content:encoded>One of main motivation of Kotlin is to reduce repetitive coding. One that many of us have spent a significant amount of time and effort is the `class` mechanism. However, creating classes that primarily hold data still requires a considerable amount of repetitive code. This is where `data class` simplify Kotlin code and perform common tasks.

### Two features of data class

You can define a data class using `data` keyword. Each constructor parameter must be preceded by `var` or `val`.

```kotlin
data class Sample(
  val arg1: Int,
  val arg2: Int
)

val s1 = Sample(10, 20)
val s2 = Sample(10, 20)
print(s1)	// &quot;Sample(arg1=10, arg2=20)&quot;
print(s1 == s2)	// true
```

Based on the sample above, you can see **two** features:

1. On `print` statement, you can notice that the `String` produced by `s1`. The data class display objects in a nice, readable format without requiring any additional code.
2. In normal class, in order to achieve the comparison between `s1` and `s2`, we have to implement `equals()` function. In `data` classes, this function is automatically generated. It compares the values of all properties specified as constructor parameters.

### copy

Another useful function generated for every `data` class is `copy()`, which creates a new object containing the data from the current object. However, it also allows you to change selected values in the process.

```kotlin
data class Contact(
  val name: String,
  val number: String,
  val address: String
)

val contact = Contact(&quot;Mike&quot;, &quot;12345&quot;, &quot;US&quot;)
val newContact = contact.copy(address = &quot;UK&quot;)
```

All arguments have default values that are equal to the current values, so you provide only the ones you want to replace.

### hashCode

`hashCode()` is used in conjunction with `equal()` to rapidly look up a `Key` in a `HashMap` or `HashSet`. Creating a correct `hashCode()` by hand is tricky and error-prone, so let the data class to do it for you.

### Conclusion

In conclusion, `data class` simplifies and reduces a lot of boilerplate code and functions such as `copy()`, `equals()` and `hashCode()`. You should use `data class` over normal class if the purpose is to purely hold the data.</content:encoded><category>kotlin</category></item><item><title>Kotlin overloading</title><link>https://htswe.github.io/blog/kotlin-overloading/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-overloading/</guid><description>If you are coming from C++, this may be familiar to you. The term Overload refers to the name of a function with the same name, but different numbers of parameters.</description><pubDate>Mon, 25 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Overload

If you are coming from C++, this may be familiar to you. The term _Overload_ refers to the name of a function with the **same** name, but **different** numbers of parameters.

```kotlin
fun f() = 0
fun f(n: Int) = n
fun f(n: Int, m: Int) = n * m
```

### Why is overloading useful?

Why is overloading useful? It allows you to express “variations on a theme” more clearly than if you were forced to use different function names. Compare these two options:

#### Option 1

```kotlin
fun addInt(a: Int, b: Int) = a + b
fun addDouble(a: Double, b: Double) = a + b
```

#### Option 2

```kotlin
fun add(a: Int, b: Int) = a + b
fun add(a: Double, b: Double) = a + b
```

Without overloading, you can’t just name the operation `add()`. With these two options, the overloaded `add()` is much cleaner.

### Conclusion

The lack of overloading in a programming language is not a terrible hardship, but this feature provides valuable simplification, producing more readable code.</content:encoded><category>kotlin</category></item><item><title>When expression</title><link>https://htswe.github.io/blog/when-expression/</link><guid isPermaLink="true">https://htswe.github.io/blog/when-expression/</guid><description>A large part of computer programming is performing an action when a pattern matches.</description><pubDate>Mon, 25 Oct 2021 00:00:00 GMT</pubDate><content:encoded>&gt; A large part of computer programming is performing an action when a pattern matches.

Usually, this condition can be represented by `if` expression, however, when you have more than two or three choices to make, `when` expression are much nicer than `if` expression.

```kotlin
if (a == 0) print(&quot;a is zero&quot;)
else if (a == 1) print (&quot;a is one&quot;)
else print (&quot;a is neither zero nor one&quot;)

when (a) {
  0 -&gt; print(&quot;a is zero&quot;)
  1 -&gt; print(&quot;a is one&quot;)
  else -&gt; print(&quot;a is neither zero nor one&quot;)
}
```

`when` expression makes the above code cleaner and more readable.

### When + Set

Many time, we will put a variable in the `when` expression. Do you also know that we can also match a `Set` of values against another `Set` of values as below

```kotlin
fun mixColors(first: String, second: String) =
  when(setOf(first, second)) {
    setOf(&quot;red&quot;,&quot;blue&quot;) -&gt; &quot;purple&quot;
    setOf(&quot;red&quot;,&quot;yellow&quot;) -&gt; &quot;orange&quot;
    setOf(&quot;blue&quot;, &quot;yellow&quot;) -&gt; &quot;green&quot;
    else -&gt; &quot;unknown&quot;
  }

print(mixColors(&quot;red&quot;, &quot;blue&quot;)) // purple
```

### When expression without argument

`when` has a special form that takes no argument. Omitting the argument means the branches can check different `Boolean` conditions.

```kotlin
val age = 17
val category = when {
  age &lt; 17 -&gt; &quot;underage&quot;
  age &lt; 25 -&gt; &quot;young adult&quot;
  else -&gt; &quot;adult&quot;
}
```

### Conclusion

The expression `when` is overall a more elegant way to choose between several options.</content:encoded><category>kotlin</category></item><item><title>Extension function is a magic</title><link>https://htswe.github.io/blog/extension-function-is-a-magic/</link><guid isPermaLink="true">https://htswe.github.io/blog/extension-function-is-a-magic/</guid><description>This is one of my most favorite features of Kotlin - Extension Function. Imagine this. You are using a 3rd party library - String that have all the things that I would need for text manipulation- alm…</description><pubDate>Sat, 23 Oct 2021 00:00:00 GMT</pubDate><content:encoded>This is one of my most favorite features of Kotlin - **Extension Function**. Imagine this. You are using a 3rd party library - String that have all the things that I would need for text manipulation- _almost_. If I have another one or two functions under `String` topic, Extension Function would solve this problem beautifully.

Kotlin’s _extension functions_ effectively add member functions to existing class.

```kotlin
fun String.addGreetingEmoji() = &quot;Hi $this 👋&quot;
&quot;Dave&quot;.addGreetingEmoji() // Hi Dave 👋
```

You can also apply extension function to your own class.

```kotlin
class Team(public val name: String)

fun Team.intro(noOfPeople: Int) = &quot;$name team has $noOfPeople.&quot;

fun main() {
  val team = Team(&quot;Man Utd&quot;)
  println(team.intro(11)) //Man Utd team has 11.
}
```

Note that the extension function `Team.intro` can access to name in `Team` class. If the `name` is `private`, the extension function couldn’t access from the extension function.

For extension function, you can rewrite Team.intro(Int) into `intro(Team, Int)`. The only reason for using extension function is the syntax. This is called _syntax sugar_, which is cleaner and more powerful.</content:encoded><category>kotlin</category></item><item><title>Named and Default Arguments</title><link>https://htswe.github.io/blog/named-and-default-arguments/</link><guid isPermaLink="true">https://htswe.github.io/blog/named-and-default-arguments/</guid><description>One thing that annoyed me mostly while I was working in Java is the arguments in the function. If you have a function that requires more than 3 arguments, it becomes cumbersome - we have to ensure th…</description><pubDate>Sat, 23 Oct 2021 00:00:00 GMT</pubDate><content:encoded>### Some background

One thing that annoyed me mostly while I was working in Java is the `arguments` in the `function`. If you have a function that requires more than 3 arguments, it becomes cumbersome - we have to ensure that we pass the right value and the data type. It also demands that we have to follow the exact order of arguments in the function.

In Java, you can see how confusing it can be when you are calling `testSometing()` function.

```java
void testSomething(int a, int b, int c, int d, int e) {
  //something
}

main() {
  testSomething(1,1,3,2,5) //ambigious
  ...
}
```

### Kotlin Named Argument

&gt; Named arguments improve code readability.

The same `testSomething` can be written in Kotlin more elegantly.

```kotlin
fun testSomething(a: Int, b: Int, c: Int, d: Int, e: Int) {
  //something
}

main() {
  testSomething(a=1, c= 3, b=1, e=5, d=2)
  ...
}
```

Furthermore, you can also rearrange the argument order as they are now all named. Note that you can mix named and positional arguments. If you change the argument order, you should use the named argument throughout the call.

### Kotlin Default Argument

Combination of named argument with default makes things more interesting and beautiful.

```kotlin
fun testSomething(a: Int = 0, b: Int = 0, c: Int = 0) {
  //something
}

main() {
  testSomething(c=10) // a and b are default to 0
}
```

### Custom Class as Default Argument

One **important** thing to take note if you are using `object` as a default argument, a new instance of that object is created for each invocation.

```kotlin
class Custom

fun test(c: Custom = Custom()) = print(c)

main() {
  test() // DefaultArgs@238x402
  test() // DefaultArgs@9103xa1
}
```</content:encoded><category>kotlin</category></item><item><title>Property Accessor</title><link>https://htswe.github.io/blog/property-accessor/</link><guid isPermaLink="true">https://htswe.github.io/blog/property-accessor/</guid><description>If you are new to Kotlin, there is something in property accessor that you might find it interesting. There are two methods - get() for getter and set() for setter for each property.</description><pubDate>Fri, 22 Oct 2021 00:00:00 GMT</pubDate><content:encoded>If you are new to Kotlin, there is something in property accessor that you might find it interesting. There are two methods - `get()` for getter and `set()` for setter for each property.

```kotlin
var a: Int = 0
  get() {
    return field
  }
  set(value) {
    field = value
  }
```

The default behaviour for a property returns its stored value from a getter and modifies it with a setter. Inside those, the stored value is manipulated indirectly using the `field` keyword and they are only valid within these two functions.

If we set a property as `private`, both `get()` and `set()` will also become `private`. For best practice, we usually make setter function as `private` whereas getter function will be exposed as `public`. In that way, the property is allowed to read outside the class, however, the value can only be modified within the same class.

```kotlin
class Balance {
  var value: Int = 0
    private set

  fun inc() = value++
  fun dec() = value--
}

class Client() {
  val balance = Balance()
  balance.inc() // this will increase the balance
  print(balance.value)
}
```</content:encoded><category>kotlin</category></item><item><title>Map in Kotlin</title><link>https://htswe.github.io/blog/map-in-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/map-in-kotlin/</guid><description>So we have seen the wonderful [Set][set-in-kotlin]. Next, we are going to look at Map.</description><pubDate>Mon, 18 Oct 2021 00:00:00 GMT</pubDate><content:encoded>So we have seen the wonderful [Set][set-in-kotlin]. Next, we are going to look at `Map`.

&gt; A Map connects keys to values and looks up a value when given a key.

In Kotlin, we can create `Map` by using `mapof()`. A plain `Map` is read-only.

```kotlin
val fruits = mapOf(
  &quot;A&quot; to &quot;Apple&quot;,
  &quot;B&quot; to &quot;Banana&quot;,
  &quot;C&quot; to &quot;Cherry&quot;
)

val aFruit = fruits[&quot;A&quot;] //Apple
```

If you want a mutable version of `Map`, then you can look at `mutableMapOf()`.

```kotlin
val numbers = mutableMapOf(
  1 to &quot;one&quot;,
  2 to &quot;two&quot;
)

numbers += 3 to &quot;three&quot;
```

### Interesting Note

- Both `mapOf()` and `mutableMapOf()` preserve the order in which the elements are put into the `Map`.
  `Map` returns `null` if it doesn’t contain an entry for a given key. If you need a result that can’t be `null`, use `getValue()` and catch `NoSuchElementException`.
  Another alternative is to use default value - `getOrDefault()` just does that.

### Conclusion

`Map` looks like a simple tiny database. They are also sometimes called associative arrays, because it associate key with value. Even thought `Map` are quite limited compared to database, they are nonetheless one of the great choices in programming data structure.

[set-in-kotlin]: /tech/set-in-kotlin/</content:encoded><category>kotlin</category></item><item><title>Infix notation in function</title><link>https://htswe.github.io/blog/infix-notation-in-function/</link><guid isPermaLink="true">https://htswe.github.io/blog/infix-notation-in-function/</guid><description>Another Kotlin treasure that I have not known is the ability to write infix notation in function. We use infix notation in most arithmetic operation such as a + b. The infix notation is where the ope…</description><pubDate>Thu, 14 Oct 2021 00:00:00 GMT</pubDate><content:encoded>Another Kotlin treasure that I have not known is the ability to write infix notation in function. We use infix notation in most arithmetic operation such as `a + b`. The infix notation is where the operator (`+`) is used between the operands (`a`) and (`b`). In infix notation, only functions defined using the `infix` keyword can be called this way.

There are 3 things to make this `infix` notation.

1. They must be member functions or extension functions.
2. They must have a single parameter.
3. The parameter must not accept variable number of arguments and must have no default value.

```kotlin
class MyStringCollection {
    infix fun add(s: String) { /*...*/ }

    fun build() {
        this add &quot;abc&quot;   // Correct
        add(&quot;abc&quot;)       // Correct
        //add &quot;abc&quot;        // Incorrect: the receiver must be specified
    }
}
```</content:encoded><category>kotlin</category></item><item><title>Set</title><link>https://htswe.github.io/blog/set-in-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/set-in-kotlin/</guid><description>In computer science, Set is an interesting abstract data type that stores unique values. It is a collection that allows only one element of each value.</description><pubDate>Thu, 14 Oct 2021 00:00:00 GMT</pubDate><content:encoded>In computer science, `Set` is an interesting abstract data type that stores unique values. It is a collection that allows only one element of each value.

If you have a list of values and you want to make it a unique collection of values, you just have to convert it to a `Set`. Isn’t it wonderful?

We can also perform some Venn-diagram operations like checking for subset, union, intersect and difference, using either

dot notation – eg. `set.union`(other)
infix notation – set `intersect` other
You can also use `distinct()`, which returns a `List`. You can also apply `toSet()` on a `String` to convert it into a set of unique characters.

```kotlin
val setA = setOf(1, 2, 3)
setA.union(setOf(3, 4, 5)) // setOf(1, 2, 3, 4, 5)
setA intersect setOf(3, 4, 5) // setOf(3)

val list = listOf(1, 2, 1, 2, 3)
list.toSet() // (1, 2, 3)
list.distinct() // listOf(1, 2, 3)
&quot;Hello&quot;.toSet() // setOf(&apos;H&apos;,&apos;e&apos;,&apos;l&apos;,&apos;o&apos;)
```</content:encoded><category>kotlin</category></item><item><title>Why package</title><link>https://htswe.github.io/blog/why-package/</link><guid isPermaLink="true">https://htswe.github.io/blog/why-package/</guid><description>A fundamental principle in programming is the acronym DRY: Don&apos;t Repeat Yourself.</description><pubDate>Thu, 14 Oct 2021 00:00:00 GMT</pubDate><content:encoded>A fundamental principle in programming is the acronym **DRY**: `Don&apos;t Repeat Yourself`.

This is not new. In fact, over again and again, I have witnessed (guilty - I did it many times too) that we have multiple identical pieces of code in our codebase. Especially, we tend to copy the code from one place to another place without considering much. Each duplication creates opportunities for makes. This is where the package comes in.

A **package** is an associated collection of code. Each package is usually designed to solve a particular problem, and often contains multiple functions and classes. For example, `kotlin.math` packages contains many mathematical related functions.

Unlike Java, you can name the source file name to anything you like - the class name doesn&apos;t need to be the same as file name. Kotlin allows to choose any name for the package, but it is considered a good style for the package name to be identical to the directory name where the package files are located. Learn more about the [coding conventions][coding-convention] of Kotlin.

[coding-convention]: https://kotlinlang.org/docs/coding-conventions.html#naming-rules</content:encoded><category>kotlin</category></item><item><title>Kotlin: Is Read-Only List immutable?</title><link>https://htswe.github.io/blog/is-ready-only-list-immutable/</link><guid isPermaLink="true">https://htswe.github.io/blog/is-ready-only-list-immutable/</guid><description>A List is a container, which is an object that holds other objects. Containers are also called collections.</description><pubDate>Tue, 12 Oct 2021 00:00:00 GMT</pubDate><content:encoded>&gt; A `List` is a container, which is an object that holds other objects. Containers are also called `collections`.

A `List` is read-only -- you can read its contents but not write to list. However if the underlying implementation is a `MutableList` and you retain a mutable reference to that implementation, you can still modify it via that mutable reference.

```kotlin
fun main() {
  val a = mutableListOf(1)
  val b: List&lt;Int&gt; = a
  print(b) // [1]

  a += 2
  print(b) // [1,2]
}
```

As we can see, even thought the `b` is read only, the value can still be modified since it is referenced to the a which is MutableList.

Therefore, Read-Only List is still modifiable.</content:encoded><category>kotlin</category></item><item><title>Variable Argument Lists</title><link>https://htswe.github.io/blog/variable-argument-lists/</link><guid isPermaLink="true">https://htswe.github.io/blog/variable-argument-lists/</guid><description>Do you know what vararg keyword is? Using this vararg, you can define a function that takes any number of argument.</description><pubDate>Tue, 12 Oct 2021 00:00:00 GMT</pubDate><content:encoded>Do you know what `vararg` keyword is? Using this `vararg`, you can define a function that takes any number of argument.

The keyword `vararg` produces a flexibly-sized argument list.

It allows you to pass any number (including zero) of arguments, but it has to be the same type because you can later access it using the parameter name as an `Array`.

```kotlin
fun max(vararg nums: Int): Int {
  var max = 0
  for (n in nums) {
    if (n &gt; max) max = n
  }
  return max
}

sum(9) // 9
sum(3, 20, 15) // 20
```

Although `Array` and `List` look similar, they are implemented differently -- `List` is a regular library class while Array has the special low level support. Array is actually come from Kotlin&apos;s requirement of compatibility with other programming languages such as Java.

In general, we use `List` when we need a simple sequence. We only consider an `Array` if the third party library requires Array type or when we are working with `vararg`.</content:encoded><category>kotlin</category></item><item><title>Some interesting things from Kotlin Objects</title><link>https://htswe.github.io/blog/kotlin-objects/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-objects/</guid><description>Objects are the foundation for many modern languages, including Kotlin.</description><pubDate>Fri, 01 Oct 2021 00:00:00 GMT</pubDate><content:encoded>&gt; Objects are the foundation for many modern languages, including Kotlin.

While I am looking at Kotlin object-oriented programming concept, there are some interesting things that I thought of taking note and sharing with you.

### Member function vs Methods

A function defined within a class belongs to that class. In Kotlin, we call these member functions of the class. Some object-oriented languages like Java choose to call them methods, a term that came from early object-oriented languages like Smalltalk. So it is the lingo -- use it correctly.

### Mutable or Immutable Properties

&gt; A property is a var or val that&apos;s part of a class.
&gt; A `var` property can be reassigned, while a `val` property can&apos;t. Defining a top-level `val` is safe because it cannot be modified. However, defining a mutable (`var`) top-level property is considered an anti-pattern.

```kotlin
val constant = 100
var counter = 1

fun inc() = counter++
fun dec() = counter--
```

Why is the `var` in the above code anti-pattern? As your program becomes more complex, it becomes harder to maintain the shared mutable state. You cannot guarantee it will change correctly.

### It is reference, not object

When a variable is assigned with another variable, it is not creating a new object. In fact, it is actually reference to the object.

```kotlin
class Car {
  var color: String = &quot;Red&quot;
}

fun main() {
  val aCar = Car()
  val bCar = aCar

  print(&quot;${aCar.color}&quot;) // Red
  print(&quot;${bCar.color}&quot;) // Red

  aCar.color = &quot;Blue&quot;
  print(&quot;${aCar.color}&quot;) // Blue
  print(&quot;${bCar.color}&quot;) // Blue
}
```

Remember that `var` and `val` control references rather than objects. A var allows you to rebind a reference to a new different object and a val prevents you from doing so.

### Visibility

This is particularly important if your code is being used by someone else. Best example is the library. The consumers of library don&apos;t want to rewrite their codes for a new version of the library. However, the library creator must be free to modify and make improvement, with some certainty that the client code won&apos;t get affected.

To control this visibility, Kotlin provides access modifiers. Library creators decide what is and is not accessible by the client programmer using the modifiers `public`, `private`, `protected` and `internal`.

![image-center](https://1.bp.blogspot.com/-fLAS2j05q_I/YVcmNBIGQlI/AAAAAAAADck/PivKn9cCTGMcjVRLvn-fbeQs4swZtq2pwCLcBGAsYHQ/w640-h480/Screenshot%2B2021-10-01%2Bat%2B11.15.37%2BPM.png)

So, think carefully on which access modifiers is suitable for each usecase.

5. Wait, what is `internal` access modifier?
   Real programs are often large. It can be helpful to divide such programs into one or more modules. A module is a logically independent part of a codebase.

An `internal` definition is accessible only inside the module where it is defined. `internal` lands somewhere between `private` and `public` - use it when private is too restrictive but you don&apos;t want an element to be a part of public API.

### Conclusion

Sometimes, it is little pieces that matter when you are experiencing a programming language. You may think those above things are common in some programming languages as well and you are totally right. Read more about Why Kotlin post on the motivation of Kotlin. So what is your favourite thing in this post?</content:encoded><category>kotlin</category></item><item><title>Kotlin testing framework</title><link>https://htswe.github.io/blog/kotlin-testing-framework/</link><guid isPermaLink="true">https://htswe.github.io/blog/kotlin-testing-framework/</guid><description>Alright. Who here think that testing is optional? Even though some doesn&apos;t write tests, I believe no one will openly say so. Oops. it hurts.</description><pubDate>Fri, 01 Oct 2021 00:00:00 GMT</pubDate><content:encoded>Alright. Who here think that testing is optional? Even though some doesn&apos;t write tests, I believe no one will openly say so. Oops. it hurts.

&gt; Constant testing is essential for rapid program development.

If you do testing, what is your favourite testing framework/ library? What? Do you mean there is more than just JUnit? No worry if you have the same question - I do too. Well after reading sometimes, there are

- [JUnit][junit] is one of the most popular Java test framework, and easily used from within Kotlin. No wonder many of us stick with JUnit framework. (As the time of writing, the latest version of JUnit is 5.)∏
- [Kotest][kotest] is designed for Kotlin, and takes many advantages of Kotlin language features. This is what they said in the website - Kotest is a flexible and elegant multi-platform test framework for Kotlin with extensive assertions and integrated property testing.
- [Spek Framework][spek] is another interesting approach to testing. Based on the website, it said &quot;Spek is a specification framework that allows you easily define specifications in a clear, understandable, human readable way. You call them tests, we call them specifications.&quot;

Probably, you are familiar with JUnit style. Here, this is what Spek looks like for two of their styles:

```kotlin
/* Style 1 : describe it */
object SimpleSpec: Spek({
    describe(&quot;a calculator&quot;) {
        val calculator = SampleCalculator()

        on(&quot;addition&quot;) {
            val sum = calculator.sum(2, 4)

            it(&quot;should return the result of adding the first number to the second number&quot;) {
                assertEquals(6, sum)
            }
        }
    }
}
```

```kotlin
/* Style 1 : given, on, it */
object CalculatorSpec: Spek({
    given(&quot;a calculator&quot;) {
        val calculator = SampleCalculator()
        on(&quot;addition&quot;) {
            val sum = calculator.sum(2, 4)
            it(&quot;should return the result of adding the first number to the second number&quot;) {
                assertEquals(6, sum)
            }
        }
    }
}
```

Conclusion
After seeing there is other choices, I am now tempted to try out some of those. What is your thought?

[junit]: https://junit.org/junit5/
[kotest]: https://kotest.io/
[spek]: https://spekframework.github.io/spek/docs/latest/</content:encoded><category>kotlin</category></item><item><title>If expression in String templates</title><link>https://htswe.github.io/blog/if-expression-in-string-templates/</link><guid isPermaLink="true">https://htswe.github.io/blog/if-expression-in-string-templates/</guid><description>You can insert a value within a String using String templates. Remember to use a $ before the identifier name:</description><pubDate>Wed, 29 Sep 2021 00:00:00 GMT</pubDate><content:encoded>You can insert a value within a `String` using `String` templates. Remember to use a `$` before the identifier name:

```kotlin
fun main() {
    val areYouOkay = true

    println(
        &quot;${if (areYouOkay) &quot;okay&quot; else &quot;nooo&quot;}&quot;
    )
}
```

### Bonus

Use triple-quoted `String` to store multiline text or text with special characters.

```kotlin
fun main() {
val age = 5
println(
  &quot;&quot;&quot; // triple quotes
  {
  &quot;name&quot; : &quot;Kotlin&quot;,
  &quot;age&quot; : $age
  }
  &quot;&quot;&quot;
)
}
```</content:encoded><category>kotlin</category></item><item><title>If expression</title><link>https://htswe.github.io/blog/if-expression/</link><guid isPermaLink="true">https://htswe.github.io/blog/if-expression/</guid><description>One of basic things that gives me a spark in the eye is when I realise in Kotlin that:</description><pubDate>Tue, 28 Sep 2021 00:00:00 GMT</pubDate><content:encoded>One of basic things that gives me a spark in the eye is when I realise in Kotlin that:

&gt; Either branch of an `if` expression can be a multiline block of code surrounded by curly braces.

```kotlin
fun main() {
    val mall = &quot;jem&quot;
    val time = 10

    val isShoppingMallOpen = if (
        mall == &quot;jem&quot; || mall == &quot;vivo&quot;
    ) {
        // in a block
        val openHour = 8
        val closeHour = 12
        println(&quot;Mall operates from $openHour to $closeHour&quot;)
        time in openHour..closeHour
    } else {
        false // single line
    }

    println(&quot;$isShoppingMallOpen&quot;)
}
```

What does Kotlin syntax surprise you? Are you a fan of block code?</content:encoded><category>kotlin</category></item><item><title>2 Most Celebrated Kotlin Features</title><link>https://htswe.github.io/blog/2-most-celebrated-kotlin-features/</link><guid isPermaLink="true">https://htswe.github.io/blog/2-most-celebrated-kotlin-features/</guid><description>While there are many great features in Kotlin language, there are two features which are very impactful and outstanding.</description><pubDate>Mon, 27 Sep 2021 00:00:00 GMT</pubDate><content:encoded>While there are many great features in Kotlin language, there are two features which are very impactful and outstanding.

1. Java interoperability
2. Indication of Emptiness

### 1. Java interoperability

To be a &quot;better C&quot;, C++ must be backwards compatible with the syntax with C, but Kotlin does not have to be backward compatible with the syntax with Java.

&gt; It just have to work with the JVM.

This actually frees up the Kotlin team to create a much cleaner and more powerful syntax, without the complication that hindered Java.

For Kotlin, to be a &quot;better Java&quot;, the experience of using Kotlin has to be pleasant. What did Kotlin do? Kotlin allows you to **coexist** with Java projects. If you already have Java project codes, fret not. You can also put Kotlin code inside the Java project and _Java doesn&apos;t even know that Kotlin is there_. How awesome it is.

With this effortless Java interoperability, it becomes very cheap or even free to try Kotlin to see whether it&apos;s a good fit. You can try Kotlin in either Android Studio or Community free version from JetBrains that supports both Java and Kotlin. There is even the tool to convert Java to Kotlin.

### 2. Indication of Emptiness

Emptiness (No value) is one of the challenging programming problem. Imagine this. You have a dictionary (no, not the book). It is a key value pairs and you use it to look up to get the value for given key. What if there is no key? You will reply with &quot;no value for that key&quot;.

Okay. A little bit of history - _null reference_ was invented in 1965 for **ALGOL** by Tony Haore, who later called it &quot;**_my billion-dollar mistake_**&quot;. You can find out more at here.

&lt;iframe width=&quot;382&quot; height=&quot;266&quot; src=&quot;https://www.youtube.com/embed/ybrQvs4x0Ps&quot; title=&quot;YouTube video player&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt;

One problem with this null reference is that it is too simple -- sometimes being told a room is empty isn&apos;t enough. You might need to know, for example, why it is empty. This leads to the second problem: the implementation. For efficiency&apos;s sake, it was typically just a special value that could fit in the small amount of memory, and what better than the memory already allocated for that information?

The original C language did not automatically initialise storage when you declare a variable, which caused numerous problems. C++ improved it by setting newly allocated storage to all ZEROS. So if you are not initialise an integer variable, the default is zero (0). This seems not so bad, but it allowed the uninitialised values to quietly slip through the crack. Worse case, if a piece of storage is a pointer that points to another storage, a null pointer would point at location zero in memory, which is certainly not what you want.

Java addresses this problem by reporting such errors at runtime. But it can only be discovered at runtime. The only way to ensure the program won&apos;t crash is by running the program. This problem has wasted a huge amount of developer time in finding them.

Kotlin solves it by preventing operation at compile time, before the program could run. Hence it is one of the biggest impactful feature for Java developers who are now adapting to Kotlin. This can minimise or eliminate Java&apos;s most famous _NullPointerException_.

If you are wondering what NullPointerException, I have a message for you.

![image-center](https://1.bp.blogspot.com/-JNuTOjliIzg/YVHlOpvDAsI/AAAAAAAADb0/Rw8r6TgbrG44PzI9bIq4wR-_GAiu2XA_ACLcBGAsYHQ/w640-h384/questions-develoer-jobs-tags-users-earch-what-is-a-nullpointerexception-32587564.png)</content:encoded><category>kotlin</category></item><item><title>Why Kotlin</title><link>https://htswe.github.io/blog/why-kotlin/</link><guid isPermaLink="true">https://htswe.github.io/blog/why-kotlin/</guid><description>Why Kotlin? I mean why we need Kotlin in this world. Don&apos;t we have enough of programming language already? This was exactly the question that I have when Kotlin was first heard back in 2016. And then…</description><pubDate>Sun, 26 Sep 2021 00:00:00 GMT</pubDate><content:encoded>Why Kotlin? I mean why we need Kotlin in this world. Don&apos;t we have enough of programming language already? This was exactly the question that I have when Kotlin was first heard back in 2016. And then I didn&apos;t embark, part of the reasons was because most of the codes that I have to write/ maintain were written in Java.

It only came to me during 2018 when I was working on a project. I remembered that I was in holiday trip and I have to learn some basic syntax before I come back to start working on a new project.

Enough about why or when I picked up Kotlin. Let&apos;s see why we need Kotlin.

### Java History

Let&apos;s go back to 1995 when Java was first created by James Gosling and his team. They were given the task of writing code for TV set-top box. They decided that they didn&apos;t like C++ and instead of creating the box, created the Java language. What a badass. Their company, Sun Microsystems, put an enormous marketing push behind the free language to attempt domination of the emerging Internet landscape.

The perceived time window for Internet domination put a lot of pressure on Java language design, resulting in a significant number of flaws. You can find more about those in the book &quot;Thinking in Java&quot;.

Although Java was remarkably successful, an important Kotlin design goal is to fix Java&apos;s flaws so the programmers can be more productive.

Java&apos;s success came from two innovation features:

1. VM (Virtual Machine)
2. GC (Garbage Collection)

#### VM

What is VM? It is an immediate layer between the language and the hardware. The language doesn&apos;t have to generate machine code for a particular processor. It only needs to generate an immediate language called bytecode that runs on the virtual machine. This JVM (Java VM) gave rise to the Java slogan - &quot;write once, run everywhere&quot;. Other languages like Groovy or Clojure also target the same JVM.

#### Garbage Collection

It solves the problem of forgetting to release the memory, or when it is difficult to know when a piece of storage is no longer used.

### Kotlin Introduction

![image-center](https://blog.jetbrains.com/wp-content/uploads/2016/02/kotlin-1_0_Banner.png)

Just as C++ was initially intended to be &quot;a better C&quot;, Kotlin was initially oriented towards being &quot;a better Java&quot;. But it is now more than that. It **pragmatically** selects only the most successful and helpful features from other programming languages, thus if you have background in another programming language, you might recognise some features from that language in Kotlin.

Hence, The reason why Kotlin was created is to maximise productivity by leveraging tested concepts from other languages. Those includes

**Readability**
Readability is the primary goal in the design of the language. It makes it so by using concise syntax.

**Tooling**
As it comes from JetBrains, we can expect some quality in the developer tooling. It has the first class support, and they are all done by experienced people.

**Multi-Paradigm**
It supports multiple programming paradigms such as imperative programming, functional programming and object-oriented programming.

**Multi-Platform**
Although we know Kotlin for Android app development, Kotlin can be complied into different targets:

1. JVM (.class file)
2. Android (.dex file) : Current runtime is ART while former was called Dalvik.
3. JavaScript (web)
4. Native (machine code)

### Conclusion

Andrey Breslav, Kotlin Lead Language Designer, once said &quot;Languages are often selected by passion, not reason... I&apos;m trying to make Kotlin a language that is loved for a reason.&quot;

Here is the [blog post][kotlin-blog-post] by him when Kotlin was released to version 1 back in 2016.

![image-center](https://1.bp.blogspot.com/-I4zQsTT9Is0/YVCVEgsdF-I/AAAAAAAADbc/U71z1B8eLB8mTi7DzZ8qG1YpDbAwwvKvgCLcBGAsYHQ/w640-h636/Kirby-holding-a-sign-Meme-Infinite-love-meme.jpg)

[kotlin-blog-post]: https://blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/</content:encoded><category>kotlin</category></item></channel></rss>