Home IOS Development Object-Oriented Programming Greatest Practices with Kotlin

Object-Oriented Programming Greatest Practices with Kotlin

0
Object-Oriented Programming Greatest Practices with Kotlin

[ad_1]

Object-Oriented Programming (OOP) is the most well-liked pc programming paradigm. Utilizing it correctly could make your life, and your coworkers’, lives simpler. On this tutorial, you’ll construct a terminal app to execute shell instructions on Android.

Within the course of, you’ll study the next:

  • Key ideas of Object-Oriented Programming.
  • SOLID ideas and the way they make your code higher.
  • Some Kotlin particular good-to-knows.

Additionally, when you’re fully new to Android improvement, learn by way of our Starting Android Improvement tutorials to familiarize your self with the fundamentals.

Observe: This tutorial assumes you understand the fundamentals of Android improvement with Kotlin. Nonetheless, when you’re new to Kotlin, try our Kotlin introduction tutorial.

Getting began

To start with, obtain the Kodeco Shell mission utilizing the Obtain Supplies button on the high or backside of this tutorial.

Open the starter mission in Android Studio 2022.2.1 or later by choosing Open on the Android Studio welcome display screen:

Android Studio Welcome Screen

The app consists of a single display screen much like Terminal on Home windows/Linux/MacOS. It permits you to enter instructions and present their output and errors. Moreover, there are two actions, one to cease a operating command and one to clear the output.

Construct and run the mission. It is best to see the principle, and solely, display screen of the app:

Main Screen

Whoa, what’s occurring right here? As you’ll be able to see, the app at the moment refuses to run any instructions, it simply shows a non-cooperative message. Due to this fact, your job might be to make use of OOP Greatest Practices and repair that! You’ll add the flexibility to enter instructions and show their output.

Understanding Object-Oriented Programming?

Earlier than including any code, it is best to perceive what OOP is.

Object-Oriented Programming is a programming mannequin primarily based on information. All the things is modeled as objects that may carry out sure actions and talk with one another.

For instance, when you had been to signify a automotive in object-oriented programming, one of many objects could be a Automotive. It could comprise actions corresponding to:

  • Speed up
  • Brake
  • Steer left
  • Steer proper

Lessons and Objects

One of the vital distinctions in object-oriented programming is between lessons and objects.

Persevering with the automotive analogy, a category could be a concrete automotive mannequin and make you should buy, for instance — Fiat Panda.

A category describes how the automotive behaves, corresponding to its high pace, how briskly it may well speed up, and so forth. It is sort of a blueprint for the automotive.

An object is an occasion of a automotive, when you go to a dealership and get your self a Fiat Panda, the Panda you’re now driving in is an object.

Class vs Object

Let’s check out lessons in KodecoShell app:

  • MainActivity class represents the display screen proven whenever you open the app.
  • TerminalCommandProcessor class processes instructions that you simply’ll enter on the display screen and takes care of capturing their output and errors.
  • Shell class executes the instructions utilizing Android runtime.
  • TerminalItem class represents a piece of textual content proven on the display screen, a command that was entered, its output or error.

KodecoShell classes

MainActivity makes use of TerminalCommandProcessor to course of the instructions the person enters. To take action, it first must create an object from it, known as “creating an object” or “instantiating an object of a category”.

To attain this in Kotlin, you utilize:


personal val commandProcessor: TerminalCommandProcessor = TerminalCommandProcessor()

Afterward, you can use it by calling its capabilities, for instance:


commandProcessor.init()

Key Rules of OOP

Now that you understand the fundamentals, it’s time to maneuver on to the important thing ideas of OOP:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

These ideas make it attainable to construct code that’s straightforward to know and keep.

Understanding Encapsulation and Kotlin Lessons

Information inside a category might be restricted. Be sure different lessons can solely change the information in anticipated methods and stop state inconsistencies.

In brief, the skin world doesn’t have to know how a category does one thing, however what it does.

In Kotlin, you utilize visibility modifiers to manage the visibility of properties and capabilities inside lessons. Two of a very powerful ones are:

  • personal: property or perform is barely seen inside the category the place it’s outlined.
  • public: default visibility modifier if none is specified, property or perform is seen in every single place.

Marking the interior information of a category as personal prevents different lessons from modifying it unexpectedly and inflicting errors.

To see this in motion, open TerminalCommandProcessor class and add the next import:


import com.kodeco.android.kodecoshell.processor.shell.Shell

Then, add the next inside the category:


personal val shell = Shell(
    outputCallback = { outputCallback(TerminalItem(it)) },
    errorCallback = { outputCallback(TerminalItem(it)) }
)

You instantiated a Shell to run shell instructions. You possibly can’t entry it exterior of TerminalCommandProcessor. You need different lessons to make use of course of() to course of instructions by way of TerminalCommandProcessor.

Observe you handed blocks of code for outputCallback and errorCallback parameters. Shell will execute considered one of them when its course of perform known as.

To check this, open MainActivity and add the next line on the finish of the onCreate perform:


commandProcessor.shell.course of("ps")

This code tries to make use of the shell property you’ve simply added to TerminalCommandProcessor to run the ps command.

Nonetheless, Android Studio will present the next error:
Can't entry 'shell': it's personal in 'TerminalCommandProcessor'

Delete the road and return to TerminalCommandProcessor. Now change the init() perform to the next:


enjoyable init() {
  shell.course of("ps")
}

This code executes when the appliance begins as a result of MainActivity calls TerminalViews‘s LaunchEffect.

Construct and run the app.

In consequence, now it is best to see the output of the ps command, which is the record of the at the moment operating processes.

PS output

Abstraction

That is much like encapsulation, it permits entry to lessons by way of a selected contract. In Kotlin, you’ll be able to outline that contract utilizing interfaces.

Interfaces in Kotlin can comprise declarations of capabilities and properties. However, the principle distinction between interfaces and lessons is that interfaces can’t retailer state.

In Kotlin, capabilities in interfaces can have implementations or be summary. Properties can solely be summary; in any other case, interfaces might retailer state.

Open TerminalCommandProcessor and substitute class key phrase with interface.

Observe Android Studio’s error for the shell property: Property initializers aren't allowed in interfaces.

As talked about, interfaces can’t retailer state, and you can not initialize properties.

Delete the shell property to get rid of the error.

You’ll get the identical error for the outputCallback property. On this case, take away solely the initializer:


var outputCallback: (TerminalItem) -> Unit

Now you have got an interface with three capabilities with implementations.

Substitute init perform with the next:


enjoyable init()

That is now an summary perform with no implementation. All lessons that implement TerminalCommandProcessor interface should present the implementation of this perform.

Substitute course of and stopCurrentCommand capabilities with the next:


enjoyable course of(command: String)

enjoyable stopCurrentCommand()

Lessons in Kotlin can implement a number of interfaces. Every interface a category implements should present implementations of all its summary capabilities and properties.

Create a brand new class ShellCommandProcessor implementing TerminalCommandProcessor in processor/shell bundle with the next content material:


bundle com.kodeco.android.kodecoshell.processor.shell

import com.kodeco.android.kodecoshell.processor.TerminalCommandProcessor
import com.kodeco.android.kodecoshell.processor.mannequin.TerminalItem

class ShellCommandProcessor: TerminalCommandProcessor { // 1
  // 2  
  override var outputCallback: (TerminalItem) -> Unit = {}

  // 3
  personal val shell = Shell(
    outputCallback = { outputCallback(TerminalItem(it)) },
    errorCallback = { outputCallback(TerminalItem(it)) }
  )

  // 4
  override enjoyable init() {
    outputCallback(TerminalItem("Welcome to Kodeco shell - enter your command ..."))
  }

  override enjoyable course of(command: String) {
    shell.course of(command)
  }

  override enjoyable stopCurrentCommand() {   
    shell.stopCurrentCommand()
  }
}

Let’s go over this step-by-step.

  1. You implement TerminalCommandProcessor interface.
  2. You declare a property named outputCallback and use the override key phrase to declare that it’s an implementation of property with the identical identify from TerminalCommandProcessor interface.
  3. You create a non-public property holding a Shell object for executing instructions. You move the code blocks that move the command output and errors to outputCallback wrapped in TerminalItem objects.
  4. Implementations of init, course of and stopCurrentCommand capabilities name applicable Shell object capabilities.

You want yet one more MainActivity change to check the brand new code. So, add the next import:


import com.kodeco.android.kodecoshell.processor.shell.ShellCommandProcessor

Then, substitute commandProcessor property with:


personal val commandProcessor: TerminalCommandProcessor = ShellCommandProcessor()

Construct and run the app.

Welcome to Kodeco Shell

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here