Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 86

Sometimes You Don't Need a Property!

Оглавление

Unbelievably, after all this work, the output from your code is still incorrect if a last name is changed after object instance creation. One simple fix here is to update the two custom mutators, for firstName and lastName, to update fullName, like this:

var firstName: String = _firstName set(value) { field = value // Update the full name fullName = combinedNames() } var lastName: String = _lastName set(value) { field = value // Update the full name fullName = combinedNames() }

Now, finally, things will work! The rather unexciting output after all this work should look like this:

Brian Truesby Rose Bushnell Rose Bushnell-Truesby

But before you pop the champagne, take a minute to think this through. Is this really a good solution? You have several problems here, all of which are nontrivial. See if these make sense; by now, they all should:

 You've got the same piece of code—the assignment to fullName—in both the firstName and lastName mutator. In general, anytime you see the same code twice, that's not great. Try to avoid repeating code, as it becomes error-prone.

 You're going to a lot of work to set the value of a property that has no special behavior. It's just the combination of the first and last names of the instance!

 You already have a function that gives you the full name; it's called combinedNames().

A much better approach, believe it or not, is to just remove fullName altogether. In fact, there's a lot that can be removed here.

Let's use combinedNames() to handle the combination of firstName and lastName. Then you can remove the declaration of the fullName property altogether. But if you do that, then you can actually remove the custom mutator for firstName and lastName, too!

And go one further; rename combinedNames() to fullName(), and then update toString() to just use that. After all that, you should have something like Listing 2.10, which is pretty minimal!

Programming Kotlin Applications

Подняться наверх