Why do we need separate ".swift" files for each class? - ios

Wondering if you might be able to answer a very basic beginner question for me. I’m working through the Cocoa + Swift tutorial on Lynda and I’m a little confused about classes/objects.
Basically, I want to know why we have to create a new swift file for each new class we create.
As far as I know, you can create a new class within any .swift file in the project. My question is, why do we have to continually keep creating .swift files for each new class.
I’m wondering why there isn’t just one .swift file called AllClasses.swift that you can create all the classes in, for instance:
Within AllClasses.swift is the following code:
Class FirstClass : NSObject
Class SecondClass : NSObject
Class ThirdClass : NSObject
Class FourthClass : NSObject
As Opposed to:
Within FirstClass.swift is the following code:
Class FirstClass : NSObject
Within SecondClass.swift is the following code:
Class SecondClass : NSObject
Within ThirdClass.swift is the following code:
Class ThirdClass : NSObject
Within FourthClass.swift is the following code:
Class FourthClass : NSObject
I just want to know why we need to separate different code into files if it can be called from within any area of the project. In the case of a Mac application, it seems like almost everything could be done from within the AppDelegate.swift file.
This is a moronic question, but another hurdle that may be making object orientation a hard concept for me to fully grasp.

Maybe I can explain it in a somewhat amusing way:
In the beginning there was no concept of files and all code was in a single entity. Code within such entities was referenced by line numbers. Because everything was in one place it was easy to find what you wanted, even though programs were small. It was better than punch tape and so there was much rejoicing. We gotta do something about loading from cassette though.
But then someone discovered you could break up the code into separate parts called modules which was just as well as software was getting bigger. Man my 10MB hard drive is huge. Each module was a specialist and could call other specialists. It made your code easier to navigate. There was much rejoicing.
But then someone discovered object-orientation (OO) and files were cheap. Programs were so large now people were having a hard time finding that class that modelled the airspeed of an African Swallow in that multiple-class-containing file of 10000+ lines that maybe its time to start putting each class in its own file. Needless to say there was much rejoicing.
Then software had become so large that someone discovered source control which was most important when a team of coding scribes all meditated on a piece of software. Madness ensured for the brotherhood whose careless endeavour to write a program in one file of 30,000+ lines (research on African Swallows had grown to include European Swallows) even with OO, only lead to line conflict after line conflict during their attempts to check in changes into the source control system. There was much burning at the stake. Later revelations lead to breaking up the code into many texts or files was the way to avoid a lynching.
In summary, there is no rule to say you must have one file per class but its a good practice to do so mainly in the event your program grows to any reasonable size or complexity that navigation and maintenance of your code would become an issue if you do not.
It becomes more important when working with a team where as the number of authors working concurrently on any given file, the probability of source code commit conflict rises.
I believe the monks are studying their favourite colours and capital cities of countries now.

Some reasons:
Encapsulation / Access Control. It's a bad practice to contain several classes in the same file as you'll be able to access every single variable / method from that source file even if that is marked as private, as stated in Apple documentation:
Private access restricts the use of an entity to its own defining
source file. Use private access to hide the implementation details of
a specific piece of functionality.
Separating your classes in separate files helps the compiler to build faster. When Swift 1.2 compiler was released, incremental builds were introduced to speed up the build times. Files that are not edited are not compiled again on your next build:
Incremental builds — Source files that haven’t changed will no longer
be re-compiled by default, which will significantly improve build
times for most common cases. Larger structural changes to your code
may still require multiple files to be rebuilt.
Writing code well organized. Together with defining correctly the responsabilities of your classes (divide and conquer) that will help you (and your teammates, if any) to understand who does what and where. And, as commented in other answers, to make your source control management easier to track.

You don't have to define just one class per file, but I would suggest doing so. I recently worked on a project for a client where there were several classes in some source files, and where some classes were defined in files who's names didn't match the class names. (This was in Objective-C, so each "file" was really a pair of files, a .h header file and a .m implementation file, but logically they were one.)
It was confusing as h*ll, and I wasted a fair amount of time fumbling around trying to find things.
Defining one class per file and making your filenames and class names match exactly is a good convention. It's like having each school subject in a separate binder. When you need to find a class you know exactly what file to open to find it.

As good practice:
If the classes are unrelated, lengthy or used independently from other unrelated classes then they should be in separate files.
However, if the classes are tightly coupled with one another and are not lengthy then they could be in the same file.
This post also touches on this subject.

As a newbie I really agree it is difficult to get the classes and inheritance concepts.
But believe it is much better to handle code in separate documents, perhaps using MVC concept, rather than having this code in a single massive document.
My own experience, it clears out the clouds of your code.

I just want to add the observation that Swift's fileprivate access modifier actually sometimes requires putting many classes inside a single source file.
The "one class per source file" doesn't necessarily fit the design of Swift. For this reason, when I need to tightly control which properties I expose, I often have one very large source file for a single API.
The only alternative is to make a separate framework for each API and using internal fields.

Related

How do libraries interact with other code?

I've been reading about encapsulation and keep seeing comments about how changing the privacy of a class or adding getters and setters where there were none before can 'break the code' of people who use your library. I don't really understand this. I'm very inexperienced in programming, and my understanding is that you download a library onto your computer and it's included in the files of the program you're writing, so if the original author changed something in THEIR COPY of the library, it wouldn't affect your copy. Is this wrong? For example, is a library more like a website that your computer connects to through the internet and the original author can update, so that changes they make to it can affect how your code works?
Software is constantly changing, so we must have a way to keep track of the different versions - hence software versions. When you download a library to use in your own program, you (usually, like with a dependency management tool) end up downloading a very specific version of that library.
If a library author was to change the interface to use it, developers using that library would also have to change how they use it when they download the version with those changes. Otherwise, it would break any code that follows an outdated interface.
As long as a library author follows proper versioning procedures, for instance including breaking changes in a new major version, and the changes improve the clarity of the library's interfaces without sacrificing other properties, then the argument is moot. Developers can either continue using the old version or update their code to be compatible with the new version.
Except for maybe in low resource, embedded systems that can use all optimizations available, like accessing object/structure properties directly rather than through a function.
Libraries:
By definition a collection of non-volatile resources used by computer
programs, often for software development. These may include
configuration data, documentation, help data, message templates,
pre-written code and subroutines, classes, values or type
specifications.
Explanation
Let me spend time on defining in coding aspects: Lets say you have a
create a soccer game, what does that need, field, ball, players,
flags.
All this we encapsulate in Class to make as Object Game which
comprises all above.
Now you start building game and realise you are spending redudant time making repeated player names, shirt design , details filling, etc.
To avoid this you make functions which are business specific like 1. generate tshirts and pass (color, design , cloth type) and it returnes you tshirt object in return.
Similary you get player information by passing country and his ID and all this details are return as Player object which have his name, place, country, contacts ets.
This is how the functions in class behaves.
Your ask
privacy of a class or adding getters and setters, ...an 'break the code' of people who use your library
These are ways how you access the object parameters or set values for them , in some languages the getter and setters are auto generated and not required to explicitly set unless you need custom settings during class object creation.
The best advantage of the getting and setter is it ensures the default class creation can be assigned some values which you dont want to change in defaults and also not allow people to enforce new values to that specific parameter of class.
This is how the control is made in place during defining your class and its functions. getter and setter are functions as well with class variables having factility to get/set values as you define the function logic inside.
You ask
my understanding is that you download a library onto your computer and
it's included in the files of the program you're writing, so if the
original author changed something in THEIR COPY of the library, it
wouldn't affect your copy. Is this wrong?
Yes think it like a CD Copy , I sent you a copy so you can use those info from the copy i made, but once i have new features and things added in CompactDisc(CD) it wouldnt be there in your copy i burnt during that time hence you code uses the old version and may use till there is need to update.
You can only get impacted if you take my new CD copy which is called as upgrading your software with my new library version.
Normally big guys software dont immediately change the library in their systems unless there is thorough analysis done with 1. need, 2. security 3. bugs in old fixed in new. factors to address for a new upgrade.
Happy Coding
Software world is free of your mind to code so dont think what is wrong or right just code.
Take a Maths Library building task in hand use anything python, java, c#, objective C, swift, javascript ...
Create library with modules with Circle, Square, Polygon, Sphere objects
Each object they will have thier respective Classes created with theier paramters (circle sample : radius, center(x,y), etc and functions like setRadius, getCircumference, etc)
Similar way all objects makes thier own classes
Abstrat word you used means some function you make private that only class can internally access but not exposed to outside when you create new Maths Object.
Hope this was helpful, happy coding.

Good or bad idea to prefix all classes with same abbreviation?

So in practically all my programs I wrote I always prefixed every class I created with the same abbreviation that was in relation to the program. So for instance say I wrote an app called GasStationDeluxe. I would make a class called GSDGasStation or GSDGasPump etc. Now I always thought that is a good idea because it would group together all thelse classes I created in intellisense to make it easier for me and other programmers to find the classes I created.
Yet, I'm reading a book called "Clean Code: A Handbook of agIle software craftsmanship" and I just read a part in a chapter where it says it's not a good idea to do that becasue auto complete will bring you back a list of tons of classes. So who else codes this way? Do you think it's a good or bad idea to code with the same prefix before each class? If yes or no, then why?
I have never done this, but you will sometimes see it done in solutions with multiple projects like GSD.App or GSD.Core
I was always that in a class called Customer.cs, you might not want to make the name field CustomeName but just Name as your already in the customer class so what is it adding. I suppose the same is true in your case of classes.
What if you want to reuse your classes elsewhere? I would say from the vast majority of code examples I come across and other peoples code I read, this isn’t common practice.
I suppose really it’s up to you and any team you work with, as long as it’s consistent.
I wonder what .net would look like if Microsoft prefixed everything!

Naming conflict in objective c framework [duplicate]

Objective-C has no namespaces; it's much like C, everything is within one global namespace. Common practice is to prefix classes with initials, e.g. if you are working at IBM, you could prefix them with "IBM"; if you work for Microsoft, you could use "MS"; and so on. Sometimes the initials refer to the project, e.g. Adium prefixes classes with "AI" (as there is no company behind it of that you could take the initials). Apple prefixes classes with NS and says this prefix is reserved for Apple only.
So far so well. But appending 2 to 4 letters to a class name in front is a very, very limited namespace. E.g. MS or AI could have an entirely different meanings (AI could be Artificial Intelligence for example) and some other developer might decide to use them and create an equally named class. Bang, namespace collision.
Okay, if this is a collision between one of your own classes and one of an external framework you are using, you can easily change the naming of your class, no big deal. But what if you use two external frameworks, both frameworks that you don't have the source to and that you can't change? Your application links with both of them and you get name conflicts. How would you go about solving these? What is the best way to work around them in such a way that you can still use both classes?
In C you can work around these by not linking directly to the library, instead you load the library at runtime, using dlopen(), then find the symbol you are looking for using dlsym() and assign it to a global symbol (that you can name any way you like) and then access it through this global symbol. E.g. if you have a conflict because some C library has a function named open(), you could define a variable named myOpen and have it point to the open() function of the library, thus when you want to use the system open(), you just use open() and when you want to use the other one, you access it via the myOpen identifier.
Is something similar possible in Objective-C and if not, is there any other clever, tricky solution you can use resolve namespace conflicts? Any ideas?
Update:
Just to clarify this: answers that suggest how to avoid namespace collisions in advance or how to create a better namespace are certainly welcome; however, I will not accept them as the answer since they don't solve my problem. I have two libraries and their class names collide. I can't change them; I don't have the source of either one. The collision is already there and tips on how it could have been avoided in advance won't help anymore. I can forward them to the developers of these frameworks and hope they choose a better namespace in the future, but for the time being I'm searching a solution to work with the frameworks right now within a single application. Any solutions to make this possible?
Prefixing your classes with a unique prefix is fundamentally the only option but there are several ways to make this less onerous and ugly. There is a long discussion of options here. My favorite is the #compatibility_alias Objective-C compiler directive (described here). You can use #compatibility_alias to "rename" a class, allowing you to name your class using FQDN or some such prefix:
#interface COM_WHATEVER_ClassName : NSObject
#end
#compatibility_alias ClassName COM_WHATEVER_ClassName
// now ClassName is an alias for COM_WHATEVER_ClassName
#implementation ClassName //OK
//blah
#end
ClassName *myClass; //OK
As part of a complete strategy, you could prefix all your classes with a unique prefix such as the FQDN and then create a header with all the #compatibility_alias (I would imagine you could auto-generate said header).
The downside of prefixing like this is that you have to enter the true class name (e.g. COM_WHATEVER_ClassName above) in anything that needs the class name from a string besides the compiler. Notably, #compatibility_alias is a compiler directive, not a runtime function so NSClassFromString(ClassName) will fail (return nil)--you'll have to use NSClassFromString(COM_WHATERVER_ClassName). You can use ibtool via build phase to modify class names in an Interface Builder nib/xib so that you don't have to write the full COM_WHATEVER_... in Interface Builder.
Final caveat: because this is a compiler directive (and an obscure one at that), it may not be portable across compilers. In particular, I don't know if it works with the Clang frontend from the LLVM project, though it should work with LLVM-GCC (LLVM using the GCC frontend).
If you do not need to use classes from both frameworks at the same time, and you are targeting platforms which support NSBundle unloading (OS X 10.4 or later, no GNUStep support), and performance really isn't an issue for you, I believe that you could load one framework every time you need to use a class from it, and then unload it and load the other one when you need to use the other framework.
My initial idea was to use NSBundle to load one of the frameworks, then copy or rename the classes inside that framework, and then load the other framework. There are two problems with this. First, I couldn't find a function to copy the data pointed to rename or copy a class, and any other classes in that first framework which reference the renamed class would now reference the class from the other framework.
You wouldn't need to copy or rename a class if there were a way to copy the data pointed to by an IMP. You could create a new class and then copy over ivars, methods, properties and categories. Much more work, but it is possible. However, you would still have a problem with the other classes in the framework referencing the wrong class.
EDIT: The fundamental difference between the C and Objective-C runtimes is, as I understand it, when libraries are loaded, the functions in those libraries contain pointers to any symbols they reference, whereas in Objective-C, they contain string representations of the names of thsoe symbols. Thus, in your example, you can use dlsym to get the symbol's address in memory and attach it to another symbol. The other code in the library still works because you're not changing the address of the original symbol. Objective-C uses a lookup table to map class names to addresses, and it's a 1-1 mapping, so you can't have two classes with the same name. Thus, to load both classes, one of them must have their name changed. However, when other classes need to access one of the classes with that name, they will ask the lookup table for its address, and the lookup table will never return the address of the renamed class given the original class's name.
Several people have already shared some tricky and clever code that might help solve the problem. Some of the suggestions may work, but all of them are less than ideal, and some of them are downright nasty to implement. (Sometimes ugly hacks are unavoidable, but I try to avoid them whenever I can.) From a practical standpoint, here are my suggestions.
In any case, inform the developers of both frameworks of the conflict, and make it clear that their failure to avoid and/or deal with it is causing you real business problems, which could translate into lost business revenue if unresolved. Emphasize that while resolving existing conflicts on a per-class basis is a less intrusive fix, changing their prefix entirely (or using one if they're not currently, and shame on them!) is the best way to ensure that they won't see the same problem again.
If the naming conflicts are limited to a reasonably small set of classes, see if you can work around just those classes, especially if one of the conflicting classes isn't being used by your code, directly or indirectly. If so, see whether the vendor will provide a custom version of the framework that doesn't include the conflicting classes. If not, be frank about the fact that their inflexibility is reducing your ROI from using their framework. Don't feel bad about being pushy within reason — the customer is always right. ;-)
If one framework is more "dispensable", you might consider replacing it with another framework (or combination of code), either third-party or homebrew. (The latter is the undesirable worst-case, since it will certainly incur additional business costs, both for development and maintenance.) If you do, inform the vendor of that framework exactly why you decided to not use their framework.
If both frameworks are deemed equally indispensable to your application, explore ways to factor out usage of one of them to one or more separate processes, perhaps communicating via DO as Louis Gerbarg suggested. Depending on the degree of communication, this may not be as bad as you might expect. Several programs (including QuickTime, I believe) use this approach to provide more granular security provided by using Seatbelt sandbox profiles in Leopard, such that only a specific subset of your code is permitted to perform critical or sensitive operations. Performance will be a tradeoff, but may be your only option
I'm guessing that licensing fees, terms, and durations may prevent instant action on any of these points. Hopefully you'll be able to resolve the conflict as soon as possible. Good luck!
This is gross, but you could use distributed objects in order to keep one of the classes only in a subordinate programs address and RPC to it. That will get messy if you are passing a ton of stuff back and forth (and may not be possible if both class are directly manipulating views, etc).
There are other potential solutions, but a lot of them depend on the exact situation. In particular, are you using the modern or legacy runtimes, are you fat or single architecture, 32 or 64 bit, what OS releases are you targeting, are you dynamically linking, statically linking, or do you have a choice, and is it potentially okay to do something that might require maintenance for new software updates.
If you are really desperate, what you could do is:
Not link against one of the libraries directly
Implement an alternate version of the objc runtime routines that changes the name at load time (checkout the objc4 project, what exactly you need to do depends on a number of the questions I asked above, but it should be possible no matter what the answers are).
Use something like mach_override to inject your new implementation
Load the new library using normal methods, it will go through the patched linker routine and get its className changed
The above is going to be pretty labor intensive, and if you need to implement it against multiple archs and different runtime versions it will be very unpleasant, but it can definitely be made to work.
Have you considered using the runtime functions (/usr/include/objc/runtime.h) to clone one of the conflicting classes to a non-colliding class, and then loading the colliding class framework? (this would require the colliding frameworks to be loaded at different times to work.)
You can inspect the classes ivars, methods (with names and implementation addresses) and names with the runtime, and create your own as well dynamically to have the same ivar layout, methods names/implementation addresses, and only differ by name (to avoid the collision)
Desperate situations call for desperate measures. Have you considered hacking the object code (or library file) of one of the libraries, changing the colliding symbol to an alternative name - of the same length but a different spelling (but, recommendation, the same length of name)? Inherently nasty.
It isn't clear if your code is directly calling the two functions with the same name but different implementations or whether the conflict is indirect (nor is it clear whether it makes any difference). However, there's at least an outside chance that renaming would work. It might be an idea, too, to minimize the difference in the spellings, so that if the symbols are in a sorted order in a table, the renaming doesn't move things out of order. Things like binary search get upset if the array they're searching isn't in sorted order as expected.
#compatibility_alias will be able to solve class namespace conflicts, e.g.
#compatibility_alias NewAliasClass OriginalClass;
However, this will not resolve any of the enums, typedefs, or protocol namespace collisions. Furthermore, it does not play well with #class forward decls of the original class. Since most frameworks will come with these non-class things like typedefs, you would likely not be able to fix the namespacing problem with just compatibility_alias.
I looked at a similar problem to yours, but I had access to source and was building the frameworks.
The best solution I found for this was using #compatibility_alias conditionally with #defines to support the enums/typedefs/protocols/etc. You can do this conditionally on the compile unit for the header in question to minimize risk of expanding stuff in the other colliding framework.
It seems that the issue is that you can't reference headers files from both systems in the same translation unit (source file). If you create objective-c wrappers around the libraries (making them more usable in the process), and only #include the headers for each library in the implementation of the wrapper classes, that would effectively separate name collisions.
I don't have enough experience with this in objective-c (just getting started), but I believe that is what I would do in C.
Prefixing the files is the simplest solution I am aware of.
Cocoadev has a namespace page which is a community effort to avoid namespace collisions.
Feel free to add your own to this list, I believe that is what it is for.
http://www.cocoadev.com/index.pl?ChooseYourOwnPrefix
If you have a collision, I would suggest you think hard about how you might refactor one of the frameworks out of your application. Having a collision suggests that the two are doing similar things as it is, and you likely could get around using an extra framework simply by refactoring your application. Not only would this solve your namespace problem, but it would make your code more robust, easier to maintain, and more efficient.
Over a more technical solution, if I were in your position this would be my choice.
If the collision is only at the static link level then you can choose which library is used to resolve symbols:
cc foo.o -ldog bar.o -lcat
If foo.o and bar.o both reference the symbol rat then libdog will resolve foo.o's rat and libcat will resolve bar.o's rat.
Just a thought.. not tested or proven and could be way of the mark but in have you considered writing an adapter for the class's you use from the simpler of the frameworks.. or at least their interfaces?
If you were to write a wrapper around the simpler of the frameworks (or the one who's interfaces you access the least) would it not be possible to compile that wrapper into a library. Given the library is precompiled and only its headers need be distributed, You'd be effectively hiding the underlying framework and would be free to combine it with the second framework with clashing.
I appreciate of course that there are likely to be times when you need to use class's from both frameworks at the same time however, you could provide factories for further class adapters of that framework. On the back of that point I guess you'd need a bit of refactoring to extract out the interfaces you are using from both frameworks which should provide a nice starting point for you to build your wrapper.
You could build upon the library as you and when you need further functionality from the wrapped library, and simply recompile when you it changes.
Again, in no way proven but felt like adding a perspective. hope it helps :)
If you have two frameworks that have the same function name, you could try dynamically loading the frameworks. It'll be inelegant, but possible. How to do it with Objective-C classes, I don't know. I'm guessing the NSBundle class will have methods that'll load a specific class.

write classes in ViewController

Having lots of experience in Java, i am new to ios and swift and looking for directions.
In java i use to create DataObjects (like Point,person etc...) every one in different class file (*.java)
public class GamePreferences
{
int gameId;
int developerId;
String orientation;
}
In Swift i see many examples where classes are being written inside the View Controller
Is it really how it should be done? or should i create different files for this purpose? if yes what is the file types suited for defining classes?
Writing every class in a different .swift file is better way.
I prefer to write many classes in the same file only if the class is ridiculously small or related only to one class that is the main class in the file.
The advantages of every class in a different files are,
Easier to navigate and improve readability
Great granularity when working with version controls.Wspecially those where you have a locking checkout mechanism for editing files
Easier for new developers to find the appropriate classes
how do i import them to classe for me to use?
in Swift, you don't need to import classes. Simply use it. Only you need to import your external modules (targets), if any.
I've seen people create enums and structures inside the UIViewConroller class but never entire classes inside this.
You definitely should create separate classes, hopefully in separate files. It's not a limitation of the system.
In most examples, you see classes in the same file as the ViewController because it's easier to scroll through.
In a real life context, it depends on your preferences and/or project norms.
I prefer to split it in different files but it's totally up to you.

Class Accessibility Throughout Project

When I first began working on a long iOS project, my first, I had need for a small class that was readily accessible throughout the project. At first I passed it around as a property and it became way too much of a headache.
So, even though I've seen posts here advising against it, I created that class in the AppDelegate and access it as needed through a pointer to the AppDelegate. Then, I would revisit it later.
So, it is now later, I'm approaching release of the project, and I want to deal with this issue. It works just fine as it is but if it is lousy practice I want to fix it before release.
I don't understand why it is lousy practice. Sometimes you just need a class that is readily available and these seems like as good a way as any to get it. But there could be some downside I'm not understanding.
Assuming I need this class instance (it is very lightweight but heavily used) to be accessible throughout the project (probably about 50 VCs, total), what would be a good alternative to just referencing it via the App Delegate?
TIA for comments. I hope it doesn't start a war.
There's no hard-fast rule for for this and hundreds of opinions to be had. Here's my take on it.
I don't understand why it is lousy practice. Sometimes you just need a class that is readily available and these seems like as good a way as any to get it. But there could be some downside I'm not understanding.
You're right to feel this way and yes sometimes you need a class readily available with your data. It's lousy because it is not how AppDelegate should be used. In an ideal world it shouldn't contain lots of unrelated state-data and should serve a singular purpose: delegating system calls to your app. The trick is where do you put your model so that everyone can have access to it?
Assuming I need this class instance (it is very lightweight but heavily used) to be accessible throughout the project (probably about 50 VCs, total), what would be a good alternative to just referencing it via the App Delegate?
Put your state in a class using the singleton pattern. It will ensure that only one copy of it is ever created and all your classes should be able to access it. This is a well accepted pattern in the iOS SDK (NSUserDefaults, UIApplication, etc..). Just beware of this class growing too large or doing too many things. Try your best to keep it simple and focused and the Object-Oriented Police will leave you alone.
Other resources and opinions worth considering:
http://www.cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html
Is it a bad practice to use your AppDelegate as your Singleton?
Is it good practice to use AppDelegate for data manipulation and Handling?

Resources