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?
Related
Context: C#, WPF, MVVM
In my viewmodels I have been using initialization logic for some of my properties that is basically a check to see if the backing property is null and, if so, initialize it. Finally, return the backing property. Here's an example for list that allows a user to select items to filter by:
List<CBPicklistString> _clientClassificationFilterList;
public List<CBPicklistString> ClientClassificationFilterList
{
get
{
Debug.WriteLine("ClientClassificationFilterList - Get: " + _clientClassificationFilterList?.Count ?? "Null");
if (_clientClassificationFilterList == null)
{
_clientClassificationFilterList = CBPicklists.PicklistStrings(CBPicklists.CLIENT_CLASSIFICATIONS).ToList();
_clientClassificationFilterList.Insert(0, new CBPicklistString() { PicklistStringId = 0, PicklistStringValue = "(All Client Classes)" });
SelectedClientClassificationFilter = _effectiveClientClassificationFilter = _clientClassificationFilterList[0];
OnPropertyChanged("SelectedClientClassificationFilter");
}
return _clientClassificationFilterList;
}
}
My method to apply the filter logic has this code:
if (_effectiveClientClassificationFilter != ClientClassificationFilterList[0])
ActiveClientFilters.Add(new ActiveFilter(_effectiveClientClassificationFilter.PicklistStringValue, "ClientClassification"));
On the initial run, the getter should initialize the list and _effectiveClientClassificationFilter and the if statement should see the comparison as false (objects are equal), meaning that there is no active filter to set. But what I am seeing is that the if statement is behaving as if it sees a true (objects are not equal). When I check the values in the debugger, they are, in fact, equal. It's acting as if there is a concurrency issue where the initialization isn't finishing prior to the comparison. But this isn't a multi-threaded bit of code. Is .Net (or WPF) doing its own thing, here? Is this not a valid way to approach the list initialization? I use this logic paradigm all over the place, (and have been, for years) but this is the first time and the only place I am seeing this funky behavior. There's not a lot of other related code involved.
What am I missing?
I am not sure, but i think the initial value of _effectiveClientClassificationFilter being first in the comparison is used and then the ClientClassificationFilterList is calculated changing the value of _effectiveClientClassificationFilter which i suppose it does not know. So if you reverse the order of condition, it will work correctly.
Instead of
if (_effectiveClientClassificationFilter != ClientClassificationFilterList[0])
use
if (ClientClassificationFilterList[0] != _effectiveClientClassificationFilter)
When you know id is suppose to exist as in the example below, is it good practice to check for nulls?
var submission = _ctx.Submissions.FirstOrDefault(p => p.Id == id);
submission.Done = true;
_ctx.Submissions.Attach(submission);
_ctx.Entry(submission).State = EntityState.Modified;
_ctx.SaveChanges();
If id is supposed to exist you do not check for null. In fact in this case you should query like this
_ctx.Submissions.Single(p => p.Id == id);
The Single method will throw an exception if the item is not found. On the other hand if you are building a WebAPI or have a specific not found page as the id is sent by the client (i.e. can result by something outside your code) you may use SingleOrDefault, then check for null and return appropriate HTTP status code or redirect to the appropriate page. Basically if null results from not validated data you should check and respond accordingly. If the arguments that cause null values are generated by code you should NOT check for null and in fact query in a way that may not result in null because otherwise you are just covering an error in your code.
This is my opinion which is a result of my personal experience. Note that not everyone agrees as is obvious by the different answers of a question I posted on programmers.stackexchange.com some time ago - https://softwareengineering.stackexchange.com/questions/147480/should-one-check-for-null-if-he-does-not-expect-null
You check for null when you cannot say with complete certainty that the object will never not be null.
With that said, you are using FirstOrDefault(). If it didn't find anything in the criteria, it will return you null.
If you feel that there should always be an object, and that there not being an object in question would mean that there is a bug in the program somewhere, then you should use First not FirstOrDefault. Doing this means that if one of your assumptions for this code ends up being violated you will be informed quickly, loudly, and as close to the source of the problem as possible.
FirstOrDefault should be used if it's entirely sensible for the query in question to have no items, resulting in a null value being returned. If you are in this position, the program should work correctly if the query does in fact return null, or whatever else you need to do for the program to function appropriately.
What you want to avoid is putting yourself in the position where a program (incorrectly) assumes a query always has at least one item, but where you use FirstOrDeafult anyway. Here you end up with NullReferenceExceptions, which can take extra debugging work to figure out where the actual problem is (a query with no items that should have had items).
For resilient code you should definitely check and handle to see if submission is null.
You check for the null values, if there is an error to be occured by passing a null value. You can check them in any way, either by using try catch block or using a an if else block.
You can check it, this way you can prevent the errors that might occur by a null value.
FirstOrDefault documents your intention as "the result I'm expecting may not contain items". In such case you should check for null and perform some reasonable fallback. Throwing exception at that point would look strange.
It sounds like in your case you don't expect empty result, so use First and handle exception somewhere higher on call stack or even let default exception handling to happen.
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));
if a condition occurs i have to stop the execution of the current method call and return to the state before the method call .how can i do it .. suppose a i am executing some sample method and a condition occurs and i am prompting a message box and then i want to return to state before this function call
If I'm understanding you correctly, you wish to undo changes you have made to certain variables if some condition is true? If that's the case, you will want to store a copy of all your variables (or your class as a whole). Then, if your condition comes up true, you'll have to revert all those variables to their initial state before returning from your function. It would be something like this:
// In order to clone your variable, you may need to inherit from
// ICloneable and implement the Clone function.
bool MyFunction(ICloneable c)
{
// 1. Create a copy of your variable
ICloneable clone = c.Clone();
// 2. Do whatever you want in here
...
// 3. Now check your condition
if (condition)
{
// Copy all the attributes back across to c from your clone
// (You'll have to write the ResetAttributes method yourself)
c.ResetAttributes(clone);
// Put a message box up
MessageBox.Show("This failed!");
// Now let the caller know that the function failed
return false;
}
else
{
// Let the caller know that the function succeeded
return true;
}
}
A generic rollback functionality on the heap is for me unheard of. But you can use the Command pattern to get undo functionality and use it for rolling back:
http://en.wikipedia.org/wiki/Command_pattern
Essentially you encapsulate an operation in an object that stores enough information of the change that it can undo it. You push that object onto a stack, and when your condition occurs, you go pop all command objects from the stack and undo them. Without more information about your case it's difficult to give more specific information or tell whether this is applicable for you.
Is it an error condition that could have been checked before calling the method? If so, throw an exception.
Otherwise, return something meaningful (e.g. if it's a void function, change it to return a bool, and return false).
This is what exceptions are for. You throw an exception to terminate the function and any caller, until an exception handler is reached.
Note that this should only be done if something exceptional has occurred; exceptions shouldn't be used as a "different kind of" return value, as they are more costly in terms of code size (whether thrown or not) and running time (if thrown) , than normals returns.
As far as returning to the state you had before, this is possible if your code and any library code through which the call proceeded was written in an exception safe manner.
I guess you are talking on the lines of object transactions OR transactional memory.
The least you can do is you can record the state (assignments) of the object being modified and write the old values on it when the condition to assignment fails.
Another solution, differing slightly from those above:
Check for the specified condition a bit now and then in your sample method.
public void MyMethod()
{
some code
if (conditionOccurred == true){ reset to the previous state and exit;}
more code
}
This is probably not according to the book, but it gives quite simple and readable code if you don't use it too often.
I probably don't have to mention that you need save the program's state if you want to be able to return to it, and you need to write some code that returns you to this state.
You can use the Memento pattern to implement object rollback. From here ...
The caretaker is going to do something
to the originator, but wants to be
able to undo the change. The caretaker
first asks the originator for a
memento object. Then it does whatever
operation (or sequence of operations)
it was going to do. To roll back to
the state before the operations, it
returns the memento object to the
originator.
Once you receive the event that indicates that you should roll back, you can undo the change and return to the caller. Here is some info. and links on why you should not use Thread.Abort.
I have a couple of methods that return a bool depending on their success, is there anything wrong with calling those methods inside of the IF() ?
//&& makes sure that Method2() will only get called if Method1() returned true, use & to call both methods
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
Method2() doesn't need to fire if Method1() returns FALSE.
Let me know there's any problem with the code above.
thank you.
EDIT: since there was nothing wrong with the code, I'll accept the most informative answer ... added the comment to solve the "newbie & &&" issue
I'll throw in that you can use the & operator (as opposed to &&) to guarantee that both methods are called even if the left-hand side is false, if for some reason in the future you wish to avoid short-circuiting.
The inverse works for the | operator, where even if the left-hand condition evaluates to true, the right-hand condition will be evaluated as well.
No, there is nothing wrong with method calls in the if condition. Actually, that can be a great way to make your code more readable!
For instance, it's a lot cleaner to write:
private bool AllActive()
{
return x.IsActive && y.IsActive && z.IsActive;
}
if(AllActive())
{
//do stuff
}
than:
if(x.IsActive && y.IsActive && z.IsActive)
{
//do stuff
}
As useful as they are, sequence points can be confusing. Unless you really understand that, it is not clear that Method2() might not get called at all. If on the other hand you needed BOTH methods to be called AND they had to return true, what would you write? You could go with
bool result1 = Method1();
bool result2 = Method2();
if (result1 && result2)
{
}
or you could go with
if (Method1())
if (Method2())
{
}
So I guess the answer to you question IMHO is, no, it's not exactly clear what you mean even though the behavior will be what you describe.
I would only recommend it if the methods are pure (side-effect-free) functions.
While, as everyone says, there's nothing "wrong" with doing things this way, and in many cases you're doing precisely what the language was designed for.
Bear in mind, however, that for maintainabilities sake, if Method2 has side effects (that is, it changes somethings state) it may not be obvious that this function is not being called (a good programmer will usually know, but even good programmers sometimes have brain farts).
If the short circuited expression has some kind of side effect, it may be more readable to seperate the statements, strictly from a maintenance perspective.
Looks good to me, multiple clauses in the if() block will short circuit if an earlier condition fails.
There shouldn't be any problem.
The normal behavior is that Method1() will execute, and if that returns true Method2() will execute, and depending on what Method2() returns, you may / may not enter the if() statement.
Now, this assumes that the compiler generates code that executes that way. If you want to be absolutely sure that Method2() doesn't execute unless Method1() returns true you could write it like this
if( Method1() )
{
if( Method2() )
{
// do stuff if both methods returned TRUE
}
}
But, I've always observed that your code will run as expected, so this is probably not necessary.
Nothin' wrong.
Actually...I wouldn't name them Method1 and Method2. Something more descriptive. Maybe passive sounding too (like StuffHasHappened or DataHasLoaded)
Looks good to me, but there are some caveats... This is NOT the kind of thing where blanket rules apply.
My guidelines are:
If the method names are short, and there are not too many of them, then it's all good.
If you have too many statements/method calls inside the if statement, you most likely are comparing more than one "set" of things. Break those "sets" out and introduce temporary variables.
"Too many" is subjective, but usually more than around 3
When I say "method names are short" I'm talking not just about the names, but the parameters they take as well. Basically the effort required for someone to read it. For example if( Open(host) ) is shorter than if( WeCouldConnectToTheServer ). The total size of all these items is what it comes down to.
Personally, I would consider
if(Method1() && Method2())
{
// do stuff if both methods returned TRUE
}
to be a bad practice. Yes, it works in the current environment, but so does
if(Method1())
{
if (Method2())
{
// do stuff if both methods returned TRUE
}
}
But will it work in ALL environments? Will future, possibly non-Microsoft, C# compilers work this way? What if your next job involves another language where both methods will always be called? I wouldn't rely on that particular construct not because it's wrong, but because it doesn't solve any serious problem, and it may become wrong in the future