Are 'Has' Properties Good Practice? [closed] - c#

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.

Related

Should two separate methods that call a shared base method individually validate inputs? [closed]

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!

two differents method or additional parameter? [closed]

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.

Class Name: Append DTO or Entity [closed]

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 7 years ago.
Improve this question
Is there any preference on either appending DTO or Entity to a class name?
Is there any standard around this?
1 Class is used by ORM (EntityFramework) and the other class is used for serialization.
The reason for this is so that there is no duplication of all fields as the EntityFramework is a wrapper around the DTO class(most but not all properties).
The DTO class is in a shared library, and decoupled from EF.
E.g. Which of these is the most common/standard approach?
// 1.
MyNamespace.Entities.MyClass
MyNamespace.Models .MyClassDto
// 2.
MyNamespace.Entities.MyClassEntity
MyNamespace.Models .MyClass
// 3.
MyNamespace.Entities.MyClassEntity
MyNamespace.Models .MyClassDto
In my personal experience your third example is the only implementation I have worked with and it is the one I would argue for because the intent of the object you are working with will always be clear whereas with the other two it only becomes clear when looking at both objects together.
That being said as long as your team comes to an agreement on which to use any would work.
In my opinion, you typically don't want to put implementation details into class names for similar reasons to why you don't want to use Hungarian Notation.
If there's a bit of code that needs to work with both types and differentiate between them, another option is including aliased using statements like this:
using entities = MyNamespace.Entities;
using dto = MyNamespace.Models;
//in code
var myClassEntity = new entities.MyClass();
var myClassDto = new dto.MyClass();
//work with both
My assumption is that the code that needs to work with both types is limited to an isolated library, and that client code typically works with one, not both types.

Is reassigning parameter (locally) inappropriate? [closed]

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 9 years ago.
Improve this question
Is there a broad aversion in the C# community to modifying parameters? For example, would a popular style-checker complain about the parameter reassignment aspect of the following?
public void Create(Template template = null) {
if (template == null) template = GetDefaultTemplate();
// ...
}
An alternative to this would be the following, but assuming code blocks are appropriately small, it's probably not any clearer:
public void Create(Template template = null) {
var theActualTemplate = template ?? GetDefaultTemplate();
// ...
}
I apologize for this surely tired/already-answered question, but oddly I can't find anything on it. I tried looking through some C# style guides (including all the ones here: Style guide for c#?), but didn't find this issue covered. Maybe it's a non-issue?
If you have a relatively authoritative source for this, I'd love to hear it.
In your sample you are just modifying the variable inside your method scope. Since that is your local variable, your method can do with it whatever it wants - it does not impact the caller. In general it is better to use the same variable because it makes the code easier to maintain - if you create a new variable, you increase the risk of accidentally using the wrong one and get NullReferenceException.
If you would be using ref keyword only then the assignment will impact the caller.
It can be useful when you need to set a default value for a reference type, because you can't really specify it like you would do for a value type.
public void Create(int templateId = 1) {
// this will compile
// ...
}
public void Create(Template template = GetDefaultTemplate()) {
// this WON'T compile
// ...
}
Using null as a default value for a reference type can help you defining a default object for your parameter.

Best Practices - Is it necessary to check for certain preconditions if another method does so? [closed]

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.

Categories