Where should variables be declared in Swift - ios

I have been declaring variables both inside and outside a Class as shown below. My understanding of OOP is to limit their scope. However, to use them in other classes/files I put them outside (e.g."testLabel"). Mainly because it "works" and I am not familiar enough with OOP to do otherwise.
var testlabel:UILabel!
public var earth = SKShapeNode(circleOfRadius: 15)
class GameScene: SKScene , SKPhysicsContactDelegate {
var startTime = NSTimeInterval()
var skView:SKView!
My question is: What is best practice in Swift/OOP to make variables available to all classes?
I have read several discussions but still not clear on the dangers (versus convenience) of declaring variables publicly or globally.
Thanks for your help.

If you declare a variable outside of a class it becomes Global variable.
It's best practice to declare variables with in class if you don't use them in another classes.
I am not sure if there are any dangers if we declare as global variables.

The "dangers" of declaring global variables are more like "code smells" or bad practice. They aren't dangerous in that they will cause your code to crash, but they are dangerous in that they cause your code to become more unwieldy and more difficult to maintain, as your classes are not neatly encapsulated, and some of their functionality lives other places.
Sometimes global behavior is necessary, though. In that case, I think you should make a shared instance or singleton of some class that all other classes can reference. Then, instead of having magic floating variables, you at least encapsulate that behavior in one class that is easy to find and control. Apple uses shared instances all over their code.
http://www.raywenderlich.com/86477/introducing-ios-design-patterns-in-swift-part-1
https://thatthinginswift.com/singletons/

Related

Discussion Question: Why doesn't dart allow to declare enums in class?

I tried to declare an enum inside the class and it gave me an error stating can't have enum inside a class. I wanted to know the reason why but I didn't find anything on the internet. Declaring enum inside a class is allowed by major languages why not dart?
Dart does not allow nested type declarations in general. You can only declare types at top-level. This includes classes, mixins, typedefs and enums.
I believe the original reason was that it was not necessary, and implementing it inadequately was worse than not doing allowing it at all.
There is nothing inherently preventing Dart from allowing static types declared inside other types. Obviously, if Dart allowed classes statically declared inside classes, it would allow in arbitrary nesting of classes, so it really is a matter of allowing zero, one or an infinite amount of nesting. Dart currently has "one'.
Still, it's something that can be easily remedied if deemed wort the effort and a higher priority than other language changes.
The other option is to have non static nested types. That's a much bigger can of worms, and probably not something that's going to happen any time soon, if ever.
Dart doesn't allow declaring of Enum inside the class as far as I know. I've made that error before and it took me a minute to figure out what was wrong with my code. Declare/setup your Enum before your class like so:
enum Gender {
male,
female,
}
/// Then declare your class next
class MyClass {
/// The rest of your code goes here, and you still have access to your enum
}

Why are instance variables considered bad practice by Apple?

In Apple's Programming with Objective-C the section on Encapsulating Data states that:
You Can Define Instance Variables without Properties
It’s best practice to use a property on an object any time you need to keep track of a value or another object.
In other words they are strongly recommending that you use private properties rather than instance variables for any private object state.
I am wondering why this might be the case? I understand that properties have features such as KVO, and attributes (strong, weak ...), but in many cases I do not need these features and an instance variable will work just fine.
Are there any good reasons why instance variables might not be considered best practice?
Even though right now your private variable might work as a plain variable, you may decide later that some of properties 'goodies' are useful:
observing
atomic accessors
custom accessors
logging on access
access from subclasses
If you only access your variables as properties, you don't add much overhead (except in tight cycles) and leave room for reaping any of those benefits described above.
Basically, properties are useful even if you don't ever plan on making them public.
Of course, there are places where using an instance variable is still 'more natural', for example if you reimplement Foundation classes in a class cluster (such as NSArray), it's expected that your implementation is private and performant, so I don't use properties then.
Also, I don't think you should read too much into the advice. To me it reads more like "If you've only learned 5 minutes ago about properties and instance variables, let's start with using properties first".
People who are new to the language can go quite far without knowing what the instance variables are.
In other words they are strongly recommending that you use private properties rather than instance variables for any private object state.
Where did you read that they are recommending private properties? I think they mean public variables/properties.
And of course using properties instead of public instance variables has a lots of advantages:
encapsulation and custom getters/setters
memory management
KVO
binary compatibility
and so on
But in my opinion using private properties in general has no advantages and it's much easier to use private instance variables. The only reason I can imagine is to make custom getters/setters for such variables in future, but I don't think that it's a "best practice".
The point is underlaying storage abstraction. So simple yet very powerful.

Using hidden properties vs. private iVars

This question is specifically focused around static libraries / frameworks; in other words, code that other people will eventually touch.
I'm fairly well versed in properties, since I started iOS development when iOS 6 was released. I have used hidden properties declared in interface extensions to do all of my "private" property work, including using readonly on public facing properties I don't want others to modify and readwrite within interface extensions.
The important thing is that I do not want other people who are using these static libraries / frameworks to be accessing these properties if I don't allow it, nor writing these properties if I let them read it.
I've known for a while that they could theoretically create their own interface extension and make my readonly properties readwrite themselves, or guess the names of hidden properties.
If I want to prevent this, should I be using ivars with the #private tag with directly declared ivars? Are there potential downfalls to doing it this way? Does it actually get me an additional measure of security, or is it a red herring?
Under ARC the only mode supported by properties and not instance variables is copy - so if you need copy use a property.
If you declare your private instance variables in the #implementation section:
#implementation MyClass
{
// private instance vars
}
then it takes serious effort to access them from outside the class. As you say accessing a "private" property just takes guessing its name - or using the library calls which tell you.
Is it worth it for security? YMMV. But its a good coding practice regardless.
Addendum
As the comment trail shows there has been much discussion over my use of serious effort.
First let's be clear: Objective-C is in the C family of languages, they all allow the programmer to just about anything they choose while staying within the language[*] - these are not the languages of choice if you want strong typing, access restrictions, etc., etc. within your code.
Second, "effort" is not an absolute measure! So maybe I should have chosen the word "obvious" to qualify it rather than "serious". To access a private property just requires the use of a standard method call where the object has type id - there is little clue in the code that the method being called is hidden. To access a private variable requires either an API call (a runtime function or KVC call) or some pointer manipulation - the resultant code looks nothing like a standard variable assignment. So its more obvious.
That said, apart from uses requiring copy, under ARC there is no good reason to use a private property when a private instance variable will do. For a private variable fred compare:
self.fred = 42; // property access, may involve a call (if not optimised out)
_fred = 42; // common way to bypass the accessors and get at the underlying var
fred = 42; // direct access
Take your pick, there is no right answer, but there isn't a wrong one either - this is the realm of opinion (and that is of course an opinion ;-)). I would often pick the last one, private variable - clean & simple. However #RobNapier in his answer prefers the use of properties.
[*] Note: once you consider linking to external code, say written in assembler, all bets are of in any language. At that point you have to look at the "hardware" (real or virtual) and/or "OS" to provide protection.
You should use private ("hidden") properties here. There is no "security" risk. The "attacker" in this scenario is the caller. The caller has complete access to all memory in the process. She can access anything in your framework she wants and there is absolutely nothing you can do to stop that (nor should you). This is true in any language. You can bypass "private:" designations in C++ as well if you know what you're doing. It's all just memory at the end of the day.
It is not your job to protect yourself or your framework from the caller. You both have the same goal: correct program behavior. Your goal is to protect callers from themselves. Make it difficult for them to use your framework incorrectly and easy to use it correctly.
So, you should use the tool that leads to the most correct code. And that tool is properties, and avoiding directly ivar access except in init and dealloc.

Is using too many static variables in Objective-C a bad practice?

Will usage of static variables expose them to a danger of being modifiable from anywhere ?(In context of Objective-C). If yes, can someone suggest best alternatives for using shared variables across all classes ?
Is using too many static variables in Objective-C a bad practice?
Yes. Of course, "too many" has not been quantified and is subjective. Really, global/static variables are very rarely a good thing -- very convenient to introduce and very difficult to debug and eliminate. Also rare is the case that they are good design. I've found life far easier without them.
Will usage of static variables expose them to a danger of being modifiable from anywhere? (In context of Objective-C).
It depends on where they are declared and how they are used. If you were to pass a reference to another part of the program, then they would be modifiable from 'anywhere'.
Examples:
If you place them so that only one file can "see" the variable (e.g. in a .m file following all includes), then only the succeeding implementation may use it (unless you pass a reference to the outside world).
If you declare the variable inside a function, then it is shared among each translation and copied for each translation in C/ObjC (but the rules are very different in C++/ObjC++).
If yes, can someone suggest best alternatives for using shared variables across all classes?
Just avoid using globals altogether. Create one or more type/object to hold this data, then pass an instance of it to your implementations.
Singletons are the middle ground, in that you have some type of global variable/object based abstraction. Singletons are still so much hassle -- they are categorized as global variables and banned in my codebase.
Static variables are local to the translation unit, so the variables are definitely not modifiable from anywhere. Globals, which are closely related to statics in that they are allocated in the same memory area, are modifiable from anywhere, and that's their main danger.
When you need a group of variables to be accessible from anywhere in your project, the common approach is implementing a singleton that holds related data, and contains methods for processing that data. In MVC apps implemented in Objective C the model is often accessed through a singleton model object.
My scenario involves a number of static variables declared in the .h file & they are assigned values in specific methods declared in those .h files.
If you declare statics in the header, they become "disconnected" from each other: each translation unit (i.e. each .m file) gets its own set of statics from the header. This is usually not what you want.
If you make these variables global, you end up with a plain C, not an Objective C, solution. You should put these variables in a class as properties, and move function implementations with them into the methods of your class. Then make the class a singleton as described in the answer linked above to get a solution that is easier to understand than the corresponding solution based on globals.

A pragmatic view on private vs public

I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!

Resources