How to write good base classes for iOS projects? [closed] - ios

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been developed apps for iOS for sometime and find that there are many repeating tasks. So I want to write base classes that the upcoming projects will subclass, so that it will cost less time and more easily to track code across projects. The most concerned are
Write good base model class that has many strategies (Core Data, Archiving, ...). This model class also has some JSON-to-property converting techniques like Mantle so that model on device and on server are the same
Write good base networking class (mostly with AFNetworking)
Write good base ViewController class. I see some repetitive tasks : avoiding keyboard with ScrollView, logging, crash tracking, loading views from Nibs, ...
Find and use some other good categories for UIView, UINib, Autolayout, ...
These are just my concerns. It may seems a vague topic and I don't ask for how to use libraries or how to make reusable components.
I just want to ask about experience for making these kinds of base classes and where I can learn from

You are not the only one that has a problem with this, I've been going through same problem with many of the projects. So the best solution to this problem is the open source libraries. The good ones are usually updated often and keep up with Apple's SDK releases. I will explain what I use to keep boilerplate code at a minimum.
Base model - Since I only use Network and Core Data models, I use MagicalRecord for Core Data and JSONModel for network based models (that map to API responses).
Networking classes - are coupled with AFNetworking and previously mentioned JSONModel, I did not find to need anything else. I can easily extend those with categories.
There are many libraries to avoid UITextField's with keyboard in a UIScrollView, but mostly I just use custom code. But if I need one, I follow TPKeyboardAvoiding. For crash tracking I just use Crashlytics or Flurry, they provide their own SDK, so I do not need much code. And I do not use NIB's anymore.
There are many useful categories around on the web. I created my own repository as a CocoaPod, which keeps all useful categories in a single pod. I keep the repository up to date and add new categories and small classes when I need them. The down side of it is that you usually do not need all of them, so sometimes too much code is loaded. But until now I did not notice any performance downsides. If you want, you can take a look on GitHub, how it looks.
Do not forget about project initialization, I've been working on my own custom Xcode project templates to solve this problem.

Related

In which situation good reason to use RxSwift & RxCocoa? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
A few days ago I have begun to learn RxSwift and but the more I write code and can't understand which cases need to use reactive programming, I am can write the same code without RxSwift and use NotificaitionCenter, delegate pattern, Grand Central Dispatch, Closures.
I understand that RxSwif and RxCocoa give next opportunity:
There are some different ways to pass information from one object to
another in iOS reactively (Notification, pass in closure, delegate,
KVO, & target/action,) each of these different systems may be simple
by itself but most of the complexity in the logic of an iOS app is in
having to convert from one of these systems to another.
RxSwift/RxCocoa replaces virtually all of these systems with one which
is in a Rx way.
But when I am trying to write code on Rx I saw that this code not easy to understand.
Maybe someone can give examples of when need to use Rx inside the application or maybe in most cases doesn't need to use Rx because code will be complicated to understand, I am enjoyed from knowledge about Rx but not fully understand the good situation when need use it.
Since you are quoting me in your question, I guess I should provide an answer...
The classic example is search... Write a view controller that allows the user to enter text, then makes a network request, then decodes the result into an array of strings, then shows the result in a table view.
In order to do it without Rx, you need to coordinate three methods from two delegates, two closures, and two state variables. Importantly, no where in the code will you see anything that looks even remotely like the sentence above.
This feature implemented using Rx would be a straight line of code going from the search text field to the network request to the decoder to the table view. Just like the requirement description.
So it's not just a matter of needing less code. It's a matter of no longer needing to coordinate desperate kinds of communication systems. It's a matter of having a single chunk of code (or at least fewer chunks of code) to represent a feature.
Well it's a tool like any other. Some people use it because you end up writing less code than you would otherwise. It does have a steep learning curve, but it can be valuable if a project requires it (the project already uses it, and the people involved want to continue using it).
I worked for company that had an RxSwift project. All the architecture was built around RxSwift and all the code had to be written using RxSwift. The code was less complex than it would've been without using RxSwift. The major issue was that it was hard to onboard new developers on the project because as I said before the learning curve for Rx is pretty steep. In the end, for that reason, they decided to start moving away from Rx to a more classical approach.
I also worked for companies that completely reject RxSwift because they don't want another 3rd party dependency in their app.
So at the end of the day it's just a matter of preference. Personally I do see the benefits and conciseness of Rx, but prefer to use as little 3rd party dependencies as possible.
To really get the benefits of Rx you'd have to use it intensely in a project and build your architecture around it. Unlike other 3rd party libraries you can't just put a wrapper around RxSwift in case it goes away and you decide to replace it with something else. But then again Rx is such wide-spread on all platforms and programming languages that I don't think it's going away any time soon.
So long story short, use it and see if you like or not. And if not, at least it's good to know it if you happen to start working on someone else's project that uses it.

How do i break Objective-C (iOS app) code into an object oriented design [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm starting a massive project for the first time. I was supposed to be one of the developers on this big project, and all of a sudden, the lead developer and his team backed out of the contract. Now I'm left managing this big project myself with a few junior developers under me and I'm trying to get a firm grasp on how this code should be broken up.
Logically, to me, the code should be broken up by the screens it has. I know that might not be how it SHOULD be done. so tell me, how SHOULD it be done? The app has about 6 screens total. It connects to a server, which maintains data about all other instances of the app on other phones. You could think of it as semi-social. it will also use the camera feature in certain parts, and it will definitely use geolocation. probably geofencing. It will obviously need an API to connect to the server. most likely more APIs than just the 1. I cant say much more about it without breaking an NDA.
So again, my question pertains to how the code should be broken up to make it as efficient as possible. Personally, i'll be doing little coding on the project. probably mostly code reviews, unit testing and planning. Should it have 1 file per screen, and parts that are repeated should have their own classes? should it be MVC? We're talking a 30k line app here, at its best and most efficient. is there a better way to break the code apart than the ways I've listed?
I guess my real question is, does anybody have good suggestions for books that would address my current issue? code clean was suggested, that's a good start. I've already read the mythical man month and code complete but they don't really address my current issue. i need suggestions for books that will help me learn how to structure and plan the creation of large code bases
As I'm sure you know this is a pretty vague question you could write a book answering it. In fact, I would recommend you read one, like Clean Code. But I'll take a stab at a 10,000 foot level overview.
First if you are doing an iPhone app, you will want to use MVC because that is how Apple has setup their frame work. That means each screen will have (at least) a view-controller, possibly a custom view or NIB.
In addition you will want your view controllers pointing to your model (your business objects) and not the other way around. These objects should implement the use cases without any user interface logic. That is what your view-controller and view will be doing.
How do you break apart your use cases? Well, that's highly specific to your program and I won't be able to tell you with a (lot of) details. There isn't a single right answer. But in general you want to isolate each object from other objects as much as possible. If ever object reference ever other object, then you don't really have an OO design, you have a mess. Especially when you are talking about unit tests and TDD. If when you test one part you end up pulling in the whole system, then you are not testing just one small unit, are you?
Really though, get a good book about OO design. It's a large subject that nobody will be able to explain in a SO answer. I think Clean Code is a good start, maybe other people will have other suggestions?

MVC Areas for enterprise - good or bad? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Within a single project solution introducing Areas when you have a lot of controllers does improve separation and allows modules to easily be copied in or out of the solution. However in a large enterprise solution I would favour splitting the logic into separate projects instead.
Thus having separate UI, Controller, SOA, Model and Repository projects. In this scenario Areas don't make sense any more, plus they add an extra top level to the Url which is often not needed, although I believe you can omit the area in the Url if you keep your controllers unique, but isn't that a bit smelly?
Perhaps Areas are good for medium complexity sites or when module code is better kept in one location so it can be copied to other sites or removed.
I'm not sure if that's the right question. Areas can be overkill for small projects, but it's hard to imagine a non-trivially large project not using areas to help keep classes organized.
I use MVC Areas for the enterprise and love several things about it:
Typically people are working on a feature within a given domain (e.g., Search, Checkout, etc). If the area names correspond with your business domains, MVC Areas help reduce the time it takes to implement a feature, because the related classes are easy to find.
MVC routing gives you a ton of flexibility over how how structure the URLs. I used to use the Action Controller "pattern" but for non-public facing URLs I've just fully embraced the Area default route to make things easy.
Areas give you the distinct advantage of styling and, more importantly, encapsulating behavior at a site-section level. Each area gets its own web config where you can control the base view page or add managed handlers.
You're absolutely right that services should be in separate projects / solutions altogether, that abstract the data access via repositories, in an environment where multiple clients can access common business functionality.
But MVC Areas are great at providing some order to the UI / routing chaos as a web project grows, which, to me, is invaluable, regardless of context.
First, before I answer note that this is just my opinion and it's mainly about models.
The way I see it, areas can be just so evil.. If you have many areas your solution explorer becomes a maze, and it can get so hard to find something.
I suggest creating a new library project inside your solution, and put the logic in there.
The best benefit (and it's not that you can find what you're looking for much easier) is that your application becomes much more modular. If you create a library and specify a reference for it in your ASP.NET MVC application, you can't easily make a mistake and involve UI in the logic.

Constructor Injection: How many dependencies is too many? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've been using manual constructor injection DI for a little bit now. One thing that I notice is that my constructors are starting to get rather long.
I have a class that depends on a bunch of little objects - anywhere between 6 and 10 sometimes. As I continue to break my application into smaller chunks, I could see this number increasing over time. Is this a common problem?
Obviously this is going to depend a great deal on the project. However, the basic question is this:
When do you start to get uncomfortable with the number of dependencies that a class has? What are some strategies that you use to reduce these dependencies?
I would not worry about it.
Instead, I would worry about the class being too complex.
A class with many dependencies that uses them all but has no loops or if statements is fine. In some code I was working on recently there were around 14 dependencies in a class. However, there was only one path through the code and no logical way to group the dependencies into better classes.
A class with a small number of dependencies that contains many branch statements or complex loop conditions should be simplified.
This may be a sign that the class with the 6-10 dependencies itself needs to be refactored.
I would think no more than three or four. If you are getting more than that, I would start thinking about how well you are abstracting your concerns. A single repository object, for example, should fulfill all of your data retrieval needs within the class in question.
Runcible,
Here is a link to the Castle Windsor project. It is an Inversion of Control container. These containers allow factory classes to collect your dependencies together and inject them as a single object into your constructor.
http://www.castleproject.org/container/index.html
I have heard good things about Windsor. Spring also makes an IoC container, and there are others.
A class with 6-10 dependencies is a code smell. It is an indication that the class is probably violating the Single Responsibility Principle.
What are some strategies that you use to reduce these dependencies?
Mark Seemann has made that task clear in his post Refactoring to Aggregate Services and moreso in his book Dependency Injection in .NET. The fact your class has so many dependencies indicates there are more than one responsibilities within the class. Often there is an implicit domain concept waiting to be made explicit by identifying it and making it into its own service. Generally speaking, most classes should never need more than 4-5 dependencies.
You may also want to see if any of the parameters to your constructor should be combined into a single class as well (assuming that the parameters make sense as a class).
It might also be that you want to look at using the ServiceLocator pattern for some of your dependencies. This is particularly true if you're having to pass the dependencies down a long chain of constructors.

How do you make code reusable? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 2 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Any code can be reused in a way or an other, at least if you modify the code. Random code is not very reusable as such. When I read some books, they usually say that you should explicitly make the code reusable by taking into account other situations of code usage too. But certain code should not be an omnipotent all doing class either.
I would like to have reusable code that I don't have to change later. How do you make code reusable? What are the requirements for code being reusable? What are the things that reusable code should definitely have and what things are optional?
See 10 tips on writing reusable code for some help.
Keep the code DRY. Dry means "Don't Repeat Yourself".
Make a class/method do just one thing.
Write unit tests for your classes AND make it easy to test classes.
Remove the business logic or main code away from any framework code
Try to think more abstractly and use Interfaces and Abstract classes.
Code for extension. Write code that can easily be extended in the future.
Don't write code that isn't needed.
Try to reduce coupling.
Be more Modular
Write code like your code is an External API
If you take the Test-Driven Development approach, then your code only becomes re-usable as your refactor based on forthcoming scenarios.
Personally I find constantly refactoring produces cleaner code than trying to second-guess what scenarios I need to code a particular class for.
More than anything else, maintainability makes code reusable.
Reusability is rarely a worthwhile goal in itself. Rather, it is a by-product of writing code that is well structured, easily maintainable and useful.
If you set out to make reusable code, you often find yourself trying to take into account requirements for behaviour that might be required in future projects. No matter how good you become at this, you'll find that you get these future-proofing requirements wrong.
On the other hand, if you start with the bare requirements of the current project, you will find that your code can be clean and tight and elegant. When you're working on another project that needs similar functionality, you will naturally adapt your original code.
I suggest looking at the best-practices for your chosen programming language / paradigm (eg. Patterns and SOLID for Java / C# types), the Lean / Agile programming literature, and (of course) the book "Code Complete". Understanding the advantages and disadvantages of these approaches will improve your coding practice no end. All your code will then become reausable - but 'by accident', rather than by design.
Also, see here: Writing Maintainable Code
You'll write various modules (parts) when writing a relatively big project. Reusable code in practice means you'll have create libraries that other projects needing that same functionality can use.
So, you have to identify modules that can be reused, for that
Identify the core competence of each module. For instance, if your project has to compress files, you'll have a module that will handle file compression. Do NOT make it do more than ONE THING. One thing only.
Write a library (or class) that will handle file compression, without needing anything more than the file to be compressed, the output and the compression format. This will decouple the module from the rest of the project, enabling it to be (re)used in a different setting.
You don't have to get it perfect the first time, when you actually reuse the library you will probably find out flaws in the design (for instance, you didn't make it modular enough to be able to add new compression formats easily) and you can fix them the second time around and improve the reusability of your module. The more you reuse it (and fix the flaws), the easier it'll become to reuse.
The most important thing to consider is decoupling, if you write tightly coupled code reusability is the first casualty.
Leave all the needed state or context outside the library. Add methods to specify the state to the library.
For most definitions of "reuse", reuse of code is a myth, at least in my experience. Can you tell I have some scars from this? :-)
By reuse, I don't mean taking existing source files and beating them into submission until a new component or service falls out. I mean taking a specific component or service and reusing it without alteration.
I think the first step is to get yourself into a mindset that it's going to take at least 3 iterations to create a reusable component. Why 3? Because the first time you try to reuse a component, you always discover something that it can't handle. So then you have to change it. This happens a couple of times, until finally you have a component that at least appears to be reusable.
The other approach is to do an expensive forward-looking design. But then the cost is all up-front, and the benefits (may) appear some time down the road. If your boss insists that the current project schedule always dominates, then this approach won't work.
Object-orientation allows you to refactor code into superclasses. This is perhaps the easiest, cheapest and most effective kind of reuse. Ordinary class inheritance doesn't require a lot of thinking about "other situations"; you don't have to build "omnipotent" code.
Beyond simple inheritance, reuse is something you find more than you invent. You find reuse situations when you want to reuse one of your own packages to solve a slightly different problem. When you want to reuse a package that doesn't precisely fit the new situation, you have two choices.
Copy it and fix it. You now have to nearly similar packages -- a costly mistake.
Make the original package reusable in two situations.
Just do that for reuse. Nothing more. Too much thinking about "potential" reuse and undefined "other situations" can become a waste of time.
Others have mentioned these tactics, but here they are formally. These three will get you very far:
Adhere to the Single Responsibility
Principle - it ensures your class only "does one thing", which means it's more likely it will be reusable for another application which includes that same thing.
Adhere to the Liskov
Substitution Principle - it ensures your code "does what it's supposed without surprises", which means it's more likely it will be reusable for another application that needs the same thing done.
Adhere to the Open/Closed Principle - it ensures your code can be made to behave differently without modifying its source, which means it's more likely to be reusable without direct modification.
To add to the above mentioned items, I'd say:
Make those functions generic which you need to reuse
Use configuration files and make the code use the properties defined in files/db
Clearly factor your code into such functions/classes that those provide independent functionality and can be used in different scenarios and define those scenarios using the config files
I would add the concept of "Class composition over class inheritance" (which is derived from other answers here).
That way the "composed" object doesn't care about the internal structure of the object it depends on - only its behavior, which leads to better encapsulation and easier maintainability (testing, less details to care about).
In languages such as C# and Java it is often crucial since there is no multiple inheritance so it helps avoiding inheritance graph hell u might have.
As mentioned, modular code is more reusable than non-modular code.
One way to help towards modular code is to use encapsulation, see encapsulation theory here:
http://www.edmundkirwan.com/
Ed.
Avoid reinventing the wheel. That's it. And that by itself has many benefits mentioned above. If you do need to change something, then you just create another piece of code, another class, another constant, library, etc... it helps you and the rest of the developers working in the same application.
Comment, in detail, everything that seems like it might be confusing when you come back to the code next time. Excessively verbose comments can be slightly annoying, but they're far better than sparse comments, and can save hours of trying to figure out WTF you were doing last time.

Resources