Should throwing exception be the first thing to do? [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 9 years ago.
Improve this question
What is the right way (if any...) to validate user input
This one (first throw the exception):
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item == null)
{
throw new ArgumentException("work flow item must have value");
}
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
Or this one (first do the action):
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item != null)
{
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
else
{
throw new ArgumentException("work flow item must have value");
}
}
Is there any guidelines?

There are no real guidelines or rules, but the first one is often preferred, because you can remove the else, removing one level of indention.
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item == null)
{
throw new ArgumentException("work flow item must have value");
}
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
Less indention makes for code that is easier to understand, especially in scenarios with multiple such checks.
Oh, and when checking a parameter for null you usually throw an ArgumentNullException with the parameter name as the first parameter:
throw new ArgumentNullException("item");

Like commentor stated i would go as follows:
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item == null)
{
throw new ArgumentException("work flow item must have value");
}
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
and doing validation at first is usually my preference. You need to check the correctness or the state or the parameter.

It's exactly the same to me and for as far as I know there are no guidelines to this.
For readability I'd suggest to put the eception first though.
E.g.
if (...) throw new Exception();
do your thing

Related

C#: How to implement keep alive timers for many objects in a proper and efficient way? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What I want to realize is easily explained, but because there are so many different possibilities I'm not really aware of the pro and cons for each possible approach:
In my application there are plenty (say some thousands of communication objects).
When such object is idle for some while (meaning that certain methods are not called), it shall simply be closed (what this means in detail is not relevant here).
I'm thinking of a "timer", associated with each object, which is re-triggered every time I "use" the object. Like:
public void ReTrigger()
{
lock (_some_locking)
{
//Reset the timer
_timer.Stop();
_timer.Start();
}
}
}
Note, my application is heavily using async/await and I would like to use a solution which fits best into this concept. I want to avoid a lot of additional threads just for running a lot of timers.
There are many different timers available:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
System.Web.UI.Timer
System.Windows.Threading.DispatcherTimer
So, which one "fits" best into my concept of using asyncio ?
To put an alternative, would it be better to rely on a background task like
while (true)
{
try
{
await Task.Delay(timeout, _cancellationToken)
... some action when expired ...
}
catch (TaskCanceledException)
{
// we have been re-triggered by "using" the object
}
}
This fits better in my concept, however, in this case I need a new cancellation token after each re-trigger, which is not really nice.
What is the "golden way" way to solve my problem; preferably using async tasks?
Another solution would be a housekeeping task, which cyclically polls all active objects for being expired or not. This would work with just one running timer, but is also not very nice.
Here is a way to keep track of the expiration status of an object passively, without using timers. The last time that each object was used is stored in a private double field, and this field is updated every time the object is used. In case the object has not been used for a long time, the field will take the value double.MaxValue which means "expired", and will keep this value forever. The GetExpired method below handles the complexity of comparing and updating the field atomically and with thread-safety:
public static bool GetExpired(ref double lastUsed, TimeSpan slidingExpiration,
bool touch)
{
// Magic values, 0: Not initialized, double.MaxValue: Expired
double previous = Volatile.Read(ref lastUsed);
if (previous == double.MaxValue) return true;
// Get current timestamp in seconds
double now = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
if (previous == 0D || now - previous < slidingExpiration.TotalSeconds)
{
// Not expired (unless preempted)
if (!touch) return false;
var original = Interlocked.CompareExchange(ref lastUsed, now, previous);
return original == double.MaxValue;
// In any other case that original != previous we've lost the race to update
// the field, but its value should be very close to 'now'. So not expired.
}
else
{
// Expired (unless preempted)
var original = Interlocked.CompareExchange(ref lastUsed, double.MaxValue,
previous);
return original == double.MaxValue || original == previous;
}
}
Usage example:
public class MyComObject
{
private readonly TimeSpan _slidingExpiration = TimeSpan.FromSeconds(60);
private double _lastUsed;
public MyComObject() // Constructor
{
GetExpired(ref _lastUsed, default, touch: true); // Start expiration "timer"
}
public bool IsExpired => GetExpired(ref _lastUsed, _slidingExpiration, touch: false);
public bool TryDoSomething()
{
if (GetExpired(ref _lastUsed, _slidingExpiration, touch: true)) return false;
//...
return true; // The job was done
}
}

How do you end a method from code in another method? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How do I end a method with logic in another method? It seems return only works in the method it is in.
private void BeAmazing (int number) {
HandleNumber(number);
Debug.Log("number is 3 or less");
}
private void HandleNumber(int number) {
if (number > 3) {
return;
}
}
Your inner function should return a result indicating whether it was successful in doing whatever it is supposed to do, like this:
private void BeAmazing (int number) {
if (!HandleNumber(number)) {
Debug.Log("number is 3 or less");
}
}
private bool HandleNumber(int number) {
if (number > 3) {
return true;
}
return false;
}
I have to guess a bit, as your description was insufficient. But I guess that FunctionA calls FunctionB - propably in some form of loop - and that in certain cases things that happen in FunctionB should also cancel the loop in FunctionA, thus ending FunctionA.
The primary way for this is throwing Exceptions. Exceptions will just plow through all brackets, until they find catch block. And the last one is in the Framework itself. There are two articles on excetpion handling, that a link often.
However one rule the mention is to not throw exceptions in situations that are not exceptional. And this case might not be exceptional. Well, for those cases there are out parameters:
void FunctionA(){
bool continueLoop = true;
while(continueLoop){
FunctionB(out continueLoop);
}
}
void FunctionB(out bool continueLoop){
//Set the bool, for out parameters this will change it back in FunctionA
continueLoop = false;
}
Of course there is also the way more common case of Recursion, where FunctionA and FunctionB are either the same, or B keeps calling itself. This is often better then using a loop like this.
Robert McKee has got the question covered, but here are two little examples how
HandleNumber could communicate with BeAmazing using an exception.
Please note that an if is the simplest solution here. The examples below are just to show another possibility.
Example 1
Task: Print the message if number is 3 or less without modifying BeAmazing.
private void BeAmazing (int number)
{
HandleNumber(number);
Debug.WriteLine("number is 3 or less");
}
private void HandleNumber(int number) {
if (number > 3) {
throw new Exception("Number is > 3");
}
}
public static void Main()
{
var p = new Program();
try
{
p.BeAmazing(5);
}
catch (Exception ex )
{
Console.WriteLine(ex.Message);
}
p.BeAmazing(3);
Number is > 3
number is 3 or less
Example 2
Task: Make BeAmazing print different messages if number is >3 or not without modifying the signature of HandleNumber.
private void BeAmazing (int number)
{
try
{
HandleNumber(number);
Console.WriteLine($"This number is amazing");
}
catch( Exception ex )
{
Console.WriteLine(ex.Message);
}
}
private void HandleNumber(int number) {
if (number > 3) {
return;
}
throw new Exception("Number is 3 or less");
}
public static void Main()
{
var p = new Program();
p.BeAmazing(5);
p.BeAmazing(3);
}
This number is amazing
Number is 3 or less

Option in rewriting some nested if statements [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have a method which used some nested if statements, so I would like to know if there is a better way to write the same logic.
For example I would like remove avoid the twice
_typologyRepository.Update(typology);
_typologyRepository.Save();
Could you point me out in the right direction? Thanks
public void Update(Typology typology, string nameOriginalValue)
{
if (typology.Name == nameOriginalValue)
{
_typologyRepository.Update(typology);
_typologyRepository.Save();
}
else
{
if (IsUniqueName(typology.Name))
{
_typologyRepository.Update(typology);
_typologyRepository.Save();
}
else
_validatonDictionary.AddError("Name", errorMessageNameUnique);
}
}
if (typology.Name == nameOriginalValue || IsUniqueName(typology.Name))
{
_typologyRepository.Update(typology);
_typologyRepository.Save();
}
else
{
_validatonDictionary.AddError("Name", errorMessageNameUnique);
}
RedFilter's answer is how it should be written. One other note about your code, though:
Usually, when people do cascading if/elses, they keep everything at the same indentation level. RedFilter's answer is better because you don't need cascading if/elses, but if you did need them, most people would write them like this:
public void Update(Typology typology, string nameOriginalValue)
{
if (typology.Name == nameOriginalValue)
{
_typologyRepository.Update(typology);
_typologyRepository.Save();
}
else if (IsUniqueName(typology.Name))
{
_typologyRepository.Update(typology);
_typologyRepository.Save();
}
else
_validatonDictionary.AddError("Name", errorMessageNameUnique);
}
}

How to know that a void runs? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
want to ask about void type, so I could know that it works or no
in PHP i could have a condition like this:
if(mysql_query($query))
{ bla bla }
else
{ print error }
how to do like that on ASP.NET?
i'm trying like this:
if (k.EditPassword(username.Text, oldPassTxt.Text, newPassTxt.Text) == true )
{
Response.Redirect("sample.aspx");
}
else
{ print error }
but of course, it cannot be like that, because void isn't boolean
Usually void functions that do work that can fail will have some other way of informing you that they failed. Often they will throw an Exception:
try
{
k.EditPassword(...)
}
catch(ApplicationException ex)
{
// print Exception
}
Response.Redirect(...)
Other times they will set a status variable or something:
k.EditPassword(...)
if (k.Result == Result.OK)
Response.Redirect(...)
else
// print error...
Looking at documentation or source code for the conditions you are trying to handle is the only way to know how to handle it.
You can use a literal control and add your text to it. So your code will go something like,
if (k.EditPassword(username.Text, oldPassTxt.Text, newPassTxt.Text) == true )
{
Response.Redirect("sample.aspx");
}
else
{ Literal1.Text = error; }
Literal should be in design file, you can add it from toolbox.
But a better and proper way would be to,
Log it. (You would need a log mecahnism)
Write a unit test :)

Best "not is" syntax in C# [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
It is important to me that my syntax does not make other developers confused.
In this example, I need to know if a parameter is a certain type.
I have hit this before; what's the most elegant, clear approach to test "not is"?
Method 1:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (!(e.parameter is MyClass)) { /* do something */ }
}
Method 2:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (e.parameter is MyClass) { } else { /* do something */ }
}
Method 3:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
var _Parameter = e.parameter as MyClass;
if (_Parameter != null) { /* do something */ }
}
Method 4:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
var _Type = typeof(MyClass);
switch (e.parameter.GetType())
{
case _Type: /* do nothing */; break;
default: /* do something */; break;
}
}
[EDIT] Method 5:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if ((e.parameter is MyClass) == false) { /* do something */ }
}
Which is the most straight-forward approach?
This is obviously a matter of personal opinion and style, so there's no right answer, but I think this is clearest:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if ((e.parameter is MyClass) == false) { /* do something */ }
}
The == false is just more obvious than the !
I would go for 3 if you need the variable later or 1 if you don't need the variable.
2 is ugly because of the empty block.
However I think they all are straight-forward.
I would think just making an extension method would be a clear way of doing it:
public static bool CannotBeCastAs<T>(this object actual)
where T: class
{
return (actual as T == null);
}
You then simply make a check like so:
if(myObject.CannotBeCastAs<SomeClass>())
{
}
Methods 1 and 3 would be my picks, depending on what I actually wanted.
Method 1 "does something" if and only if the passed object is not of the expected type. This means the passed object could be null and still pass.
Method 3 "does something" if the passed object is not of the expected type, OR if the object is null. This is basically a one-pass check that you have a "valid" instance of the class to work with further.
So, whether I wanted 1 or 3 depends on what I was planning to do. Usually, when the variable isn't of the expected type or is null, I want to throw an exception. If I were happy with throwing just one type of exception (say just an ArgumentException), I'd use method 3. If I wanted to check for null separately and throw an ArgumentNullException, I'd use method 1 and add the null check.
Method 2 is functionally correct, but I'd rather invert the if condition as in Method 1, as an if block that does nothing is redundant.
I would never do Method 4. A switch statement taking the place of a simple if-else is unnecessary and confusing, especially in the manner you're using it.
To me, Method 1 is the most straight-forward, both on its own and by convention. This is the syntax I've seen the most if you just need to know if an object "is-a" certain class.
If you actually need to do something with the object "as-a" certain class, then Method 3 is the way to go.
Method 1 is the best in my view. It's very obvious what the code is doing and I can follow right along. Method 2 introduces unnecessary syntax that is easily corrected by Method 1. Method 3 requires me to think more than the other two (marginally, but still!), and it also uses extra space that isn't needed.
Remember code is written for people to read, and only after for machines to execute. Go with clarity every time.
If you want elegance and readability:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
bool isMyClass = e.parameter is MyClass;
if (!isMyClass) // or isMyClass == false
{
/* do something */
}
}
I've always tried my best not to put too much logic in a single line of code, specially if conditions. I think the type check and negation operator might be annoying to parse on first glance.
Method #5 (a different spin)
public static class TypeExtensions
{
public static bool IsNotTypeOf<T, X>(this T instance, X typeInstance)
{
return instance.GetType() != typeInstance.GetType();
}
}
// ...
if(e.parameter.IsNotTypeOf(MyClass)) { /* do something */ } ;
I would be of the opinion that braced functionality should always match whatever brace pattern is in use in your application. For instance, in the case of iteration or conditional blocks, if you use:
If (foo != bar)
{
//Do Something
}
well then this should be how you use brace patterned functionality at all times. One of my biggest bugbears with reading other peoples code (and this is especially true if they use CodeRush or Resharper) is the unnecessary terseness people add for no other reason than to display wizardry.
I am not saying the above is the best brace matching pattern however, use whatever one you feel comfortable with, what I would like to get across is that the pattern does not matter so much as the consistency of its use.
Personally, since C# is a terse language in comparison to, say VB.Net I would use long form statements or assignments (with the exception of var initialising) over more condense syntax to help aid later readability.
I like an approach used by one of the NUnit Assert's:
Assert.InstanceOf<MyType>(objectInstance);
BTW,
If you have a set of checks whether object is of specific type like:
if(objectInstance is TypeA)
{
// ...
}else
{
if(objectInstance is TypeC)
{
// ...
}
}
There should be some design issues like tied coupling between few types, so consider an other approach like injected map of associations or map like algorithm method per type
IDictionary<Type, Func<TParameter>>

Categories

Resources