Why shouldn't I set an Ionic provider as a global variable?

Viewed 30

In my Ionic project, I use a device.ts provider in many custom classes. The problem is, every time I use my custom classes, I have to pass my device provider into it since there's no other way to get to it.

So, my code every time would look like:

let user = User(device);
let cart = Cart(device);
let page = Page(device);

To get around this, in my provider's constructor, I can set

window.device = this;

Now, I don't need to pass device to each of my objects since I can fetch it there as window.device. What's the harm in this? There's nothing simlar to this in Ionic's documentation and I'm not sure why, or if what I'm doing is a bad idea.

1 Answers

The idea is that your custom classes could survive outside your project. Your User() should be able to be used anywhere that a device is provided (in the way it sounds like you wrote it). At least that's my humble opinion. If your custom classes rely on some variable in your project, then they cannot stand on their own and aren't reusable.

If you never plan to reuse your code, go for it, you do you. I always chase best practices, but sometimes wasting time doing so. Do what is best for your situation.

I always believe modularity makes my code easier for me to understand and fix later. If one piece of code is self contained and doesn't rely on another section of code or global variable and can be understood on its own without understanding the entire project it is always more maintainable for me.

Related