C#/.net Reuse code chunks [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
In my project, there are a lot of code chunks that a reused under different conditions. These chunks are just a few lines of code. The calls of these chunks are spread all over the program and some of theme depend ob which mode the program is running.
I now want to provide this code in a easy to access way with a good performance.
I've two attempts in mind.
a) Create a static class with functions, each containing one chunk of code.
b) Creating several small classes (components) each with an execute method holding one chunk of code.
I'm not sure which is a clean way to handle that situation or if there is any best practice approach.
If you need more information, just let me know.
EDIT: I try to give a short example. The program can run in two different modes. Each mode has the same workflows but they differ slightly in the two modes. One workflow is about loading another assembly and setup communication between both programs. In both modes I have to call functions that are not needed in the other mode. Also this calls appear in other parts of the program.
These chunks are always about calling some functions at the right time in the correct order.
void WorkflowXY()
{
Foo.Do();
Foo.DoMore();
if(Mode.A)
{
//Chunk1, several lines of code, mostly calling other functions
}
else
{
//Chunk2, several lines of code, mostly calling other functions
}
}
void SomewhereElse()
{
//Code
//Chunk2
//more code
}
void InACompletlyDifferentNamespace()
{
//Code
//Chunk1
//more code
}

Avoid Helper classes, if you can. They're clear SRP violations and tend to become dumping grounds for loosely related methods.
I favour your second option. IMHO, classes cannot be too small. One class, one job.
This is worth a read.

Your "chunks of code" is a little bit unclear. Anyway, consider another question concerning static vs non static. It mentions also an extension method. If you do not wanna apply extensions, then another issue could fit for your purpose.

Related

When to create a new function? [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 6 years ago.
Improve this question
I had an argument with my teammate about the following.
We need to parse a symbol in a string to int(it is always a digit), this particular functionality is used in a number of places. So this can be done this way:
var a = int.Parse(str[i].ToString());
The argument was: do we need to create a function for this.
int ToInt(char c) {
return int.Parse(c.ToString());
}
that can be used:
var a = ToInt(str[i]);
My opinion is that creating such a function is bad: it gives no benefits except for typing couple characters less (no, as we have autocomplete), but such practice increase a codebase and makes code more complecated to read by introducing additional functions. My teammate's reason is that this is more convinient to call just one such function and there is nothing bad in such a practice.
Actually question relates to a general: when it is ok(if at all) to wrapp combination of 2-3-4 functions with a new function?
So I would like to hear your opinions on that.
I argee that this is mostly defined based on personal preferences. But also I would like to hear some objective factors to define a convention for such situations in our project.
There are many reasons to create a new sub-routine/method/function. Here is a list of just a few.
When the subroutine is called more than once.
If it makes your code easier to read/understand.
Personal preference.
Actually, the design can be done in many ways of course, and depends on the actual design of the whole software, readability, easy of refactoring, and encapsulation. These things are to be considered on each occasion by its own.
But on this specific case, I think its better to keep it without a function and use it as the first example for many reasons:
Its actually one line of code.
The overhead of calling a function in performance will be far more the benefit you get from making it.
The compiler itself probably will unwrap it again into the one line call if you make it a function, though its not always the case.
The benefit you get from doing so, will be mainly if you want to add error checking, TryParse, etc... in the function.

Using static functions in a asp.net 3.5 website [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 8 years ago.
Improve this question
I am building a ASP.NET webapplication in which I use several classes containing static functions for retreiving database values and such (based on session of user so their results are session specific, not application wide).
These functions can also be called from markup, which makes developing my GUI fast and easy.
Now I am wondering: is this the right way of doing things, or is it better to create a class, containing these functions and create an instance of the class when needed?
What will happen when there are a lot of visitors to this website? Will a visitor have to wait until the function is 'ready' if it's also called by another session? Or will IIS spread the workload over multiple threads?
Or is this just up to personal preferences and one should test what works best?
EDIT AND ADDITIONAL QUESTION:
I'm using code like this:
public class HandyAdminStuff
{
public static string GetClientName(Guid clientId)
{
Client client = new ClientController().GetClientById(clientId);
return client.Name;
}
}
Will the Client and ClientController classes be disposed of after completion of this function? Will the GarbageCollector dispose of them? Or will they continue to 'live' and bulk up memory everytime the function is called?
** Please, I don't need answers like: 'measure instead of asking', I know that. I'd like to get feedback from people who can give a good answer an maybe some pro's or cons, based on their experience. Thank you.
"Will a visitor have to wait until the function is 'ready' if it's also called by another session?"
Yes. It may happen if you have thread safe function body, or you perform some DB operations within transaction that locks DB.
Take a look at these threads:
http://forums.asp.net/t/1933971.aspx?THEORY%20High%20load%20on%20static%20methods%20How%20does%20net%20handle%20this%20situation%20
Does IIS give each connected user a thread?
It would be better to have instance based objects because they can also be easily disposed (connections possibly?) and you wouldn't have to worry about multithreading issues, additional to all the problems "peek" mentioned.
For example, each and every function of your static DAL layer should be atomic. That is, no variables should be shared between calls inside the dal. It is a common mistake in asp.net to think that [TreadStatic] data is safe to be used inside static functions. The only safe pool for storing per request data is the Context.Items pool, everything else is unsafe.
Edit:
I forgot to answer you question regarding IIS threads. Each and every request from your customers will be handled by a different thread. As long as you are not using Session State, concurrent requests from the same user will be also handled concurrently by different threads.
I would not recommend to use static function for retrieving data. This because these static functions will make your code harder to test, harder to maintain, and can't take advantage of any oo principals for design. You will end up with more duplicate code, etc.

is having fewer lines of code always better? [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
Which is best?
private long sumVals()
{
return (dbReturn("NUns") / dbReturn("TSpd")) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
or
private long sumVals()
{
long numUnits = dbReturn("NUns");
long targetSpeed = dbReturn("TSpd");
return (numUnits / targetSpeed) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
Is it better to try and put it all onto one line, so there is less code overall, or to spread it out like in the second one?
Is one or the other quicker? Is there a benefit, eg, while compiling?
Your case is simple, so the first one is OK. But in general, I would go for the second one.
It is important that you (and others) can read the code, but you don't need to save memory (fewer lines of code as well as fewer variables).
Your code will be easier to understand and debug if you choose to write it the second way. You also don't have to have a lot of comments if your variable names explain the code well enough, which makes your code easier to read in general. (I am not telling you to stop commenting, but to write code which does not need trivial comments!)
See this question for more answers.
My rule of thumb is to include enough content to fully describe what the intent of the code is, and no more. In my opinion, assigning values to variables only to use those variables immediately is actually less readable. It communicates the flow of the program well enough, but doesn't communicate the actual intent.
If you renamed the function from dbReturn to GetDatabaseValue then I don't think I can come up with a more expressive way to write this function than:
return (GetDatabaseValue("NUns") / GetDatabaseValue("TSpd")) * 60);
This communicates the intent perfectly (notwithstanding the fact that I don't know what "NUns" and "TSpd" mean). Fewer symbols means fewer things to understand when reading the code.
Full disclosure: Including extra symbols does improve debuggability. I write this way when I am first building a function so that I can track down where things go wrong. But, when I am satisfied with the implementation, I compress it down as much as possible for my and my co-workers' sanity.
As far as I can tell, there would be no run-time performance gain achieved by either approach. Compilers are awesome - they do this inlining without your knowledge. The only difference is in the code's readability.
To me, longer is always better. Modern compilers will shrink most code to be very fast. However, being able to maintain code through lots of comments and easy-to-read code is hugely important.... especially if you are one of those guys who have to maintain someone else's code!
So, my vote is the longer version (with a comment explaining what you are doing too!)

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.

General method placement [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
Is it best practice to place method bodies before or after they are called ? I generally place them after; interested in what others are doing ?
I prefer after. The reason for this is because it makes the flow of your code more logical. Code flows from top to bottom anyway, so it's logical that methods called appear after the current method.
This has the added advantage of the entry point of your program/class being at the top, which is where you start looking anyway.
When developing Java, I place the method bodies after they are called. This will typically result in classes that have a small number of public methods at the top, followed by quite a few private methods at the bottom. I think this makes the class easier to read and understand: you just need to read those few public methods at the top to understand what the class does — in many cases you can stop reading once you get to the private methods.
I also note that Java IDEs typically place the method body after the current method when you refactor code. For example in Eclipse, if you select a block of code and click Refactor | Extract Method... it will place that selected code in a new method below the current one.
It is entirely a matter of personal preference. For most people, the code navigation facilities of a modern IDE mean that it hardly makes any difference how the methods are ordered.
The method placement is largely irrelevant to me (of course in case of some static methods that need to be defined before invoked):
The code formatters are usually in place (and running automatically - if not for you, turn them on) which results in the source being ordered nicely by type of the method and then alphabetically, rather without the regard to the method call sequence
I use the modern IDE, where finding the proper method is done in a different way than sequentially going through the whole source

Categories