vendredi 6 novembre 2015

What should I do about frequently repeated constants?

This seems like a very simple question, but I can't find a clear answer. Also it's not specifically about swift or iOs, but I'm new to programming and swift is the only language I know anything about, so I don't know how to phrase it for a more general context.

I'm trying to write an iOs app and I found myself defining the same constants many times throughout my code.

I must have written this line about a hundred times, for instance:

let calendar = NSCalendar.currentCalendar()

Another example is getting my only User object from its persistent store:

let realm = try! Realm()
let user = realm.objects(User).first!

I define those calendar and user constants over and over throughout my whole code in classes and subclasses and extensions and computed properties.

That seems kind of stupid, though. I think I should be able to define calendar once and for all and just use it when I need it. So my first thought was to declare a global constant, but apparently everybody thinks anything with the word "global" in it should be avoided at all costs.

So what should I do? Is there another solution for this? Should I just keep writing the same stuff over and over again?

Thanks in advance,

Daniel

Aucun commentaire:

Enregistrer un commentaire