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

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!

Related

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?

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

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.

iOS - Abbreviating XXXViewController to XXXVC bad or ok?

Since every view controller ends with "ViewController" would it be evil to simply abbreviate it as "VC"? I know the Apple Docs say not to abbreviate things and make the names meaningful but isn't this something that's just obvious what it is? I find it lengthy and verbose to type ViewController after every single one. Also, xcode 4 automatically names the nib file the same as the header and class files. Do you remove the "Controller" part of it?
What are your naming conventions and why did you choose to do it that way?
Thanks
If you're using Xcode, you shouldn't have to type the full name every time. Auto-complete handles that for you.
In general, avoiding abbreviation makes your code more readable and easier to maintain. Sure you know what VC means, but someone else 3 years from now might not understand what you were doing.
In this specific case, it may not make tons of sense, but naming conventions are conventions. We follow them in most cases to make our lives (and others) easier in the future.
Always imagine that the person who will eventually maintain your code is a big mean guy with a hair-trigger temper who knows where you live.
Despite what people seem to say Apple has excellent documentation. They have even gone so far as to provide a Coding Guidelines document.
This not only provides some good examples for you to use, but also helps to understand the way name, conventions and abbreviations are used in the Frameworks.

Things you look for when trying to understand new software

I wonder what sort of things you look for when you start working on an existing, but new to you, system? Let's say that the system is quite big (whatever it means to you).
Some of the things that were identified are:
Where is a particular subroutine or procedure invoked?
What are the arguments, results and predicates of a particular function?
How does the flow of control reach a particular location?
Where is a particular variable set, used or queried?
Where is a particular variable declared?
Where is a particular data object accessed, i.e. created, read, updated or deleted?
What are the inputs and outputs of a particular module?
But if you look for something more specific or any of the above questions is particularly important to you please share it with us :)
I'm particularly interested in something that could be extracted in dynamic analysis/execution.
I like to use a "use case" approach:
First, I ask myself "what's this software's purpose?": I try to identify how users are going to interact with the application;
Once I have some "use case", I try to understand what are the objects that are more involved and how they interact with other objects.
Once I did this, I draw a UML-type diagram that describe what I've just learned for further reference. What happens after depends on the task I've been assigned, i.e. modify the code, document the code etc.
There is the question of what motivation do I have for learning the new system:
Bug fix/minor enhancement - In this case, I may focus solely on that portion of the system that performs a specific function that needs to be altered. This is a way to break down a huge system but also is a way to identify if the issue is something I can fix or if it is something that I have to hand to the off-the-shelf company whose software we are using,e.g. a CRM, CMS, or ERP system can be a customized off-the-shelf system so there are many pieces to it.
Project work - This would be the other case and is where I'd probably try to build myself a view from 30,000 feet or so to know what are the high-level components and which areas of the system does the project impact. An example of this is where I'd join a company and work off of an existing code base but I don't have the luxury of having the small focus like in the previous case. Part of that view is to look for any patterns in the code in terms of naming conventions, project structure, etc. as this may be useful once I start changing some code in the system. I'd probably do some tracing through the system and try to see where are the uglier parts of the code. By uglier I mean those parts that are kludge-like and may have some spaghetti code as this was rushed when first written and is now being reworked heavily.
To my mind another way to view this is the question of whether I'm going to be spending days or weeks wrapping my head around a system like in the second case or should this be a case where it hopefully takes only a few hours, optimistically that is, to get my footing to make the necessary changes.

Programming for and by yourself

If you're writing something by yourself, whether to practice, solve a personal problem, or just for entertainment, is it ok, once in a while, to have a public field? Maybe?
Let me give you an analogy.
I come from a part of the world where English is not the primary language. But it’s necessary for all things in life.
During one of those usual days during my pre-teen years I said something very funny in English. Then my Dad said, “Son, think in English. Then you’ll get fluent”
I think it applies perfectly to this situation.
Think,try and question best practices in your playground. You will soon realize what’s best for what.Why are properties needed in the first place. Why should this be public? Why should I not call a virtual member from the constructor? Let me try using "new" modifier for a method call. What happens when I write 10 nested levels of if-then-else and try reading it again after 10 days. Why the heck should I use a factory pattern for a simple project. Et cetera.
And then you’ll realize without shooting at your foot, why design patterns are patterns...
I think it's reasonable if you're consciously throwing the code away afterwards. In particular, if you're experimenting with something completely different, taking shortcuts makes sense. Just don't let it lead to habits which cross over into "real" code.
Violating general principles is always "ok"! It is not an error to violate a principle but it is a trade off. The cost of not writing clean code will be higher the longer your software will survive. My take on this is: If in doubt make it clean!
Of course it's OK. It's your code, you can do whatever you want with it. Personally, I try to stick to good practice also in my private code, just to make it a natural habit so I don't have to think about it.
The short answer is yes, if you believe that you're gaining a lot by making things public instead of private with accessors you are welcome to do so. Consistency, I think, is the biggest thing to keep in mind. For instance, don't make some variables straight public, and some not. Do the same across the board if you break with best practices. It comes back to a trade-off. Almost no-one follows many of the IEEE specs for how Software Engineering should be executed and documented because the overhead is far too great, and it can get unmanageable. The same is true for personal, light-weight programming. It's okay to do something quick and dirty, just do not get used to it.
Public members are acceptable in the Data Transfer Object design patter:
Typically, the members in the Transfer Object are defined as public, thus eliminating the need for get and set methods.
One of the key advantages of OOP is for scaling and maintainability. By encapsulating code, one can hide the implementation. This means other programmers don't have to know the implementation, and can't change your object's internal state. If you language doesn't support properties, you end up with a lot of code which obfuscates and bloats your project. If the code doesn't need to be worked on by multiple programmers, you aren't producing a reusable component, and YOU are the maintenance programmer, then code in whatever manner allows you to get things done.
Does a maid need to make his/her own bed in the morning in order to practice properly making a bed?
Side note: it also depends on the language:
In Scala, according to the Uniform Access Principle, clients read and write field values as if they are publicly accessible, even though in some case they are actually calling methods. The maintainer of the class has the freedom to change the implementation without forcing users to make code changes.
Scala keeps field and method names in the same namespace.
Many languages, like Java, keep field and method names in separate namespaces.
However, these languages can’t support the uniform access principle as a result, unless they build in ad hoc support in their grammars or compilers.
So the real question is:
What service are you exposing (here by having a public field)?.
If the service (get/set a given type value) makes sense for your API, then the "shortcut" is legitimate.
As long as you encapsulate that field eventually, is it ok because you made the shortcut for the "right" reason (API and service exposure), versus the "wrong" reason (quick ad-hoc access).
A good unit test (thinking like the user of your API) can help you check if that field should be accessed directly or if it is only useful for internal development of other classes within your program.
Here's my take on it:
I'd advise avoiding public fields. They have a nasty habit of biting you later on because you can't control them. (The word you're looking for here is volatility.) Further, if you decide to change their internal implementation, you have to touch a lot more code.
Then again, that's what refactoring tools are for. If you have a decent refactoring tool, that's not nearly so difficult.
There is no silver bullet. I can't repeat this enough. If you have work to do, and you need to get it done in a hurry, writing one line of code instead of eight (as is the case in Visual Basic) is certainly faster.
Rules were meant to be broken. If a rule doesn't necessarily apply in your case, don't use it. Design patterns, coding guidelines, laws and best practices should not be treated as a straightjacket that requires you to needlessly complicate your code to the point where it is enormously complex and difficult to understand and maintain. Don't let someone force you into a practice just because it's popular or "standard" when it doesn't fit your requirements.
Again, this is a subjective opinion, and your mileage may vary.

Resources