Should a factory method of a custom container return the newly created instance? - factory-method

I have a custom collection Doohickeys indexed by keys. This collection has a factory method createDoohickey(key) and an accessor Doohickey(key). Should createDoohickey(key) return the new object or should it return void?
In the first case, I would use it like this
myDoohickey = doohickeys.createDoohickey(key);
doStuff(myDoohickey);
in the other case like this
doohickeys.createDoohickey(key);
doStuff(doohickeys(key));
Which one would you consider preferable, and why?
EDIT I believe I have learned quite a bit over the years and that the answer I accepted is actually not really the best one.

I'm not sure the container should have a factory method to create the object it contains - good separation of concerns would be to separate object creation from the container.
Therefore, I think you should have something like this:
Doohickey myDookickey = new Doohickey();
doohickys.Add(key, myDookickey);
doStuff(myDookickey); // or
doStuff(doohickeys(key));
You are then free to use a separate object factory or instantiate Doohickey directly. This makes it easier to unit test the container with mock Doohickey objects.
If you must have the factory method, I would return the Doohickey, because it is probably cheaper to ignore the return value (assuming a reference/pointer is returned) when it is not needed than to use the index to retrieve it when it is.

Yes, a Factory should return the newly created instance.
However like Alex pointed out you could seperate the Repository and the Factory. I would most likely design the factory to have a reference to the repository. I don't think it would be the end of the world of you combined the two into one class just as long as the factory method actually returns the newly created instance.

The example above embeds the factory method in the container class. I agree with willcodejavaforfood, and this may or may not be a good idea over the longer term. The issue is whether the reduced coupling of splitting the factory into its own class is worth the extra cost.
As far as why a factory method should return the newly created instance, it is preferable to decouple creation from containment. Some users of the class might want one but not the other. Also, when you couple creation and containment you can no longer (unit) test creation without also testing containment.

This answer is from a colleague of mine. He suggested to have createDoohickey(key) indeed return the Doohickey; and, additionally, to call it getDoohickey(key) instead.
EDIT I believe after what I have learnt since that this answer is not necessarily the best one any more.

Related

Proper way of handling scopes with pivot involved

As a laravel user for a couple of months now, I'm trying to better understand advanced use of Eloquent.
I ran into a case where I can't come up with a solution that feels right.
I've got the following structure (simplified)
Mandate
id
status_id
Mandate_user
mandat_id
user_id
link_status
User
id
I declared belongsToMany in both User and Mandat via the pivot table.
on User:
public function mandates(){
return belongsToMany(..)->withPivot('link_status');
}
I'm able to get accepted mandates for a user by using
public function acceptedMandates(){
return $this->mandates()->wherePivot('link_status', MandateUserStatus::Accepted);
}
This works but I'm wondering if there would be a better way by using scopes or other eloquent methods.
And I'm trying to get accepted mandates that also have a status_id lower than 4 (which comes from an enum as well)
I thought of something like :
public function runningMandates(){
return $this->acceptedMandates()->where('status_id','<', 4);
}
Then gathering mandates like so:
$mandates = User::find(1)->runningMandates();
But would the eloquent way be of doing something like:
$mandates = User::find(1)->mandates()->running()->accepted();
Thanks for your time.
It's a very subjective question and hard to give a straight answer to, but hopefully I can stop you from second-guessing yourself: what you're doing is perfectly fine and no less "eloquent-like" than the other.
Personally I like what you're doing now much more than what you present as the "Eloquent way" and have done so before in professional projects, but ultimately there is a difference in the way you design the code for a framework or package, which must be flexible to account for many different scenarios, most of which you cannot even envision when doing version one, versus how you design the code for an app which will only be consumed by itself. If you know the business logic that drives your app and the views it will present to its users (subsequently, the queries it must perform), why wouldn't you create methods that will easily achieve just that?
Eloquent relies on chaining not just because it's cool, but because it does not know (or care to know) what your business logic is. To me, the "Eloquent way" is more about fluent, readable code, and I find that $user->runningMandates is more readable than $user->mandates()->running()->accepted()->get().
I also find that the first approach is easier to get into. If you're constantly forcing yourself to separate methods so they can be chained, it can be harder to grasp which method is doing what and which method relies on which. Query scopes can modify the query as they like (join, alias, etc) so the danger lies in one method requiring another to come first, because you're conditioning based on a table or column that isn't on the original query, so a method will only work in conjunction with another; or maybe two methods are trying to join the same table, or using the same aliases, so they cannot be used together. It may seem far-fetched, but often the effort to keep things separate and tidy will make your code harder to use. But even if things don't blow up code-wise, the deal-breaker to me would be neglecting business logic: in your case, does it make sense to have two separate scopes for running and accepted? Can a mandate be running if it's not accepted? If not, you should try to prevent a less knowledgeable developer from creating that flawed query (logic-wise). And as you said, the structure is simplified so there may be other gotchas lurking around, and many more will come as the app grows in complexity.
If I'm taking over someone else's code, I'd rather have limited, self-contained methods that don't break over simple, decentralized methods that require you to read (often non-existent) documentation in order to prevent the many ways in which to mis-use them.
Basically, scopes add constraints to the query so you may use the scope approach to modify the query by calling scope methods that will eventually give you a chance to make a query dynamically. So, you may declare (as you did) one relationship method where you may do all the query and call that specific method or use scope methods two build the query using method calls where each method adds a constraint. In this case, it'll be more dynamic but still it's a preference and it gives you more flexibility (IMO). So yes, you can use query scopes for that, for example:
// Declare the main relationship
public function mandates()
{
return $this->belongsToMany(..)->withPivot('link_status');
}
Now, declare query scope for accepted (add a constraint on the query returned by mandates method call)
public function scopeAccepted($query)
{
return $query->wherePivot('link_status', MandateUserStatus::Accepted);
}
Now, add another query scope for running, for example:
public function scopeRunning($query)
{
return $query->where('status_id','<', 4);
}
Now, if you call something likethe following:
$user = User::find(1);
Now, call the relationship method (not as property)
$mendates = $user
->mandates() // The method is called and a query object is constructed
->running() // Add another constraint into the query: ->where('status_id','<', 4)
->accepted() // Add another constraint into the query: ...
->get(); // Finally, execute the query to get the result
Probably, it's clear to you now. Notice the method call mandates(), it's a method call on the relation defined which returns the Query Builder and by chaining additional scope method calls, you are just modifying the query by adding some more constraints but you can do all the query in one method without dynamic scopes, so it's up to you. While, scopes gives you more flexibility but it doesn't mean you've to follow this approach always, it depends.

Services vs Factory in agularJs

Is there any thing exist which I could do in service but not in factory or vice-versa? Basically I want to conclude the difference between the service and a factory.
you can take a look at a the new post .service() versus .factory(), the actual answer. by #ToddMotto
So, what is a service?
A Service is just a function for the business layer of the application, it’s just a simple function. It acts as a constructor function and is invoked once at runtime with new, much like you would with plain JavaScript
Factory
Next, the confusing .factory() method. A factory is not just “another way” for doing services, anyone that tells you that is wrong. It can however, give you the same capabilities of a .service(), but is much more powerful and flexible.
A factory is not just a “way” of returning something, a factory is in fact a design pattern. Factories create Objects, that’s it. Now ask yourself: what type of Object do I want? With .factory(), we can create various Objects, such as new Class instances (with .prototype or ES2015 Classes), return Object literals, return functions and closures, or even just return a simply String. You can create whatever you like, that’s the rule.
Enjoy

What's the preferred way to go about using backbone with non-crud resources?

New to backbone/marionette, but I believe that I understand how to use backbone when dealing with CRUD/REST; however, consider something like results from a search query. How should one model this? Of course the results likely relate to some model(s), but they are not meant to be tied to said model(s).
Part of me thinks that I should use a collection using a model that doesn't actually sync with a data store through the server, but instead just exists as a means of a modeling a search result object.
Another solution could be to have a collection with no models and just override parse.
I assume that the former is preferred, but again I have no experience with the framework. If there's an alternative/better solution than those listed above, please advise.
I prefer having one object which is responsible for both request and response parsing. It can parse the response to appropriate models and nothing more. I mean - if some of those parsed models are required somewhere in your page, there is something that keeps reference to this wrapper object and takes models from response it requires via wrapper methods.
Another option is to have Radio (https://github.com/marionettejs/backbone.radio) in this wrapper - you will not have to keep wrapper object in different places but call for data via Radio.

angularjs using angular.extend to bind $scope to a service bad/good practice

I'd like to know if using
angular.extend($scope,MyService);
Does it break oop encapsulation principle ?
Does it smell like MyService.call($scope) ?
Could you face variable and function conflicts ?
Is this a bad/good practice?
Typically from my experience services are injected into the controller and then will be called from that scope. I wouldn't say that using extend to copy over functions and properties is necessarily bad, but it might mitigate some of the purposes of IoC (inversion of control), which is what injection in angular is based on.
Does it break oop...?
My understanding is that what you would get from this call is additional functions and service calls directly on your scope. This doesn't break OOP in the sense that scope is an object and would have functions applied. Provided those functions + properties make sense on the scope it seems like a fine thing to do from that perspective.
Does it smell like MyService.call($scope)?
As I said in the first paragraph - I don't see why you wouldn't just call the service and either share data or pass in references to objects to the service. Another pattern that is common in angular is to use a promise to process returned data in your scope. That looks like:
MyService.callFunction(parameters).then(function (data) {
// process data here. Since this runs in $scope you can also use $scope normally.
// $scope.$apply() is in progress and will complete when the function returns
});
All the service does is provide the data to the scope then. Point is that I think there are better patterns than "extend".
Can you face conflicts?
In the call angular.extend(a, b); data, properties and functions are copied from b to a. If something already exists on a it will be overwritten with the data from b. So technically the short answer is "yes", you can face conflicts.
The bottom line
So at the end of the day this isn't a bad pattern but there are probably more common patterns I would try to use first.

helper functions as static functions or procedural functions?

i wonder if one should create a helper function in a class as a static function or just have it declared as a procedural function?
i tend to think that a static helper function is the right way to go cause then i can see what kind of helper function it is eg. Database::connect(), File::create().
what is best practice?
IMO it depends on what type of helper function it is. Statics / Singletons make things very difficult to test things in isolation, because they spread concrete dependencies around. So if the helper method is something I might want to fake out in a unit test (and your examples of creating files and connecting to databases definitely would fall in that category), then I would just create them as instance methods on a regular class. The user would instantiate the helper class as necessary to call the methods.
With that in place, it is easier to use Inversion of Control / Dependency Injection / Service Locator patterns to put fakes in when you want to test the code and you want to fake out database access, or filesystem access, etc.
This of course has the downside of there theoretically being multiple instances of the helper class, but this is not a real problem in most systems. The overhead of having these instances is minimal.
If the helper method was something very simple that I would never want to fake out for test, then I might consider using a static.
Singleton solves the confusion.
MyHelper.Instance.ExecuteMethod();
Instance will be a static property. Benefit is you get simple one line code in calling method and it reuses previously created instance which prevents overhead of instance creation on different memory locations and disposing them.

Resources