Your First Kotlin Android App: Polishing the App

Jul 14 2022 · Kotlin 1.6, Android 12, Android Studio Bumblebee | 2021.1.1

Part 1: Build Out the App

06. Improve the Alert Title

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Challenge: Keep Track of Game Rounds Next episode: 07. Challenge: Add Bonus Points

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 06. Improve the Alert Title

Okay, this is not a challenge episode. I didn’t mean what I said earlier.

Now, if you look at the bullseye app, you can see that it is playable but there’s definately room for improvement. Currently, the alert view still says “Hello, There!”. You could give it the name of the game, Bull’s Eye, but I have a better idea. What if you change the title depending on how well the player did?

If the player put the slider right on the target, the alert could say: “Perfect!” If the slider is close to the target but not quite there, it could say, “You almost had it!” If the player is way off, the alert could say: “Not even close…” And so on. This gives the player a little more feedback on how well they did.

In the previous course, you learned about variables, strings, and if statements, this should be a breeze. Let’s try it out!

You’re going to create a new function that will return a string, in this case, the alert’s title. You’ll add it right below the showResult method.

But first, let me show you a cool way to get around your file inside Android Studio. If you look at the tool window bar on the left side of your screen, you’ll see the structure button. Go ahead and click on it. This opens up a window on the side. The structure window as its name suggests, shows you the structure of the file. In here, you can see MainActivity class, its variables and the methods declared inside it. Clicking on them takes you to that point inside the editor window.

Go ahead and click on the showResult method. And you can see, the editor scroll to that point in our code. The structure window can come in handy when working with large files and you down want to spend time searching or trying to scroll to a particular point in your code. With the structure window, you get a bird’s eye view or should I say you hit the bull’s eye of the point you want to be in your code.

Okay, enough of promoting Android Studio even when I’m not an official brand Ambassador for JetBrains.

Now, click on the structure button once again to close the window.

Then go ahead and add the following code below the showResult method:

private fun alertTitle(): String {
    
}

This function is expected to return a String as seen from its definition. And that’s why you have an error since nothing has been returned. Not to worry, you’ll return something shorthly. Next, you’ll get the difference by doing a little calculation like so:

val difference = abs(targetValue - sliderValue)

At this point, we’ll declare a title variable and set it in an if block. I’ll do that now:

val title: String = if (difference == 0) {
    getString(R.string.alert_title_1)
} else if (difference < 5) {
    getString(R.string.alert_title_2)
} else if (difference <= 10) {
    getString(R.string.alert_title_3)
} else {
    getString(R.string.alert_title_4)
}

Finally, we’ll return the title:

...
return title

The code is self descriptive. We simply assign the title based on the value of the difference. And we set the conditions using the if statement. Do note that the string resources are already added to the starter project of this episode. To see them, hold down the Cmd key and click on one. This takes you its definition in the strings.xml file. And you can see the alert title level with its coresponding title string. I’ll close this file up and go back to the MainActivity.

If you notice, Android Studio shows a warning on the if statement. Let’s hover over it. It says “Cascade if should be replaced with when” Cascade here means that we’re assigning the result of the if statement directly to the title variable.

So it suggests that there’s a better syntax for this: using the when statement. Let’s use the suggestion. Click on the bulb icon then select “Replace ‘if’ with ‘when’” And your code is updated to accordingly.

Take a look at the code. It’s pretty much doing the same thing but with a different syntax using the when statement. If you dont like this syntax, just undo the change and move on. Remember, its a warning and not an error. You’ll learn more about the when statement as you progress in your learning path.

Finally, let’s assign this method we just created as the title of the dialog. Replace the current value to this method like so:

val dialogTitle = alertTitle()

Run the app.

Then play multiple rounds to see different variations of the alert title.

This looks great - but something doesn’t really smell right. Not an actual smell, but something known as a “Code smell.” What is a code smell? You might ask.

Whenever you find repeated lines of code in your app, that’s a code smell. In our code, you can see have the same code to calculate the difference repeated in multiple places. Programmers prefer to write each line of code only once and then reuse it in multiple places.

This is an approach that programmers call “Don’t Repeat Yourself,” which is often shortened to DRY.

The rationale behind DRY is to make code easier to read and change and to make it less prone to errors when updating your code. Because you have the code in one place which is then reused in multiple places.

For example, if you decided later that you wanted to change the way that you convert the slider’s value, you’d have to change it in one spot if you were using DRY code. If you didnt use DRY then you’ll have to remember to fix the code in different spots.

Code smell here simply means repeating code becomes a problem when you have to update the same code in multiple places. Thats a deeper problem if you think about it carefully.

Now, determining what is and what’s not a code smell is subjective and can be very opinionated.

For instance, I personally use the WET approach which means “Write Everything Twice.” With this approach I only refactor my code when I need to reuse the same code the third time. With this, I save a lot of time during development and avoid premature optimization because in many cases, I only need those repeated code in two places.

And with this, i have successfully confused you on which approach to use. Okay let’s use the DRY approach to get rid of the code smell.

The first thing you’ll do is create a new method to calculate the difference. We’ll call this differenceAmount. Enter the following code above the pointsForCurrentRound() method:

private fun differenceAmount() = abs(targetValue - sliderValue)

The code above shows the use of something called: “Single Expression Function.” It acts like a variable and if you notice we did not include the return type of Int in the function definition. This is simply because the function is short and easy to read so the compiler can easily infer its type as Int.

Now go ahead and replace it where the difference is needed inside the pointsForCurrentRound() method. And also inside the alertTitle() method.

Cool!!! And with that, our code smell is gone and we have a reusable method for the difference calculation.