phonix94
phonix94

Reputation: 15

Asking About Using Variable in Kotlin

I am new to programming and currently trying to learn how to build an application by using Kotlin. I just want to ask should I declare variable outside of the main activity class and then access it in another activity. For example, in the following code:

   var post: ArrayList<Model> = ArrayList()
   class MainActivity : AppCompatActivity() { 
    }

I declare the post ArrayList outside of the mainActivity and then in my second Activity, I can access it without using any technique to pass and receive data. I have never seen any instruction to do that way and wonder why it should not be done. Sorry if my question is stupid.

Upvotes: 0

Views: 68

Answers (1)

Tenfour04
Tenfour04

Reputation: 93609

In general terms, it is good design practice to avoid putting data in globally-accessible properties because it increases the overall complexity of the application. I don't mean in terms of lines of code, because doing it this way is in this case is actually fewer lines of code.

The problem is that it increases coupling between different elements of your code. For example, if multiple classes are accessing that list property, any of them could change the contents of the list, or even what list it is pointing to. This can make it exponentially harder to track down bugs that involve the property because it can be modified from so many different places, and it also makes it exponentially more likely to cause bugs in the first place, for the same reason.

It also makes it more difficult to modify code or change your design as your app evolves. When there are possibly many places in your code that access this same list, you have to keep them all in mind as you make changes to how it works.

And it makes it difficult to create unit tests for testing small segments of your application independently. To properly unit test something, you'd have to simulate all the things that can happen to that list from all possible sources.

A second issue with it is simply that the data may exist in memory longer than it needs to be, which is wasteful.

Addressing the comments: there's no reason putting them in a companion object would be any better. Either way, they are still globally accessible.

Upvotes: 1

Related Questions