Symfony | Best way to init property in Entity - entity

I'm new in Symfony, i have a question about the best way to init a property in an Entity.
For example, i have an Entity "Question" which has a property "user", i do this :
$question = new Question();
$question->setUser($this->getUser());
$form = $this->createForm(QuestionType::class, $question);
It works, i can also do it with the constructor :
$question = new Question($this->getUser());
$form = $this->createForm(QuestionType::class, $question);
It works too but I don't know which one is the best. Or maybe there is another better solution ? I mean, I will have to init this Entity many times and maybe there is a way to do :
$question = new Question();
$form = $this->createForm(QuestionType::class, $question);
So I don't have to care about "user" in my controllers ?
Anyway, what is the best solution to do this ?
Thanks.

It depends on whether or not a question in your context must have a user. If it is optional, the setter is fine - you can create a question even without a user. If it is necessary, you should inject it in the constructor - this also helps other developers and your future self to understand that you cannot create a question without a user.
The third option would mean that you somehow have to fetch the user from inside the question, which couples it to the mechanism that is responsible for that (for example the security component). This is generally a bad idea as it limits it's usages and makes testing a lot harder.
Another hint: maybe setUser() is not a good naming choice for a Question class, as it lacks expression of what it really is. Is it the author of the question? Then setAuthor() could be a better choice.

Related

Does Open Closed Principle mean that we have to define every method as virtual?

I'm having trouble getting the idea behind open closed principle.
As far as I know, the principle says that every class should be closed for modification and open for extension. right?
So it means that we have to make every method in our class virtual so we can extend the class without needing to modify it. Is this correct?
I think you are somewhat misunderstanding what the Open-Closed principle entails.
The open-closed principle states that software entities should be closed for modification and open to extension. Software entities in this context refers to classes, structs methods etc.
The basic idea is that your entities should not need to change often to requirements. If new requirements come along, your entities should be extended to accommodate the new functionality.
Suppose we have the following function:
public List<Product> GetProducts(Criteria criteria)
{
return context.Where(x => x.criteria1 = criteria.criteria1)
.Where(x => x.criteria2 = criteria.criteria2)
.Where(x => x.criteria3 = criteria.criteria3)
.Where(x => x.criteria4 = criteria.criteria4);
}
It is easy to see that when another criteria requirement comes along, this will require modification to the "ProductRepository" class and it's functions. Ofcourse, many more functions in this class might need to be modified as it may also use criteria objects.
Suppose we can write something like this instead:
private List<Product> GetProducts(Criteria criteria)
{
return cleverContext.Apply(criteria);
}
We immediately gain the flexibility where only the code that is responsible for the criteria is modified or extended.
The biggest ways of improving design to satisfy the Open-Closed principle is to use a rich domain. When your domain models enterprise business rules, the rules should never change. We separate Domain with Use-Cases to deal with application rules.
Uncle bob writes more on this in his clean architecture.
Let me know if there is anything that I can shed light on, or try to explain further :)

Passing an object with Aurelia router.navigate to a view

I need to do a master-details view when I click on a row. I have the code in a branch here's the commit link.
let urlDetail = this.router.generate('energy-details', {model: this.model});
this.router.navigate(urlDetail);
This works, but the query string is awful. How do I send the model across in memory?
This was really hard to find an example for. https://github.com/softchris/aurelia was the best one.
Is there a better way to do master-detail views? I'm new to Aurelia.
http://localhost:5000/#/energy-details?model%5BdataSeriesId%5D=ES&model%5BcountryId%5D=392&model%5BcountryName%5D=Japan&model%5BtransactionCode%5D=01&model%5BcommodityTransactionId%5D=ES01&model%5BcommodityTransactionName%5D=Electricity%20-%20solar%20production%2C%20public&model%5Byear%5D=2000&model%5Bunit%5D=Kilowatt-hours%2C%20million&model%5Bquantity%5D=2&model%5BfootnoteSequenceId%5D=0.
Reconsider if you just don't want to use id. Quite often in a mater-details you need to make a new query to get more data anyway.
If not possible for your use case, maybe it makes sense to have a DataManager singleton.
Create a DataManager class that you inject in your List and Detail ViewModel. By default every injected class is a singleton in aurelia
In the list ViewModel, make sure your data is saved in the DataManager
Routing by passing the id only
In the details ViewModel call your method getModelById(id) of the DataManger

Why are helperclasses anti pattern

A recent question here made me rethink this whole helper classes are anti pattern thing.
asawyer pointed out a few links in the comments to that question:
Helper classes is an anti-pattern.
While those links go into detail how helperclasses collide with the well known principles of oop some things are still unclear to me.
For example "Do not repeat yourself". How can you acchieve this without creating some sort of helper?
I thought you could derive a certain type and provide some features for it.
But I bellieve that isnt practical all the time.
Lets take a look at the following example,
please keep in mind I tried not to use any higher language features nor "languagespecific" stuff. So this might been ugly nested and not optimal...
//Check if the string is full of whitepsaces
bool allWhiteSpace = true;
if(input == null || input.Length == 0)
allWhiteSpace = false;
else
{
foreach(char c in input)
{
if( c != ' ')
{
allWhiteSpace = false;
break;
}
}
}
Lets create a bad helper class called StringHelper, the code becomes shorter:
bool isAllWhiteSpace = StringHelper.IsAllWhiteSpace(input);
So since this isnt the only time we need to check this, i guess "Do not repeat yourself" is fullfilled here.
How do we acchieve this without a helper ? Considering that this piece of Code isn't bound to a single class?
Do we need to inherit string and call it BetterString ?
bool allWhiteSpace = better.IsAllWhiteSpace;
or do we create a class? StringChecker
StringChecker checker = new StringChecker();
bool allWhiteSpace = checker.IsAllwhiteSpace(input);
So how do we acchieve this?
Some languages (e.g. C#) allow the use of ExtensionMethods. Do they count as helperclasses aswell? I tend to prefer those over helperclasses.
Helper classes may be bad (there are always exceptions) because a well-designed OO system will have clearly understood responsibilities for each class. For example, a List is responsible for managing an ordered list of items. Some people new to OOD who discover that a class has methods to do stuff with its data sometimes ask "why doesn't List have a dispayOnGUI method (or similar such thing)?". The answer is that it is not the responsibility of List to be concerned with the GUI.
If you call a class a "Helper" it really doesn't say anything about what that class is supposed to do.
A typical scenario is that there will be some class and someone decides it is getting too big and carves it up into two smaller classes, one of which is a helper. It often isn't really clear what methods should go in the helper and what methods should stay in the original class: the responsibility of the helper is not defined.
It is hard to explain unless you are experienced with OOD, but let me show by an analogy. By the way, I find this analogy extremely powerful:
Imagine you have a large team in which there are members with different job designations: e.g, front-end developers, back-end developers, testers, analysts, project managers, support engineers, integration specialists, etc. (as you like).
Each role you can think of as a class: it has certain responsibilities and the people fulfilling those responsibilities hopefully have the necessary knowledge to execute them. These roles will interact in a similar way to classes interacting.
Now imagine it is discovered that the back-end developers find their job too complicated. You can hire more if it is simply a throughput problem, but perhaps the problem is that the task requires too much knowledge across too many domains. It is decided to split up the back-end developer role by creating a new role, and maybe hire new people to fill it.
How helpful would it be if that new job description was "Back-end developer helper"? Not very ... the applicants are likely to be given a haphazard set of tasks, they may get confused about what they are supposed to do, their co-workers may not understand what they are supposed to do.
More seriously, the knowledge of the helpers may have to be exactly the same as the original developers as we haven't really narrowed down the actual responsibilities.
So "Helper" isn't really saying anything in terms of defining what the responsibilities of the new role are. Instead, it would be better to split-off, for example, the database part of the role, so "Back-end developer" is split into "Back-end developer" and "Database layer developer".
Calling a class a helper has the same problem and the solution is the same solution. You should think more about what the responsibilities of the new class should be. Ideally, it should not just shave-off some methods, but should also take some data with it that it is responsible for managing and thereby create a solution that is genuinely simpler to understand piece by piece than the original large class, rather than simply placing the same complicated logic in two different places.
I have found in some cases that a helper class is well designed, but all it lacks is a good name. In this case, calling it "Builder" or "Formatter" or "Context" instead of "Helper" immediately makes the solution far easier to understand.
Disclaimer: the following answer is based on my own experience and I'm not making a point of right and wrong.
IMHO, Helper classes are neither good nor bad, it all depends on your business/domain logic and your software architecture.
Here's Why:
lets say that we need to implement the idea of white spaces you proposed, so first I will ask my self.
When would I need to check against white spaces?
Hence, imagine the following scenario: a blogging system with Users, Posts, Comments. Thus, I would have three Classes:
Class User{}
Class Post{}
Class Comment{}
each class would have some field that is a string type. Anyway, I would need to validate these fields so I would create something like:
Class UserValidator{}
Class PostValidator{}
Class CommentValidator{}
and I would place my validation policies in those three classes. But WAIT! all of the aforementioned classes needs a check against null or all whitespaces? Ummmm....
the best solution is to take it higher in the tree and put it in some Father class called Validator:
Class Validator{
//some code
bool function is_all_whitespaces(){}
}
so, if you need the function is_all_whitespaces(){} to be abstract ( with class validator being abstract too) or turn it into an interface that would be another issue and it depends on your way of thinking mostly.
back to the point in this case I would have my classes ( for the sake of giving an example ) look like:
Class UserValidator inherits Validator{}
Class PostValidator inherits Validator{}
Class CommentValidator inherits Validator{}
in this case I really don't need the helper at all. but lets say that you have a function called multiD_array_group_by_key
and you are using it in different positions, but you don't like to have it in some OOP structured place you can have in some ArrayHelper but by that you are a step behind from being fully object oriented.

Is this an anti pattern? If so why? If not why not?

I'm working on a bit of code where we're creating object models but the models have generic keys. For example
class myContact {
var key;
var value;
}
And then in the code instantiating them as follows
myContact = new myContact()
myContact.key = 'address'
myContact.value = '123 my address'
myContact2 = new myContact()
myContact2.key = 'secondAddress'
myContact2.value = '123 my other address'
And then attaching them to a parent object like
myBank = new company();
myBank.addContact(myContact);
myBank.addContact(myContact2);
To me this feels wrong as the model is so loosely defined. However you do know from the class name it's going to be some sort of contact information.
At the same time I can see why this might be useful as if we want to add a different type of contact in future this kind of methodology makes it easy to do so.
Can any one explain to me if this is good practice? Bad practice and the reasons why?
My initial thoughts:
Good practice
Easy to extend contact types in future.
Easy to loop through contact information for myBank and get the data.
Bad practice
If you want to update a specific contact type you have to loop
through to find the correct key.
I've never written code like this which is why it feel like bad practice
even though it's perfectly acceptable.
Anemic model, there's no real need to be a class.
There's no defined key so we can't delete or add a contact easily without searching through them all again.
There's no definition of what a contact is or should be.
Any thoughts would be greatly appreciated.
edited: Adding some more thoughts as I go alone
in my opinion, there is nothing bad with 'custom fields'. it's rather popular in all systems that allow user to define their own fields (e.g jira, phone books, etc). usually there are some basic, predefined fields/keys like name, id, email etc, which are used e.g. for searching or authentication. the only thing i don't like in this code is the anemic model. if you make a class myClass (change that name!) and then give public access to all its fields, then why do you need a class? class is about encapsulation.
To me this feels wrong as the model is so loosely defined.
"Doctor, it hurts when I do this" - "Then don't do that".
Do you need a loose model to represent it? Then go for it. If not, if you feel it is only a burden, choose a simpler solution.
Apparently, there is no current need for it. What are the chances of this need to arise in the future? How would such a refactoring impact your codebase? Can you even make assumptions on that yet?
It may make sense in this case to apply the YAGNI principle in this case.

How much responsibility should a method have?

This is most certainly a language agnostic question and one that has bothered me for quite some time now. An example will probably help me explain the dilemma I am facing:
Let us say we have a method which is responsible for reading a file, populating a collection with some objects (which store information from the file), and then returning the collection...something like the following:
public List<SomeObject> loadConfiguration(String filename);
Let us also say that at the time of implementing this method, it would seem infeasible for the application to continue if the collection returned was empty (a size of 0). Now, the question is, should this validation (checking for an empty collection and perhaps the subsequent throwing of an exception) be done within the method? Or, should this methods sole responsibility be to perform the load of the file and ignore the task of validation, allowing validation to be done at some later stage outside of the method?
I guess the general question is: is it better to decouple the validation from the actual task being performed by a method? Will this make things, in general, easier at a later stage to change or build upon - in the case of my example above, it may be the case at a later stage where a different strategy is added to recover from the event of an empty collection being return from the 'loadConfiguration' method..... this would be difficult if the validation (and resulting exception) was being done in the method.
Perhaps I am being overly pedantic in the quest for some dogmatic answer, where instead it simply just relies on the context in which a method is being used. Anyhow, I would be very interested in seeing what others have to say regarding this.
Thanks all!
My recommendation is to stick to the single responsibility principle which says, in a nutshell, that each object should have 1 purpose. In this instance, your method has 3 purposes and then 4 if you count the validation aspect.
Here's my recommendation on how to handle this and how to provide a large amount of flexibility for future updates.
Keep your LoadConfig method
Have it call the a new method for reading the file.
Pass the previous method's return value to another method for loading the file into the collection.
Pass the object collection into some validation method.
Return the collection.
That's taking 1 method initially and breaking it into 4 with one calling 3 others. This should allow you to change pieces w/o having any impact on others.
Hope this helps
I guess the general question is: is it
better to decouple the validation from
the actual task being performed by a
method?
Yes. (At least if you really insist on answering such a general question – it’s always quite easy to find a counter-example.) If you keep both the parts of the solution separate, you can exchange, drop or reuse any of them. That’s a clear plus. Of course you must be careful not to jeopardize your object’s invariants by exposing the non-validating API, but I think you are aware of that. You’ll have to do some little extra typing, but that won’t hurt you.
I will answer your question by a question: do you want various validation methods for the product of your method ?
This is the same as the 'constructor' issue: is it better to raise an exception during the construction or initialize a void object and then call an 'init' method... you are sure to raise a debate here!
In general, I would recommend performing the validation as soon as possible: this is known as the Fail Fast which advocates that finding problems as soon as possible is better than delaying the detection since diagnosis is immediate while later you would have to revert the whole flow....
If you're not convinced, think of it this way: do you really want to write 3 lines every time you load a file ? (load, parse, validate) Well, that violates the DRY principle.
So, go agile there:
write your method with validation: it is responsible for loading a valid configuration (1)
if you ever need some parametrization, add it then (like a 'check' parameter, with a default value which preserves the old behavior of course)
(1) Of course, I don't advocate a single method to do all this at once... it's an organization matter: under the covers this method should call dedicated methods to organize the code :)
To deflect the question to a more basic one, each method should do as little as possible. So in your example, there should be a method that reads in the file, a method that extracts the necessary data from the file, another method to write that data to the collection, and another method that calls these methods. The validation can go in a separate method, or in one of the others, depending on where it makes the most sense.
private byte[] ReadFile(string fileSpec)
{
// code to read in file, and return contents
}
private FileData GetFileData(string fileContents)
{
// code to create FileData struct from file contents
}
private void FileDataCollection: Collection<FileData> { }
public void DoItAll (string fileSpec, FileDataCollection filDtaCol)
{
filDtaCol.Add(GetFileData(ReadFile(fileSpec)));
}
Add validation, verification to each of the methods as appropriate
You are designing an API and should not make any unnecessary assumptions about your client. A method should take only the information that it needs, return only the information requested, and only fail when it is unable to return a meaningful value.
So, with that in mind, if the configuration is loadable but empty, then returning an empty list seems correct to me. If your client has an application specific requirement to fail when provided an empty list, then it may do so, but future clients may not have that requirement. The loadConfiguration method itself should fail when it really fails, such as when it is unable to read or parse the file.
But you can continue to decouple your interface. For example, why must the configuration be stored in a file? Why can't I provide a URL, a row in a database, or a raw string containing the configuration data? Very few methods should take a file path as an argument since it binds them tightly to the local file system and makes them responsible for opening, reading, and closing files in addition to their core logic. Consider accepting an input stream as an alternative. Or if you want to allow for elaborate alternatives -- like data from a database -- consider accepting a ConfigurationReader interface or similar.
Methods should be highly cohesive ... that is single minded. So my opinion would be to separate the responsibilities as you have described. I sometimes feel tempted to say...it is just a short method so it does not matter...then I regret it 1.5 weeks later.
I think this depends on the case: If you could think of a scenario where you would use this method and it returned an empty list, and this would be okay, then I would not put the validation inside the method. But for e.g. a method which inserts data into a database which have to be validated (is the email address correct, has a name been specified, ... ) then it should be ok to put validation code inside the function and throw an exception.
Another alternative, not mentioned above, is to support Dependency Injection and have the method client inject a validator. This would allow the preservation of the "strong" Resource Acquisition Is Initialization principle, that is to say Any Object which Loads Successfully is Ready For Business (Matthieu's mention of Fail Fast is much the same notion).
It also allows a resource implementation class to create its own low-level validators which rely on the structure of the resource without exposing clients to implementation details unnecessarily, which can be useful when dealing with multiple disparate resource providers such as Ryan listed.