How to solve this Go cyclical dependency - go

I've been learning Go for a class course and I am very excited with the language, it really is very useful for web services.
So, I've been writing this CRUD restful API for a final project and I keep running in the damn circular dependency problem. I've already researched and read on the ways of solving it and will post here just for the sake of it, but first the problem I am having:
routes need to know about the handler functions in the handlers package, which in turn need to know about the user structure inside the model package, which in order to send a registration e-mail with a link need to know about the routes path
Classical A -> B -> C -> A
Now, I am trying to write this API using MVC and three layer architecture, this I would love for my routes to be in a controller package, my handlers to be on a business logic package and my user on a model package. This is also needed because I have over 43 model classes, I need them tidy up and tucked away on their package.
Ok, the solutions I found out
1 - Throw everybody on the same package : That's what I've been doing so far but is a very horrible solution for obvious reasons.
2- Pass whatever user needs as argument when it's functions are called: That would be a good solution, but won't work because the function that is being called from user is from an interface implementation because it has to be a generic call and before anyone goes around saying that my problem is because I am forcing generics in go, well too bad, I need that generic, I will not write over 160 crud functions. The whole point of functions is to avoid code repetition.
3- Create another package, with another interface, and have it having a instance of handlers and user and have it pass arguments from one to the other: Despite the reason mentioned above, the need of generic, this sounds like an unnecessarily complicated solution, I refuse to believe that this is better design than circular dependencies.
Bottom line question: How to solve this dependency when C needs to know information from A and generics must be respected
I can post some code here if you need to but I don't see the relevance of specific code when this is more of a high level question.
EDIT: Solved my dependency problem. Thank you all for the comments and answer as it led me to the answer. I don't think I've implemented any of the solutions suggested but it did taught me a lot about how to solve the problem, and they would all be very acceptable and doable solution if it wasn't for my own constrains where I don't want to pass anything to User.
To anyone trying to solve their own dependency problem, what I was able to gather is, instead of making in my case, C ask something from A, give to C whatever it needs, before it has to ask, meaning pass the information to him.
Alas, that was not my solution, what I did was remove the information from A and give the information to Z, now both A and C are asking the path information to Z, which is just a Map, sitting there being all map like and holding information.
Thank you all

You've got some options, and you've found some of them. The main ways of handling this are:
Refactor your design to turn the cycle into a tree. This doesn't really apply to your situation due to your requirements.
Refactor your design to use some kind of dependency injection (this is your 2nd option in your question). This is perfectly viable, and probably the cleanest and easiest.
Refactor your design to take a locally declared interface. This is a more Go-idiomatic version of your option 3. Because interfaces in Go are duck-typed, you get to define it where it's consumed, rather than where it's implemented. So your user package can define a one-method interface for "a thing that gives me a URL I need" and it never needs to reference the package that implements the interface.

Related

Multiple Controllers appropriate with one entity in spring framework

I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer.
So, I would like to know.Is it appropriate to declare the controllers like this.
Thank
The answer to this question is subjective and maybe more a topic for https://softwareengineering.stackexchange.com/. However, there is something very spring related about it that I would like to comment.
There are a few principles that attempt at guiding developers of how to strike a good balance when thinking about designing the classes. One of those is the Single responsibility principle.
In object-oriented programming, the single responsibility principle
states that every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class. All its
services should be narrowly aligned with that responsibility
A catchier explanation is
A class or module should have one, and only one, reason to change.
However, its still often hard to reason about it properly.
Nevertheless, Spring gives you means for it (think of this statement as a poetic freedom of interpretation). Embrace constructor based dependency injection. There are quite a few reasons why you should consider constructor based dependency injection, but the part relevent to your question is adressed in the quote from the blog
An often faced argument I get is: “Constructors just get too verbose
if I have 6 or 7 dependencies. With fields only, this is fine”.
Awesome, you’ve effectively worked around a clear indicator that the
code you write is doing way too much. An increase in the number of
dependencies a type has should hurt, as it makes you think about
whether you should split up the component into multiple ones.
In other words, if you stick to constructor based injection, and your constructor turns a bit ugly, the class is most likely doing too much and you should consider redesigning.
The same works the other way around, if your operations are a part of the logical whole (like CRUD operations), and they use the same dependencies (now "measurable" by the count and the type of the injected deps) with no clear ideas of what can cause the operations to evolve independently of each other, than no reason to split to separate classes/components.
It should be better if you define one controller for Customer class and in that class you should have all methods related to customer operations (edit,delete,create and read).

laravel 4 api documentation - how to quickly find functions?

I am having trouble in using documentation. Lets say I want to see the source of function
DB::transaction();
I go to http://laravel.com/api/index.html
and enter in the search form 'transaction'
Nothing is found.
I then try to go on the left to Namespaces/Database which makes sense.
And later I have no idea where to go. There is some namespaces, some classes, some interfaces. Later found out that this is in the connection class, which at first I did not even look at. Connection associates to connecting to the database, not making transaction.
And there often happens when I don't know how to quickly find things.
How do you deal with that?
I assume the documentation should be one of best developers friends, but I guess I found this function by using sublime massive search in all files.
Btw also - I lowed the Codeigniter documentation, so thats why also I am disapointed. In codeigniter everythign looked so simple and search worked very well. Typing same word 'transaction' finds like charm.
Ok, tried same way as CI does to serch:
transaction site:http://laravel.com/api/
then it finds. If there is no other way, maybe I should bookmark the search link and just change the keyword or something like that.
CodeIgniter was definitely simpler, to the point that any larger project suffered greatly under the weight of (forcibly) badly misplaced code. Laravel raises the bar there a little bit, but it's to your benefit as a developer (I promise :D ).
Firstly, kudos for searching through the code. Many people do not. You learn a LOT by looking in there.
Laravel Code
For Laravel, you'll do best by knowing about Namespaces, and how they relate to autoloading files (Namespaces will relate to directories, essentially). You likely know this, but it relates to how you can find classes and their methods.
Now, this doesn't go towards knowing where anything is - that comes with some digging into the code yourself. I almost always have Github open to the laravel/framework repository to look at code.
Note: That API search looks for files, rather than methods within them (unfortunately).
Github
As mentioned, I use Github mercilessly for searching code, instead of the API documentation. The search in Github is quite good - it will search within the current repository.
For example, I searched "function transaction" in github and got good results.
It led me to see here that it accepts a closure, and surrounds the code run within the closure around a transaction. You can see that throwing any exception within that closure will get caught and cancel the transaction (and gives you a way to control it).
Facades
As #matit pointed out, Facades do in fact hide where code is. That's a tricky part. In general, you can call the getFacadeRoot() method on any facade to figure out what class it is:
// Figure out what underlying class the Auth facade actually is
echo get_class( Auth::getFacadeRoot() );
Eventually you'll discover patterns in the code. Most facades point towards certain types of classes within each package (For instance, a Manager class who's job it is to decide which underlying implementation is used).
I really suggest reading Taylor's book which goes into the general architecture of Laravel. It's a quick read which is highly worth it.
Where CodeIgniter excelled in simplicity, Laravel excels in teaching you better coding concepts. Give it some time :D (Or use CodeIgniter still, that's cool too - whatever gets your work done!)
This is why I strongly suggest using CTAGS! I use sublime text 2 with the CTAGS plugin. I just press CTRL+SHIFT+Click on the class method and it will bring up a list of classes that have that method, or if only one exists, take me directly to the file and method. It beats searching the API/docs in terms of speed. There is even a Sublime text 2 plugin for Laravel Facades !
https://github.com/stidges/Laravel-Facades-for-ST

Laravel4: Will not using the repository pattern hurt my project in the long run?

I'm reading Taylor Otwell's book in which he suggests using the repository pattern. I get the theory behind it. That it's easy to switch implementations and decouples your code. I get the code too. And it is very nice to be able to switch by App::bind() with some other implementation. But I've been thinking for the last two hours how I should approach things for a new CRM I'm building. Almost no code yet but it might end up big.
I would prefer to simply use eloquent models and collection injected through the controller. That should make everything testable if I'm not mistaken.. . Allowing for mocks and such.
Does the repository pattern maybe offer any benefits towards scalability? In cases when more servers or resources are needed..
And why would anybody want to replace the Eloquent ORM once committed to its use? I mean most projects need a relational database. If I would build a UserRepositoryInterface and an implementation DbUserReponsitory, I cannot see when I would ever need or want to switch that with something else. This would count for most entities in my project (order, company, product, ...). Maybe to use another ORM to replace Eloquent? But I don't see myself doing this for this project.
Or am I missing something? My main concern is to have code that is readable and easy to test. Haven't really been testing that well up to now :)
It does not necessarily mean that ignoring the Repository pattern will give you headaches on the long run, but it certainly makes re-factoring code much easier thus you can easily write Test repositories and bind them with your controllers to easily test your business logic.
So even if it is not likely that you will replace Eloquent or any other part, encapsulating chunks of logic and operations in repositories will still be beneficial for you.
Dependency injection is nothing new in terms of design patterns, will it hurt your code, not necessarily. Will it hurt your ability to easily write / re-factor old code and swap it in easily... absolutely it will.
Design patterns exist as solutions to common problems. I would tell you straight away that ignoring the IoC container in Laravel and not dependency injecting will have a big impact on you later down the line if you're writing complex applications. Take for example that you may want different bindings based on request type, user role / group, or any other combination of factors, by swapping out the classes without impacting your calling code will be beyond invaluable to you.
My advice, do not ignore the IoC container at all.
As a sidenote, Service Providers are also your friend, I'd suggest you get well acquainted with them if you want to write great apps in Laravel 4.

Using an object oriented approach in Ruby

I have two classes, Class A and Class B.
I've recently noticed that they share a lot of the same code. For example:
def viewable_by?(user)
super || clinic.has_staff_member?(user) || user.system_admin? || self.person == user.person
end
I want to minimize the code duplicated between the classes. But in refactoring, I've found that much of it doesn't fit neatly into one class that falls cleanly in the Single Responsibility Principle. I want to put it all into a single module, but the methods will have to do with time formatting, viewing permissions, and a few other things.
As I see it, I have a few choices. (And I bet you can suggest others.) From an object oriented point of view, which approach should I go with and why?
Use one single module shared between both of the classes. It may
not have a specific single responsibility, but it does clean up the
code significantly, and keeps it all in one place.
Make tiny classes and mix in to both classes as modules. They
will all have a single responsibility, but there will be many of
them, some of which may only have one method. Seems like a waste.
Perhaps use a presenter for things like time formatting, and a
permissions module shared between both classes. Perhaps "cleaner,"
but methods are going to be everywhere.
Another possibility I haven't yet considered?
EDIT
This question had previously mentioned Clinic::Appointment and Clinic::Visit classes, rather than A and B. Answers may refer to appointments and visits.
This is a neat question because it deals in a great way with the overall strucuture of your project. I understand that Appointment and Visit are separated things, and an Visit don't need to be linked to an Appointment.
For authorization methods, like viewable_by?, I recommend move all authorizations to other place - you might want to check the cancan structure, that have worked well for many Rails projects, and most likely will work well for any application, even coding an authorization system yourself. So in part, my answer for you is to use (3).
However, since not all code that is shared by the two classes are for authorization purposes, I would try to classify a set of methods, and give an answer for each class of methods you could think of. For method classes that have a similar behavior I would try to encapsulate in a module and include it (so just like (1), but in smaller parts). For example one module HasVisitors with methods like got_on_time? and was_conclusive? (well, maybe not the best examples, but you get it). When your model has a broader scope, like Authorization, that is present in most of your classes, then it is time to go to (3).
I suggest you stop and think again if you should have a Visit class apart from Appointment and it relationship, but not now. After got at home, have fun, take it off from your head, then think again next day.
Would the design be clearer if you shifted the responsibilities? e.g. user.can_view?(resource)

Prism, mapping region to a view

I'm quite new to Prism. I'm studying QuickStarts shipped with it as well as other examples on the net. Almost all of them make modules aware of what region their view(s) get dropped into. Typically, the method Initalize of a module has a line like the the following.
RegionManager.Regions["LeftRegion"].Add(fundView);
I feel quite uncomfortable with that. There's a similar discussion but I think that it should be the responsibility of the shell component to define such mapping. However, I cannot find any example of such approach and I'm not sure whether the bootstrapper is the right place to put such mapping in.
Is this approach completely wrong?
Nothing is completely wrong. But it makes no sense to have the shell/bootstrapper (that by design doesn't know anything about the application it will host) knows what view goes into which region.
Consider an application that can be extended by simply adding modules into a given folder. When you follow the approach that the module knows where it's views want to reside (the mapping is done in Initialize()), this is no problem. I designed my first Prism application that way.
But if your mapping is done in your shell you always have to update your shell (which is part of the base application, not any module) when you want to add another module. This runs contrary to the loosely coupling paradigm. Besides that you have to create one base application for every module constellation. And there are (2^number of modules) permutations you have to cover. That results in loosing your flexibility you gained by using Prism.

Resources