What is Loosely Coupled Code? - ruby-on-rails

I recently learned Ruby and Rails, I come across these terminologies, that I can't understand off the bat.
So Please explain, ( with analogies, if possible ) what is Loosely coupled Code.

A Lay Man's Explanation,
You have two classes, Class A and Class B that probably interact together. if they are loosely coupled, Class A would do what it is supposed to Do(what you want it to do) without knowing the details of Class B's Implementation
Hope it makes some Sense?

loose coupling basically means that you want the components of your program to connect easily with other components, this was you can enjoy code reuse and make things more efficient, e.g., there are Design Patters like MVC (Model View Controller) that help you with separation of concerns, you can have some of your code responsible for the GUI and some other code responsible for the access to a database, and if you want to change any of these parts you want them to avoid being too dependent on each other, i.e., that's why you should rely on interfaces instead of implementations, you want to make things easier because software is always changing/evolving.
Usually loose coupling is mentioned along with the concept of "High Cohesion", this one can be subjective but it's nothing more than writing code that makes sense and design your components in a way that will facilitate understanding, maintenance, extensibility etc.

Related

How evil is a UIViewController?

This is a somewhat open ended question about the UIViewController class, and their proper role in an iOS app.
I recently read this article, and I partially agree with the author. It's obviously important that every bit of logic related to your views and models doesn't end up getting dumped into the UIViewController, but it seems a bit extreme to build all of your views separately and use delegate methods to access the actions.
I'm curious about which design is most efficient in regards to the memory and performance of the app (clearly an important consideration when dealing with mobile apps)? As the author of the post pointed out, Apple doesn't seem to strongly advocate against putting logic in the UIViewController.
Ultimately, I'd like to know the right way of doing things. So the question is, should the views and any logic associated with it be completely separated out of the VC? Should I really be using delegates to communicate with the UIViewController?
A view controller is not evil by nature, although it's common for them to grow into monolithic messes because they are so convenient to extend.
…it seems a bit extreme to build all of your views separately and use delegate methods to access the actions.
Think of it as breaking up your program into smaller units, whatever that may be. Subclassing UIViews in every case isn't the best solution (as one example).
Each developer's tolerance is a bit different and it varies by program/case, but it's pretty easy to recognize and eliminate duplicate code, and to break your programs down into smaller units.
I think most classes:
should not exceed a few ivars (e.g. 2)
should not require more than 100 lines
should favor composition over inheritance. in many cases where you think you need inheritance, protocols may be used.
Of course, there will be exceptions.
I'm curious about which design is most efficient in regards to the memory and performance of the app (clearly an important consideration when dealing with mobile apps)?
It matters more that you will gain a lot by writing more reusable programs. Invest more time and effort into these reusable designs, reduce duplicate code, and focus on quality. Write performance and memory into your designs where it is a concern. Generally, this will result in a big win when compared to the dreaded freshly written, poorly tested, monolithic VCs.
Ultimately, I'd like to know the right way of doing things. So the question is, should the views and any logic associated with it be completely separated out of the VC? Should I really be using delegates to communicate with the UIViewController?
Oversimplification: No, you don't have to go that far if you eliminate redundant code, focus on reusability where applicable, and ensure your units/classes maintain low complexity. Absolutely, fix those problems before they grow into monolithic classes, regardless of whether they are VCs or another type.
I've also read this article a year ago, when I was looking for better iOS coding practices than what you see everywhere (dumping all kinds of crap in view controllers...). I agree with its points, although unfortunately it doesn't provide any kind of solution to the problem.
After a year of working on a fairly large iOS application, with complicated data model, remote services and highly nonlinear navigation, my experiences come down to these points:
Use view controllers for a single unit of user interaction, like prompting for login credentials etc. Basic validation (e.g. checking for empty fields, number formats etc.) takes place in the view controller, but if validation is part of your business logic, it should be put in your model.
I usually have a so-called controller object which orchestrates the UI flow, and connects it with the domain model. The controller receives user input from the view controllers via delegate mechanisms, so they're loosely coupled.
A single monolithic controller should be avoided; so I usually try to split my controller functionality between simpler, modular parts. For example, I have a controller which manages a registration process with a mostly linear UI flow, and its embedded in the main controller of the application so its

MV4 Application with EF5 model first, without ViewModels or Repositories

I'm building a MVC4 app, I've used EF5 model first, and kept it pretty simple. This isn't going to a huge application, there will only ever be 4 or 5 people on it at once and all users will be authenticated before being able to access any part of the application, it's very simply a place order - dispatcher sees order - dispatcher compeletes order sort of application.
Basically my question is do I need to be worrying about repositories and ViewModels if the size and scope of my application is so small. Any view that is strongly typed to a domain entity is using all of the properties within that entity. I'm using TryOrUpdateModel in my controllers and have read some things saying this can cause a lot of problems, but not a lot of information on exactly what those problems can be. I don't want to use an incredibly complicated pattern for a very simple app.
Hopefully I've given enough detail, if anyone wants to see my code just ask, I'm really at a roadblock here though, and could really use some advice from the community. Thanks so much!
ViewModels: Yes
I only see bad points when passing an EF Entities directly to a view:
You need to do manual whitelisting or blacklisting to prevent over-posting and mass assignment
It becomes very easy to accidentally lazy load extra data from your view, resulting in select N+1 problems
In my personal opinion, a model should closely resembly the information displayed on the view and in most cases (except for basic CRUD stuff), a view contains information from more than one Entity
Repositories: No
The Entity Framework DbContext already is an implementation of the Repository and Unit of Work patterns. If you want everything to be testable, just test against a separate database. If you want to make things loosely coupled, there are ways to do that with EF without using repositories too. To be honest, I really don't understand the popularity of custom repositories.
In my experience, the requirements on a software solution tend to evolve over time well beyond the initial requirement set.
By following architectural best practices now, you will be much better able to accommodate changes to the solution over its entire lifetime.
The Respository pattern and ViewModels are both powerful, and not very difficult or time consuming to implement. I would suggest using them even for small projects.
Yes, you still want to use a repository and view models. Both of these tools allow you to place code in one place instead of all over the place and will save you time. More than likely, it will save you copy paste errors too.
Moreover, having these tools in place will allow you to make expansions to the system easier in the future, instead of having to pour through all of the code which will have poor readability.
Separating your concerns will lead to less code overall, a more efficient system, and smaller controllers / code sections. View models and a repository are not heavily intrusive to implement. It is not like you are going to implement a controller factory or dependency injection.

DRY vs Security and Maintainability with MVC and View Models

I like to strive for DRY, and obviously it's not always possible. However, I have to scratch my head over a concept that seems pretty common in MVC, that of the "View Model".
The View Model is designed to only pass the minimum amount of information to the view, for both security, maintainability, and testing concerns. I get that. It makes sense.
However, from a DRY perspective, a View Model is simply duplicating data you already have. The View Model may be temporary, and used only as a DTO, but you're basically maintaing two different versions of the same model which seems to violate the DRY principal.
Do View Models violate DRY? Are they a necessary evil? Do they do more good than bad?
This has been brought up time and time again. Not only is it a pretty substantial dupe but the answer is subjective and argumentative. ViewModels are a response to DDD and the concept of persistence ignorance.
To say not using ViewModels is bad means ignoring that Django and Rails and most PHP ORM/MVC frameworks don't care at all about those concepts. Do you want somebody to tell you all those other languages and frameworks are "doing it wrong?".
Whether or not you want to use ViewModels is 100% dependent on what architecture styles you are going for and what the goals of the application are.
This is like asking is dragging and dropping GridViews in a WebForm app appropriate? Depends on a lot of things.
There is also a misconception about DRY that you have here. Do Proxy classes from a WCF service violate DRY? Does the ViewModel contain logic? The primary goal of DRY is to not have duplicated logic with a meaningful purpose. Do a couple of DTOs that share object shapres violate that?
The DDD principal of bounded contexts would make for a good read too. If a ShoppingCart object needs to function differently in a warehouse vs ecommerce website setting does that mean you to share the types? What happens when the only shared functionality is totaling a price ( price + tax + shipping )? Do you create a base class just for that therefore increasing coupling? What are the tradeoffs in time/cost/maintenance for being 100% DRY for a simple method like GetTotal(). Does violating DRY when it makes sense actually decreasing the complexity and overall cost of maintaining your codebase?
I'm sorry for answering with so many questions but hopefully now you can see the nuances and intricacies of the question you asked. ;)
One could also note that not using view models would be a violation of the single responsibility principle -- your entity should not be polluted with UI concerns.
I also think the real value of view models doesn't necessarily become apparent in version 1.0 of your application. You will thank yourself when working on version 2.0 when you completely re-think how your back-end works but you don't have to carry those changes out to the view layer.

Why does any kind of abstraction use interfaces instead of abstract classes?

Heyho,
There´s a question in my mind for some time now, which hopefully can be cleared quickly by some of you:
I am a big fan of MVC, ASP.Net Mvc in my case.
What I have noticed is the hype about interfaces. Every video, tutorial and book seems to solve any kind of abstraction with interfaces. I have adapted these patterns, understood why and how and I am basically very happy with it.
But I just don´t get why interfaces are used everywhere. I´ve almost never seen some abstraction being done with abstract base classes, which I don´t understand. Maybe I miss something? I know that you can only inherit from one base class while multiple interfaces are possible. But interfaces do have disadvantages, especially when some changes need to be done, which breaks your implementations.
In my projects so far, I only used to pick interfaces for completely different classes.
For example, the whole repository pattern could be done with an abstract base class, still providing testability and exchangeability, or did I miss something?
Please point me to the part where my brain laggs :)
Interfaces are used in tutorials, blogs and elsewhere because those authors are particularly influenced by a group of methodology called "design for testability".
Primarily, design for testability school of thoughts used interface every way because they want to be able to mock any component under tests. If you use concrete class, then a lot of mocking tools can't mock those class, and hence will make it difficult to test your code.
A Story
I once attended a Java user group
meeting where James Gosling (Java's
inventor) was the featured speaker.
During the memorable Q&A session,
someone asked him: "If you could do
Java over again, what would you
change?" "I'd leave out classes," he
replied. After the laughter died down,
he explained that the real problem
wasn't classes per se, but rather
implementation inheritance (the
extends relationship). Interface
inheritance (the implements
relationship) is preferable. You
should avoid implementation
inheritance whenever possible.
While using only or mostly Interfaces does have code reuse problems(as well as eliminating nice base classes), It makes it a lot easier to do Multiple Inheritance like things. As well as having widely different implementations that will work and where you don't have to worry about the base class changing or even what it does(you do have to implement the whole thing though so its a trade off).
P.S. I think the new Go language is based on interfaces rather then inheritance(looks sort of interesting).
If the language doesn't support multiple inheritance or mix-ins abstract base classes are limited in scope compared to interfaces. E.g. in .NET if you must inherit from some other type such as MarshalByRef, you can't use an abstract base class to implement a pattern. Interfaces do not impose this restriction.
Besides the fact you mentioned that you can inherit from a single base class only (which is pretty inconvenient if you want to use an existing class that already inherits from some class with the new framework base class), you also avoid the fragile base class problem if you use interfaces instead.
Coding against interfaces makes your design more flexible and extensible. For instance, plugin frameworks and dependency injection. Without interfaces, the extensibility of it is pretty much limited.
Read about interfaces, abstract classes, breaking changes, and MVC here: http://ayende.com/Blog/archive/2008/02/21/Re-Versioning-Issues-With-Abstract-Base-Classes-and-Interfaces.aspx.
One solution that is presented there (or somewhere else on Ayende's blog) is: do use interface but also provide abstract classes. Those who case about breaking changes can base their implementations on abstract classes. Those who need power of interfaces are also satisfied. But do make sure your methods accept interfaces, not abstract classes, as input.

Is there any hard data on the value of Inversion of Control or dependency injection?

I've read a lot about IoC and DI, but I'm not really convinced that you gain a lot by using them in most situations.
If you are writing code that needs pluggable components, then yes, I see the value. But if you are not, then I question whether changing a dependency from a class to an interface is really gaining you anything, other than more typing.
In some cases, I can see where IoC and DI help with mocking, but if you're not using Mocking, or TDD then what's the value? Is this a case of YAGNI?
I doubt you will have any hard data on it, so I will add some thoughts on it.
First, you don't use DI (or other SOLID principles) because it helps you do TDD. Its the other way around, you do TDD because it helps you with the design - which usually means you get code that follow those principles.
Discussing why to use interfaces is a different matter, see: https://stackoverflow.com/questions/667139/what-is-the-purpose-of-interfaces.
I will assume you agree that having your classes do many different things results in messy code. Thus, I am assuming you are already going for SRP.
Because you have different classes that do specific things, you need a way to relate them. If you relate them inside the classes (i.e. the constructors), you get plenty of code that uses specific versions of the classes. This means that making changes to the system will be hard.
You are going to need to change the system, that's a fact of software development. You can call YAGNI about not adding specific extra features, but not on that you won't be needing to change the system. In my case that's something really important as I do weekly sprints.
I use a DI framework where configuration is done through code. With a really small code configuration, you hook up lots of different relations. So, when you take away the discussion on interface vs. concrete classes, you are actually saving typing not the other way around. Also for the cases a concrete class is on the constructor, it hooks it up automatically (I don't have to configure) building the rest of the relations. It also allows me to control some objects life time, in particular I can configure an object to be a Singleton and it hands a single instance all the time.
Also note that just using these practices isn't more overhead. Using them for the first times, is what causes the overhead (because of the learning process + in some cases mind set change).
Bottom line: you ain't gonna need to put all those constructor calls all over the place to go faster.
The most significant gains from DI are not necessarily due to the use of interfaces. You do not actually need to use interfaces to have beneficial effects of dependency injection. If there's only one implementation you can probably inject that directly, and you can use a mix of classes and interfaces.
You're still getting loose coupling, and quite a few development environments you can introduce that interface with a few keypresses if needed.
Hard data on the value of loose coupling I cannot give, but it's been a vision in textbooks for as long as I can remember. Now it's real.
DI frameworks also give you some quite amazing features when it comes to hierarchical construction of large structures. Instead of looking for the leanest DI framework around, I'd recommend you look for a full-featured one. Less isn't always more, at least when it comes to learning about new ways of programming. Then you can go for less.
Apart from testing also the loose coupling is worth it.
I've worked on components for an embedded Java system, which had a fixed configuration of objects after startup (about 50 mostly different objects).
The first component was legacy code without dependency injection, and the subobjects where created all over the place. Now it happened several times that for some modification some code needed to talk to an object which was only available three constructors away. So what can you do but add another parameter to the constructor and pass it through, or even store it in a field to pass it on later. In the long run things became even more tangled than they already where.
The second component I developed from scratch, and used dependency injection (without knowing it at the time). That is, I had one factory which constructed all objects and injected then on a need to know basis. Adding another dependency was easy, just add it to the factory and the objects constructor (or add a setter to avoid loops). No unrelated code needed to be touched.

Resources