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 have a method set in an POCO entity that set the basic property and the navigation property. In some cases, I don't need to verify some conditions, but in another cases I need to verify to ensure that the information is coherent in the database, but this verification makes me to get extra data from database.
So by the moment I have my basic method that is this:
public void setMyProperty(MyType paramProperty)
{
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
For the method that verifies the data, I guess that I have two options.
First one, I can create a new method for business logic, somthing like that:
public void setPropertyBi(MyType paramProperty)
{
//check conditons
//If all OK then
this.setPorperty(paramProperty);
}
But I have another option, use only one method, not the basic method and the other for business checks. Something like that:
public void setProperty(MyType paramType, bool paramDoChecks)
{
if(paramDoChecks)
{
//Do checks
}
//if all OK
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
Which is the recommended option? or there are another ways?
People here seem to prefer the flag, I personally think it is horrible.
You want to achieve two different things: just set a property; validate AND set a property. IMHO it should be two separated methods.
Just don´t write two different Methods if it´s one equaly functionality. Just add a Parameter which makes the validation-difference like you´ve written last.
But don´t forget to enter the behaviour if validation failed. separate it well.
You could add a Boolean ValidationRequiredproperty to MyType which you can set before the call to setMyProperty().
I prefer to have two methods: CanSetProperty and SetProperty.
CanSetProperty: just check the condition, does not change anything in the parameter.
SetProperty: will modify the paramenter.
I think this code is a good candidate to follow the Command Query Separation Pattern
The fundamental idea is that we should divide an object's methods into
two sharply separated categories:
Queries: Return a result and do not change the observable state of the
system (are free of side effects).
Commands: Change the state of a
system but do not return a value.
Related
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 2 years ago.
Improve this question
Imagine I have the following class:
public class MyWeirdCollection
{
private IList<string> _myTrueList;
private IList<string> _myFalseList;
public MyCollection()
{
_myTrueList = new List<string>();
_myFalseList = new List<string>();
}
public void Add(string item, bool listType)
{
if (listType)
{
_myTrueList.Add(item);
}
else
{
_myFalseList.Add(item);
}
}
public IList<string> Get(bool listType)
{
return listType ? _myTrueList : myFalseList;
}
}
How would I go about unit testing the Get and Add methods? I'm doubting between 2 possible solutions:
Making the 2 lists protected instead of private, so I can create an inheriting TestableWeirdCollectionClass that exposes the content of the lists to the test
Leave the class as it is and test Add and Get together? i.e. calling Add to add some elements and then Get to see if the correct values come back.
I'm leaning towards option no. 2, but would like some more opinions. Thanks.
Definitely go for the option 2. Pretty much every test I can imagine must go though Add, then Get, together.
When testing you are ultimately testing the public interface, not the internal state. The whole idea of the test code is that you give items to it, then you get them back with the appropriate key. In your particular case it uses private lists to hold the items, but this may not be the case (you might store them to a database or file, rely on another class or something else). This is ultimately an implementation detail, the important bit is that Add and Get always play together, therefore you should it.
I would strongly recommend option 2. The reason is that your whole class should be consider a unit, and be tested as such. Making methods public for the sole purpose of unit testing can be motivated in some rare cases for very complex classes, but should be avoided if at all possible.
See also
Is it bad practice to make methods public solely for the sake of unit testing.
Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject
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 4 years ago.
Improve this question
Say I have a base method GetSong() that fetches songs from a database, and two methods that call this - GetRockSong() and GetPopSong().
Both methods take a string input of the song name, then pass that input to the GetSong() method, along with a genre.
Should the base method be in charge of validating the string input?
I would think the first two methods should, but this would lead to repeating the exact same code (i.e. checking the string isn't empty).
Obviously I have used a hugely simplistic illustration, but the problem is pretty much the same.
Example code:
public Song GetRockSong(string title)
{
// could null check title here before calling the method?
return GetSong(title, "Rock");
}
public Song GetPopSong(string title)
{
// could null check title here before calling the method?
return GetSong(title, "Pop");
}
public Song GetSong(string title, string genre)
{
// example validation, if null checking title above
// then could just check genre here
if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(genre))
{
// fetch song logic here
}
// etc
}
I personally think if the validation is the same then do the check in the shared method.
This will allow for you to maintain the code easier and it is always best to have the method that does the heavy lifting also validate the values passed to it.
I have done similar thing and found that the amount of code I needed to write and maintain is half of what it could have been if I had put the validation in each method that called it.
I hope this helps!
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 6 years ago.
Improve this question
I have a class/object called "User" that has about a dozen properties (eg: UserGUID, UserName, etc.). It has a constructor, static methods, couple other helpers/support methods, etc.
The website has hundreds of functions/methods where 2+ parameters come from the User object. For example:
public string HelloWorld(Guid userGUID, Guid accountGUID, bool somethingElse)
{
//Do something
}
I really want to pass in the User object itself to make the call cleaner and not have to keep adding parameters everytime I need a new value from the User object. Like this:
public string HelloWorld(User user)
{
//Do something
Guid userGUID = user.UserGUID;
}
So my question is, at what point is passing in the object good/bad vs passing in several parameters? Does it depend on the size of the object? How would I determine what's "too big" vs "OK"? Is it the number of parameters? How many params is too many?
You should think about what the method is supposed to do . Why does the method exist?
The semantic of the method will determine its arguments. So, for example, if HelloWord is supposed to print some stuff out, like a userId, and something else, then the signature should contain userId and something else as arguments.
On the other hand, if HelloWord is supposed to print out some information about a User, then the method signature should have the object User as a parameter.
It all depends on the method semantic.
In Clean Code, Robert Martin says to prefer 0 arguments, 1 or 2 arguments are acceptable and 3 is too many.
In my opinion as long as you're in the same process I think passing the object is preferable to passing arguments. You wouldn't want to send (or receive) more than is needed to another process (say a web service).
I highly recommend Clean Code, it's a good read and has a lot to say about structure.
There is a very important difference here, and this is not an opinion.
I have a class/object called "User" that has about a dozen properties
Given the above situation, if you were then to allow (User user) as opposed to only allowing (Guid userGUID, Guid accountGUID, bool somethingElse) you have just introduced a security hole.
Clients would be able to send more data than they were supposed to have access to by posting the extra names of the User class. For example, it is possible for a client to alter foreign navigation property keys in this fashion if you make the entire class available (and it had foreign relations). It is also possible for clients to alter timestamps, and even logical separations depending on information stored in that class.
Preventing this type of breach is easy to do if you allow the entire class to be accepted, you just need to then manually inspect each property to make sure it wasn't erroneously sent, or screen it by only selecting the subset of information sent. Either way, this is a bad idea.
While there may be no difference in using a User class with the same properties as the 3 shown, allowing the model binding of a User class which has a larger set than the 3 can be problematic if left unchecked.
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 6 years ago.
Improve this question
Sometimes in my models, I implement get only 'Has' properties (e.g. HasDescription) so I can easily check the validity of a property from outside my model with if (model.HasDescription) { ... }.
The implementation might look something like:
public bool HasDescription => Description != null && Description != string.Empty;
Is this good practice? More specifically, if I do take this approach should I move this conditional logic elsewhere? Perhaps into extension methods?
It's a matter of personal preference sometimes; having a bunch of HasX properties can be OK. I sometimes do it for validation reasons (I found it works well to use a property like that for an MVC app when using FoolProof). It can be cumbersome to have to add a bunch of HasX properties though... So, if you are using these for evaluations in your controller, it's a matter of personal preference. If that is the approach you want to take, I wouldn't worry about it.
If you are using it for validation purposes, sometimes when you need model-based evaluation, you can use an IsValid method for determining validation status. That would be more MVVM-like than MVC-like, but it works.
Has is completely legitimate. However, the logic belongs in the setter or in the constructor: decide on a way to represent a missing property (null or string.Empty, preferably null, but definitely not both). This leaves the Has logic to check for null.
One consideration in favor of dropping Has altogether is the possibility of using ?? operator. If your use cases allow you to replace
var xyz;
if (x.HasXyz) {
xyz = h.Xyz;
} else {
xyz = defaultValueOfXyz;
}
with
var xyz = h.Xyz ?? defaultValueOfXyz;
then you can drop HasXyz altogether.
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 4 years ago.
Improve this question
Here's an example. I saw a "ReadOnlyDictionary" class online and it had the following code:
void ICollection.CopyTo(Array array, int index)
{
ICollection collection = new List<KeyValuePair<TKey, TValue>>(this._source);
collection.CopyTo(array, index);
}
For example, should I check array for a null argument, or should I let the the CopyTo method do that for me? It just seems a bit redundent, but if best practices say to check everything in your own method, then that's what I want to do. I'm just not sure what "best practices" says to do.
I think it wise to say if you plan to do something with array that relies on it NOT being null then you should check this. But if it just a pass through then I don't see a reason why you should check.
Another thought is if the method gets complicated in the future. You might still want to check for it because someone may modify the code and use array without realizing that it might be null. This is only for maintaining good code in my opinion.
If somebody else's library or API* is going to complain about my inputs, I don't want to give it those inputs, I want to validate and/or complain first. This is especially important if calls into external APIs are expensive, such as a database or web service call.
You know what inputs the API is going to reject. Don't send those, invalidate them in your own public API.
*Note: I consider my own public boundaries to be the same thing. If I have class Foo that does not like given arguments, if I invoke Foo, at some level before doing so, I'm going to validate my arguments. You don't do this at every level (assume there are layers of indirection, maybe, private methods calling into private methods, etc.), but at some reasonable public boundary, I will validate. Validate early, don't let complicated logic or work be done when it's just going to be rejected anyway.