Exit loop coding style [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've got a coding style question. Below are two looping functions that do the same thing but with a slightly different loop exit technique. I just wanted to get a sense of what you guys prefer.
I personally prefer the first. I don't see why I should declare a new variable and break a loop when I know there's nothing else to be done.
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
return someObj;
}
}
return null;
}
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
SomeObj found = null
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
found = someObj;
break;
}
}
return found;
}

Both have different purposes. They are not replacements for each other.
First one comes out from the method
Second one comes out from the loop NOT method.
Let us say if there is some code which manipulates SomeObj after the for loop, then results will differ from first method to second method.

I prefer the first. In general, i prefer early exits from methods as it tends to reduce nesting.

Both approaches could not replace each other in every situation. Suppose you want to execute the code after loop finishes then return could not do that for you and vice versa. In your case both could be used but not in every situation.
Statements after for loop, which you do not want to execute get executed with break
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
SomeObj found = null
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
found = someObj;
break;
}
}
//Statements you do not want to execute get executed with break
return found;
}
Statements after for loop, which you want to execute do not get executed with return
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
SomeObj found = null
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
found = someObj;
return;
}
}
//Statements you want to execute do not get executed with return
return found;
}

Related

TryParse dilemma-Dealing with out parameters [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
I never liked out and ref parameters.When I see them in action they give me a feeling that something is messy about the design.
I thought that the only exception was the so called TryXXX pattern that returns a boolean as the function result (whether everything was fine or something went wrong) and an out parameter for the real result, until I read this article today and It made me think if there's a better pattern to implement this kind of methods.
I thought that we could either have a function that returns more than one result(or as the article says a tuple)
Tuple<Exception,T> TryParseT(object obj)
or a function that accepts a callback function for success :
void TryParseT(object obj,Action<T> success)
The question is , which one is better from a functional design point of view ?
UPDATE :
To rephrase my question , I want to know which of these two functions more complies with Functional Programming principles and why ?
Essentially the problem is that to follow the functional programming approach you should always provide a return value for an input value. So the returning void route isn't the way to go. You need to return a value that can represent success (and hold the successful result) and failure (and hold no result).
The closest to that is where you have returned a Tuple which includes the exception. However you then don't have the 'infrastructure' to deal with the Tuple reliably once you've got it. So the code scaffolding around it will be repeated.
Take a look at this library language-ext. It deals with improving the out problem for TryParse using its implementation of Option<T>.
string inp = "123";
// Attempts to parse the value, uses 0 if it can't
int value1 = parseInt(inp).IfNone(0);
// Functional alternative to above
// Attempts to parse the value, uses 0 if it can't
int value2 = ifNone(parseInt(inp), 0);
// Attempts to parse the value and then pattern matches the result
int value3 = parseInt(inp).Match(
Some: x => x * 2,
None: () => 0
);
// Functional alternative to above
// Attempts to parse the value and then pattern matches the result
int value4 = match( parseInt(inp),
Some: x => x * 2,
None: () => 0
);
The library also allows you to just check that something is valid:
if( parseInt(inp) )
return 1;
else
return 0;
And allows for comparisons without actually extracting the value:
if( parseInt(inp) == 123 )
return 123;
else
return 0;
As well as logical operations:
var allValid = parseInt(x) && parseInt(y) && parseInt(z);
var someValid = parseInt(x) || parseInt(y) || parseInt(z);
And finally LINQ expressions which can often remove the need for if-then-else or matching:
var res = from x in parseInt(inp1)
from y in parseInt(inp2)
from z in parseInt(inp3)
select x + y + z;
It also has TryGetValue extensions for IDictionary, IReadOnlyDictionary, IImmutableDictionary and IImmutableSet that instead return Option<T> and can be used as above.
The most elegant method is
int Parse(string value)
The Tryxxxx methods only exist for an implementation detail named performance. If you are seeking elegance you can use the Parse method and handle any errors by failing fast.
You can instead return a tuple but this will cost an additional allocation on the heap since Tuple is a reference type.
A better solution in terms of performance (if you care) would be aKeyValuePair. But it hides (like tuple) the semantics behind generic data types which is not optimal for code clarity. A better way to signal failure than by defining some convention that the first bool of the tuple contains the failure state is by defining your own data type.
struct ParseResult<T>
{
public bool Success { get; private set; }
public T Value { get; private set; }
public ParseResult(T value, bool success):this()
{
Value = value;
Success = success;
}
}
class Program
{
static ParseResult<int> TryParse(string s)
{
int lret = 0;
if (int.TryParse(s, out lret))
{
return new ParseResult<int>(lret, true);
}
else
{
return new ParseResult<int>(lret, false);
}
}
static void Main(string[] args)
{
string test = "1";
var lret = TryParse(test);
if( lret.Success )
{
Console.WriteLine("{0}", lret.Value);
}
}
}
That approach is still quite efficient and spares you the out parameters at the cost of the allocation of a cheap container object.

running tasks parallely in asp.net [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 9 years ago.
Improve this question
By seeing this solution specified in Divide Foreach into threads sample
I tried to implement it with this code:
foreach (Object vo in arrreclist)
{
msg = String.Empty;
objprocess.GetType().GetMethod("ProcessRecord").Invoke(objprocess, new Object[] { vo });
status = (StatusInfo)objprocess.GetType().GetProperty("status").GetValue(objprocess, null);
if (status.errcode != 0)
{
lngfailedcnt++;
WriteErrorLog();
}
else
{
lngsuccesscnt++;
lngInstanceSuccCount++;
}
lngcnt++;
if ((lngcnt % 10) == 0)
{
if (instanceId == 0)
{
schldr.ModifyJobhistoryForUploadFileRecCnt(Runid, (int)lngTotreccnt, lngfailedcnt, (int)(lngfailedcnt + lngsuccesscnt));
}
else
{
schldr.ModifyJobhistoryForUploadFileRecCnt(Runid, 0, lngfailedcnt, (int)(lngfailedcnt + lngsuccesscnt));
}
status = schldr.status;
if (status.errcode != 0)
{
if (!String.IsNullOrEmpty(Errorlogfile))
WriteErrorLog();
holdInstance = true;
break;
}
//Get Job Status
//If job was terminated then Update Batch and Job history with status as STOPPED
intstatus = schedulersvc.GetJobStatus(Runid);
status = schedulersvc.status;
if (status.errcode != 0)
{
WriteErrorLog();
holdInstance = true;
break;
}
if (intstatus == 1) //STOPPED
{
holdInstance = true;
break;
}
lngcnt = 0;
}
}
And error message is coming for break statement:
cannot leave the body of anonymous method or lambda expression
My major task is to parallelize the following line:
objprocess.GetType().GetMethod("ProcessRecord").Invoke(objprocess, new Object[] { vo })
But other are dependents so how to implement?
First, parallelization often doesn't make sense in ASP.NET. If you have many users accessing your site, you usually care more about scalability (how many users can you serve at the same time), than raw performance for single user.
If that's not your case, parallelization might make sense for you.
Second, you're getting that error, because Parallel.ForEach() is not a loop (as far as the language is concerned). And breaking out of a lambda doesn't make any sense.
To break out of Parallel.ForEach(), you can use ParallelLoopState.Break() or ParallelLoopState.Stop() (read the documentation to find out which one of those do you actually want). To do this, you will need to use an overload of Parallel.ForEach() that gives you that ParallelLoopState.
Third, there is a good reason why Parallel.ForEach() doesn't support ArrayList: it's because you should never use it. If you really want a list of objects, use List<object> to make it clear that you really don't know the type. If you can't (or don't want to) change the ArrayList, you can use .Cast<object>() to make Parallel.ForEach() (and other methods that work with IEnumerable<T>) accept it.
Fourth, I think that parallelizing just the ProcessRecord doesn't make sense. It looks like status returns the status for the last ProcessRecord. And if you execute ProcessRecord in parallel, then it's not clear anymore which one is the last.
Also, you shouldn't think that some method is not thread-safe. You should know that. If you parallelize something that you don't know is thread-safe, you're likely to get hard to debug bugs later on.
Fifth, if you want to parallelize just the first part of a loop, I think the best option is PLINQ. Something like:
var intermediateResults = source.AsParallel().Select(x => Process(x));
foreach (var intermediateResult in intermediateResults)
{
// the rest of the loop
}

c# string tricks/features? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have always hated string parsing, something I am doing a lot of in a current project.
Does c# have and tricks or quick features for strings that would make my life easier? In particular cropping, multiplying or substringing? The end goal here is to take a list of string and turn it into a nice pretty columned structure. Easy, but still, I would it to be python easy.
For example, python has:
>>> a = "I once was a string, then I got mutilated"
>>> print a[20:]
then I got mutilated
or
>>> 'chicken' in 'chicken noodle soup'
True
or finally
>>> 'lol' * 5
'lollollollollol'
There aren't language related features for this in C# like there are in Python. The only real C# language feature with strings is allowing + to be mapped to String.Concat, to simplify (and keep efficient) "a" + "b" + "c" statements.
The String class provides this functionality via methods, however. There is also StringBuilder, which is used for building large strings based on multiple concatenations.
In your example, see String.Substring for slicing and String.Contains for in. There isn't a simple "repeat" style operation like the multiplication in Python.
That being said, it's easy to make an extension method which handles the multiply functionality.
They're different languages - the syntax is different and comparing C# to Python in this way is largely pointless. Also I completely challenge your assertion that the examples you've given are 'easier'.
I don't see how you can get much easier than:
Console.WriteLine("Foo".Substring(1)); //<-- prints 'oo'
Console.WriteLine("chicken noodle soup".Contains("chicken")
.ToString()); //<-- prints 'true'
And for the last one, read this SO: Can I "multiply" a string (in C#)?
Personally, in particular, I hate the idea of multiplying a string - too much ambiguity if that value happens to be '5' - hiding such functionality behind operators smells.
First Question
You can use String.SubString():
string a = "I once was a string, then I got mutilated";
string lastTwentyCharactersOfA = a.Substring(Math.Max(0, a.Length - 20));
// returns "then I got mutilated"
Credit where credit is due: This answer does a nice job of making sure that you don't get an exception if your string has less characters than you are requesting.
Second Question
You can use String.Contains():
string soup = "chicken noodle soup";
bool soupContainsChicken = soup.Contains("chicken"); // returns True
Third Question
You can't override the multiplication operator for the String class. It's a sealed class, and of course you don't have access to the source code to make it a partial class or something along those lines. You have a couple of options that will get you close to what you want to do. One is to write an extension method:
public static string MultiplyBy(this string s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s);
}
return sb.ToString();
}
Usage:
string lol = "lol";
string trololol = lol.MultiplyBy(5); // returns "lollollollollol"
Or if you want to go the route of operator overloading, you can write a custom String class of sorts and then have at it.
public struct BetterString // probably not better than System.String at all
{
public string Value { get; set; }
public static BetterString operator *(BetterString s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s.Value);
}
return new BetterString { Value = sb.ToString() };
}
}
Usage:
BetterString lol = new BetterString { Value = "lol" };
BetterString trololol = lol * 5; // trololol.Value is "lollollollollol"
In general, there's a lot you can do with System.String and System.Text.StringBuilder. And the possibilities are almost endless with extension methods. Check out MSDN if you are interested in learning the ins and outs of it all.
using linq, you can treat your string like a list of chars and do what you want easy enough.
var chickenString = "chicken noodle soup";
var hasChicken = chickenString.Contains("chicken");
// hasChicken = true at this point...

Is it considered readable to call methods inside the IF condition? [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 1 year ago.
Improve this question
Is this way of writing IF conditions considered good coding style in Java and C# languages or not?
if (checkIfIdInFirstRange()){
//call Range1 handling method
}else if(checkIfIdInSecondRange()){
//call Range2 handling method
}else{
//call error handling method
}
I'm wondering about the method inside the IF condition itself, or would it be better to make it like:
int idInRange = getIdInRange();
//handle isInRange
I think this is fine.
Even better is if you phrase your methods like a question, or flows with the if statement
if (thisConditionIsTrue()){
// Do this
}elseif(anotherConditionIsTrue()){
// Do this instead
}elseif(isThisParameterOkay(someParameter)){
// Yeh do this
}
Some hardcore purists will even say that if you have > 3 levels of indentation, your method is too nested and should be split into smaller methods.
Doing this is IMHO good coding practice as long as the method calls don't have any side effects.
e.g.
if checkIfIdInFirstRange() this is OK:
private bool checkIfIdInFirstRange()
{
return firstRange.Contains(ID);
}
But doing this might create confusion:
private bool checkIfIdInFirstRange()
{
SomeStringProperty = "totally new value that no caller would ever expect after a call to this method";
return firstRange.Contains(ID);
}
Another possible solution - depending on the actual type of your problem at hand - could be to define an interface / base class and use polymorphism.
example:
internal abstract class A
{
public void DoSomething(int ID)
{
if(IsInRange(ID))
DoSomethingProtected(ID);
}
protected abstract bool IsInRange(int ID);
protected abstract void DoSomethingProtected(int ID);
}
internal class B : A
{
private List<int> firstRange = new List<int> { 42, 23, 5};
protected override bool IsInRange(int ID)
{
return firstRange.Contains(ID);
}
protected override void DoSomethingProtected(int ID)
{
Console.WriteLine("{0}", ID);
}
}
public class Program
{
public static void Main(string[] args)
{
B foo = new B();
foo.DoSomething(3);
foo.DoSomething(42);
}
}
CAUTION: code written without IDE to hand.
Yes. It would be much more readable if you used just a little whitespace. Bunching it up like that makes it hard to tell where things begin and end and makes else if() look like a function call.
if ( checkIfIdInFirstRange() ) {
//call Range1 handling method
}
else if ( checkIfIdInSecondRange() ) {
//call Range2 handling method
}
else {
//call error handling method
}
Making the extra variable is likely to make code harder to read since you have to define them all before the if/else stack. However, it all depends on the case. Sometimes it might be better to use a variable if you will be using an expensive function many times or if you can make the variable have a more descriptive name than the function.
Actually it is also required if you want to test multiple methods and use short-circuit evaluation.
For instance, this is safe:
if (isResourceAvailable() && isResourceValid()) {
...
}
while this may no be:
bool resAvailable = isResourceAvailable();
bool resValid = isResourceValid(); // can you call that alone?
if (resAvailable && resValid ) {
...
}
It is good style as long as the methods you call don't just do something that would be clearer if it was coded in place:
if ( a > 0 && a < 10 ) doSomething();
is better than
if ( isInRange(a, 0, 10) ) doSomething();
Eh, it's mostly up to the coder but declaring the int is a bit more readable.
It's OK to write methods in the IF condition statement. But if the method will be used more than one time, you should first use a local variable to store the return value and use the variable as the IF condition
You can aim at writing function / method names that will make the code more readable where they are used. Like:
if (idInFirstRange()){
//call Range1 handling method
}else if(idInSecondRange()){
//call Range2 handling method
}else{
Also, usual convention for functions returning bool is that they start with is - isIdInFirstRange
Lastly, try avoiding such if-else ( and switch ) ladder. Try to use Dictionaries in such cases. ( https://stackoverflow.com/questions/6506340/if-if-else-or-switch-case/6506403#6506403 )
Although this practice is not wrong or condemned by any best practices guidelines, if you have more than one call within if condition it can be a bit difficult to know which call refused to enter if statement during a debug session.
if (idInFirstRange() && idInSecondRange()){
//call Range handling method
//if didn't reach this point, who was the responsible (idInFirstRange or idInSecondRange)?
}else if(idInSecondRange()){
//call Range2 handling method
}else{
//call something else
}

What different ways can you write this [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There are some cool and exciting features in .NET 3.5/C# 3.0, and with those features comes some darn interesting ways to write the exact same line of code.
Using the above stated tool set (and by extension .NET 2.0 stuff), what are the different ways the below code snippet could reasonably be rewritten?
string uploadDirectory = "c:\\some\\path\\";
if (Directory.Exists(uploadDirectory)) {
string[] files = Directory.GetFiles(uploadDirectory);
foreach (string filename in files) {
if (File.GetLastWriteTime(filename).AddHours(12) < DateTime.Now) {
File.Delete(filename);
}
}
}
Lambda:
if (Directory.Exists(uploadDirectory))
Directory.GetFiles(uploadDirectory)
.Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12))
.Each(f => File.Delete(f));
Edit: On 2nd thought, you can avoid the security lookups on each File access by using DirectoryInfo and FileInfo instead of the static File methods:
var di = new DirectoryInfo(uploadDirectory);
if (di.Exists()) {
di.GetFiles()
.Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12))
.Each(f=> f.Delete());
}
And for those missing their own Each method:
void Each<T>(this IEnumerable e, Action<T> action) {
foreach (T t in e) {
action(t);
}
}
To make this really crazy, and fit the C# 3.0 theme, let's throw in an anonymous type:
di.GetFiles().Select(f => new() {
Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { }
}).Delete();
But that just doesn't make any sense. ;)
Well, the first bit maps quite neatly to a LINQ query... but there is (deliberately) no ForEach in regular LINQ. We can annoy Eric and add one, though ;-p
So the following uses LINQ and a custom extension method - but we could re-write the exact same code (i.e. the same IL) as:
query syntax (as below)
fluent syntax (.Where().Select() ec)
explicit static (Enumerable.Where(...))
lambdas vs anonymous methods vs named methods (last changes the IL)
delegates with/without the abbreviated (C# 2.0) delegate "new" syntax
generic calls with/without generic type inference (Where() vs Where<T>())
call to File.Delete vs call to x=>File.Delete(x) etc
etc
static void Main()
{
string uploadDirectory = "c:\\some\\path\\";
if (Directory.Exists(uploadDirectory))
{
var files = from filename in Directory.GetFiles(uploadDirectory)
where File.GetLastWriteTime(filename) < DateTime.Now.AddHours(-12)
select filename;
files.ForEach(File.Delete);
}
}
static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
We could write the DateTime code with a custom Expression, but that would be overkill...
However, I doubt we could ever run out of ways of writing it ;-p

Categories

Resources