I am coding a C# MVC5 Internet Application and have a question about checking an objects attributes.
I retrieve an Asset object from a DbSet, and I want to check to ensure that the Asset has either a userName of the current user, or a category of DefaultMapMarker. If neither of these are true, I wish to show a HttpNotFound page.
Is the below code correct?
if (!asset.category.Equals("DefaultMapMarker" || asset.userName != User.Identity.GetUserName()))
{
return HttpNotFound();
}
Thanks in advance
EDIT
I meant to ask if the above code achieves the same as this following code:
if (!asset.category.Equals("DefaultMapMarker"))
{
if (asset.userName != User.Identity.GetUserName())
{
return HttpNotFound();
}
}
Of course not. The first will pass if only one condition is correct. But the second will check both conditions to excecute the action.
the second is equal to:
if (!asset.category.Equals("DefaultMapMarker") && asset.userName != User.Identity.GetUserName()))
{
return HttpNotFound();
}
No, this does not achieve the same thing.
Your first statement with the logical or says "If this condition is met OR the other is met: {...}"
Your second statement says "If condition is met AND this condition is met {...}", which could be translated into:
if (!asset.category.Equals("DefaultMapMarker" && asset.userName != User.Identity.GetUserName()))
{
return HttpNotFound();
}
So the answer to your question is: No, they don't achieve the same thing. If you want a HttpNotFoundException to be raised if both conditions are met you have to chain your conditions with a logical AND (&&)
//edit: before the nitpicking starts. Yes I am aware, that the order is relevant in his second code snippet, but I choose to ignore it for the sake of the problem.
Related
while analyzing my code using sonarqube i came across 'variableProducerAgreements' is null on at least one execution path in the following code (the foreach loop):
however, upon looking at it and trying various things, variableProducerAgreements seems to never be null in this foreach loop. during a code review, i'm being told that it can "totally" be null and should add conditional logic to handle it. but i'm not understanding how it can be null and thus not sure how to add a conditional. any ideas?
I can't see a way in which variableProducerAgreements could be null since you have the null guard in place at the top (and assuming you don't have any crazy code in your property getters).
if (userProfile?.ProducerProfile == null)
return result;
The Where and FindAll methods in .NET doesn't return null.
However, it is possible the use of a null-conditional every time you access ProducerProfile is confusing some tools and people. Since you're returning early if it is null, you should remove them:
if (IsActingAsDelegate && userProfile.ProducerProfile.IsInactiveProducer)
{
variableProducerAgreements = userProfile.ProducerProfile.ProducerAgreements.FindAll(ag => ag.IsActive && ag.IsVariableBranchContract);
}
else
{
variableProducerAgreements = userProfile.ProducerProfile.ActiveAgreements.Where(a => a.IsVariableContract);
}
If there was a way for it to be null before the if statement, you would also risk a NullReferenceException when you access the IsInactiveProducer property.
Also, the reviewer should be able to explain his/her reasoning.
I think that there is a specific answer to this.
If I have a command binding
private bool CanExecute(Object args){
// Should this just be null checks?
// Should it also contain logic?
// example:
return this.SelectedObject != null;
// or
return this.SelectedObject != null && this.SelectedObject.Status == 1;
}
private void Executed(Object args){
//Or should logic be reserved for the Executed command
if(this.SelectedObject.Status == 1)
//Do stuff
else
//Don't do stuff
}
It seems redundant to have a can execute method if we do additional data validation within the executed method.
if the logic of your command assumes, that it must not be executed, when some conditions have met, then CanExecute have to check these conditions.
Otherwise, CanExecute must return true.
It doesn't matter, what is the nature of conditions, but you should note, that long running checks may hit UI thread performance.
The way that I see it is that there is a distinction of whether something CAN happen and if something SHOULD happen.
An example of this can be a save button or something. The user may not have rights to save an entity so the action CAN'T happen.
If the user does have rights, all of the required fields may not be filled in so it SHOULDN'T happen.
Its in the semantics.
I have a validation method that I call to validate the fields on my form. I want to put these in an if statement check to see if they return true then in my else statement insert them into my database. i already have the method declared and the insert method declared. How can I write this if statement to check to see if all the validation methods return true?
My method validation calls:
formValidation(firstnameTextBox.Text);
formValidation(lastnameTextBox.Text);
formValidation(usernameTextBox.Text);
formValidation(passwordTextBox.Text);
formValidation(emailTextBox.Text);
formValidation(cellnumberTextBox.Text);
Just use the AND operator (&&)
if(formValidation(firstnameTextBox.Text) &&
formValidation(lastnameTextBox.Text) &&
formValidation(usernameTextBox.Text) &&
formValidation(passwordTextBox.Text) &&
formValidation(emailTextBox.Text) &&
formValidation(cellnumberTextBox.Text))
{
}
As mentioned in the comments, if you want all of the methods to be run (to display the relevant errors for each field) no matter what, and to not stop as soon as it hits the first error, you can use a non-short circuiting AND, which is the & operator.
Alternatively, you could put the textboxes into a collection and act on that collection:
var fieldsToValidate = new TextBox[]{firstnameTextBox, lastnameTextBox, ...}
if(fieldsToValidate.All(field => formValidation(field.Text));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should a function have only one exit-point?
I heard that method must have ideally one (no more) return statement. It is true?
For example what type of method is better?
//1
public Object getResult() {
Object result;
if (someValue != null) { **// NOT null checking**
// initializing result
}
return result;
}
// 2
public Object getResult() {
Object result;
if (someValue == null) { // **null checking**
return null;
}
// initializing result
return result;
}
One of the guidelines of the structural programming is not to use multiple exit points in your function (method). The reason is mainly readability (try to draw an algorithm which has multiple exit points, it won't look very nice). However, today very few people draw algorithms before writing some code and modern IDEs can detect unreachable code etc. Multiple exit point method allows more flexibility, hence you can make a method that returns before the code that would make some side effects if it had continued with execution. Also, this in most times prevents the usage of complicated condition tests and therefore can be more optimal (i.e. faster). Off course how compilers change your code is a difficult question, but I presume that most of them make from your single exit method a multiple exit method. I tend to make single exit methods wherever that doesn't significantly influence performance and/or involves complicated, hard to read, selections (if, switch-case itd.)
If you are using checkstyle in Eclipse then it is definitely one. But there are some situations when it makes writing code more difficult (for example in some recursive methods where you are testing for a base case) if you can have only one return statement in those cases I think that you should use what's best in the context.
So it depends on the context.
How many return statements ideally must have a function?
I'll say only one but not at the cost of readability.
If having more than on return statements improve the readability of code, you should choose to have more than one exit points from a function.
At the end, it depends on personal choice and project coding guidlines.
If i was to choose between the two versions of code you provided, I'll choose 2nd version. For me it is more readable.
I say you can definitely have more than one return statement. If you have the rule "only one return statement", you might end up with this:
if (value != null) {
if (value.fieldA != null) {
if (value.fieldB != null) {
// initialize
}
}
return result;
instead of this:
if (value == null) {
return null;
}
if (value.fieldA == null) {
return null;
}
if (value.fieldB == null) {
return null;
}
// initialize
return result;
I find the second much more readable, easier to debug and probably more efficient in some cases.
In second example will return null and wond read next rules. I add return statements when I'm checking values which function accept, as I don't want to process all function if my values are bad, so I retunr null or throw an exception.
If you have just one return statement; then code looks cleaner.
But there is no hard restriction on number of return statements. So you can have multiple return statements. But this also doesn't mean to have say 10 return statements.
I feel if you have 2-3 return statements; method looks cleaner and easier to understand. If number of return statements increases then its sign that you should perform code refactoring and convert one method into multiple methods.
This is a matter where probably everyone has it's own opinion. But I think there isn't a clear right or wrong answer. I usually don't care about the number of return statements. If there is nu reason to stay in some method, then I return out of it.
> Both are correct. Its depends on scenario of your project.
For Ex:
In Second case of your code, if i have a many number of lines code below this
**if (someValue == null)
{
// **null checking**
return null;
}**
then returning from "if" statement is correct
If you have a very less code like in your first example(code) then setting the return value in each if condition and return it #end is ok
> Refere this also
I have a method Modify() shown below
// Convert SortedList of objects
if (retval) //
{
// Release the database lock
Debug.Verbose(func, "Unloc");
The functionality which i want to achieve is if flag RuntimeUp true and m_reconnectInProgress false that means if(RuntimeUp && !m_reconnectInProgress) i have to do the entire procees in the Modify() method otherwise i need to return 'retval' as false .We will get retval from ClientModify(col) method also which is processed by some other side
If i put check if(RuntimeUp && !m_reconnectInProgress) on the very begginning and down side
else part returning retval = false is sufficient or is there any other convenient way to do that so that we can avoid bad logic
I did above assumption based on this comment obtained"" There is no need to create the list of modified objects[col.Add(dmo);] if the RuntimeUp == false and m_reconnectInProgress ==true. You can just return false at the top of the Modify method that means You can perform these checks at the beginning of the Modify method rather than waiting until the call to ClientModify ""
If I understand correctly I'd just add the lines
if(!RuntimeUp || m_reconnectInProgress)
return false;
At the very top of the method, which I think is a perfectly acceptable way of avoiding running the method if the application isn't in the correct state for running it right then.
However, the comment bit of your question does not mention that it should check for reconnect in progress, so I'm not sure if you should be doing that?