Static values vs passing parameters - c#

I have a situation where I have to pass a List<> across 2-3 independent classes up and down the class. Right now I'm mostly passing the list using parameter so all 3 classes gets the list. Should I use a static list instead of passing List all over the classes to simplify the code like Class23.ListObjects.Add() and then release the static values once the operation is done so the next operation starts with an empty List. Right now it feels like the parameters are getting a lot and I'm getting confused if the list has the right values, forgetting to pass the list to the next class, etc. What do you think?

I would suggest you create a new class that represents the combined operation performed by the various classes (a "context" class, if you will). Values needed to perform the operation can be held as instance variables in that context, along with instances of the classes used in performing the work.
That way, you avoid passing stuff around (as code evolves, this can get somewhat ugly) while avoiding a "global" variable. Data is in exactly the scope it needs to be, and is disposed when the overall operation is complete.

In Coding practices, it is bad to have static or Global variables and passing through parameters is considered good.

If you use a static parameter, you run the risk of getting corrupted data if those functions are used in multiple places in your code, especially if threading is involved.
For instance, suppose Class A needs to use your functions that act on your static list. Before those functions are completed, Class B tries to use them as well, causing the list to get data from both calls, since the same static list is used in both cases.

Related

Is there a way to force a method to inherit a scope from it's caller?

If I have a method outside it's callers scope that does a few things, and I have to call this method multiple times in multiple places. Is there any way to make the entire scope of the caller available to the method without passing parameters and also without using global variables? Like if I need it to have an access to a List, an entity framework context
Instead of
myMethod(string _string, List<string> _stringList, EntityContext _db)
{
//log _string to a database table
//add _string to _stringList
//etc.
}
Is there a way I can just pass the _string and make the method inherit the scope as if I'm just writing the same three lines of code everywhere I call this method? It seems a lot cleaner to call myMethod("foo") than myMethod("foo", stringList, MyEntities).
I could create a class, instantiate it, and call the class, but I'm just plain curious if scope inheritance or scope passing is a thing.
Absolutely don't do that. If you have a context you need to pass, use a class to represent the context needed, but don't try to handwave it away and hide it. It makes for unmaintainable code full of interdependencies.
In fact, the "bother" or "overhead" of passing the context object around is a good thing: it points out that having dependencies between the elements of your software project is not free. If you think that writing out the extra parameter is "too much work", then you're missing the forest for the trees: the dependency thus introduced has a much higher mental overhead than the mere mechanics of typing an extra parameter. After you pass that context a few times, typing it will be second nature and have 0 real overhead. The typing is cheap and doesn't require thinking, but keeping in mind the dependency and how it figures in the design of the overall system is anything but.
So: if you are trying to argue that introducing the dependency is worth it, then you have to back it up with actions and actually pass the context object around. The real cost is in the dependency, not the typing. Otherwise, it's a case of "talk is cheap" :)
One way of decreasing the apparent "cost" of passing such context objects is to upset the balance and make the context object actually do something, besides just carrying data. You would then use the context object to manipulate the objects for you, instead of calling the methods on the objects. This sort of "inversion" is quite handy, and often results in better design. After all, the presence of the context indicates that there's an overarching common state, and that perhaps too much functionality is delegated to the "end object", making it intertwined with the common state, whereas it may make more sense in the context object, making the end object less dependent on the presence of any particular external state.
You'd want the context to have methods that require "seeing the big picture", i.e. being aware of the presence of multiple objects, whereas the "leaf objects" (the ones with myMethod) should have methods that don't require the context, or that are general enough not to force any particular context class.
In your case, myMethod perhaps instead of working directly on an EntityContext could generate a functor or a similar action-wrapping object that performs the action, and this could then be applied by the caller (e.g. the context) to execute the database action. This way later it'll be easier to centrally manage the queue of database operations, etc.
When I refactor large projects, this sort of a "context inversion" comes in handy often, and the need for such patterns is very common. Usually, as large projects grow, the "leaf classes" start up lean, and end up acquiring functionality that belongs at a higher level. This is why using good tooling to explore the history of the repository is an imperative, and it's equally important that the entire repository history is available, i.e. that it was properly imported to git. I personally use DeepGit to trace the history of the code I work on, and find such tool indispensable. DeepGit is free as in beer for any use, and if you're not using a tool with similar functionality, you're seriously missing out, I think.
The need to pass contexts around is usually the indicator that a higher level has to be designed and introduced, and the "leafs" then need to be slimmed down, their context-using functionality moved out into the higher level. A few years down the road yet another higher level ends up being needed, although there are projects so far gone that when you just refactor them to make sense of the code base, two or three additional layers make themselves apparent!
I know of 2 ways that can be done. Consider you have the following method:
static void myMethod(string _stringA, string _stringB, string _stringC)
{
Console.WriteLine($"{_stringA},{_stringB},{_stringC}");
}
Create an overload method in the class. For example you could create an overloaded method like:
static void myMethod(string _stringA)
{
myMethod(_stringA, "stringB", "stringC");
}
The second way (which I would not advice it) is doing it the functional way like Javascript does (by using delegates):
public delegate void MethodDelegate(string _string);
static MethodDelegate mMethod1;
static MethodDelegate mMethod2;
static void Main(string[] args)
{
mMethod1 = delegate (string s) { myMethod(s, "method1-str-a", "method1-str-b"); };
mMethod1("str1");
mMethod2 = delegate (string s) { myMethod(s, "method2-str-a", "method2-str-b"); };
mMethod2("str2");
}

Refactoring if-elseif block to hash and classes

I'm working on the legacy asp.net code (however it was converted to newest .net version), I encountered file which contains 15 500 long if-elseif block (with 700 conditions). Each condition is of the same structure:
if(a == "aaa")
{
.....
}
else if(a == "bbb")
{
....
}
.....
I think it needs to be refactored. I want to split the code from each block into separe classes, name them as "aaa", "bbb", ... and use Dictionary or Hashtable to store references to them. It would probably have an Interface with method execute() with the certain return type. The problem is that I think instantiation of each class and storing the objects to hash table would take some time and I believe that performancewise it would be worse thing (for each request constructing hashtable). It would have to store total of 700 objects and then it would retrieve only one object. My questions are:
Is there any better way of solving such a problem? For example, maybe I shall store classes instead of objects, and then use reflection to instantiate class and call its method?
How painful it would be performance wise to apply such design (dividing if/else if blocks into classes -> add objects (which implement certain interface) to dictionary --> take one object from dictionary
Let's say I put all the classes to folder F, how could I retrieve all the classes and add them to dictionary
Any suggestions, other ways to solve the problem?
Well, if you don't need instance variables, I would recommend a static class with each of these as a separate function. Then you can define a compatible delegate method, and store references to the functions themselves rather than the classes. Since they'd be executed in a static context, there would be no need for class instantiation.
It would require a bit of memory to load up the hash map, but after that the footprint would be negligible.

How to keep track and manipulate a variable using multiple classes - c#

i am building a sort of program that generates a random list of word according to a database.
I Made a class that deals with the word selecting and handling (a random select function, a connect to the database function etc..)
I have 3 variables that indicate the last 3 words chosen.
how do I use a funcion on the form1 (button 1 press), to manipulate the same 3 variables, without creating them from scratch everytime (what happens now...)
To make myself clearer:
accualy what I need is to know how to keep track of a variable between multiple classes.
I might be using the whole classes thing wrong... I am now triyng to get the grasp of it.
Thank you very much,
Barak.
Your two options as I see it are:
1) an instance of a class that holds those variables that can be passed around
You may want to use the singleton pattern for this class if you want to make sure there is only ever one of them.
2) A static class with static members holding this information.
It may be that your entire random word class could be static. In this case you'd just call the methods and properties on that class to generate and access your words.
Also I would suggest that you may want to consider a collection to hold your words rather than three separate variables. It will of course depend on your implementation so I will mention it just inc ase you haven't thought of it and I'm not saying you definitely should. :)
I would avoid static or Singletons just for this purpose - they're not good habits to pick up for simple object oriented scenarios.
Encapsulate the state variables in a class, which you instantiate first, then pass by reference into the form and/or data fetch logic.
Key to this is understanding the concept of reference - your form and fetch logic will see the same instance of your state class, effectively sharing it.
If you implement the "variables" as properties on the state class, you can use events to notify other parts of your code when the word states change.
Consider also clearly defining the possible interactions (interfaces) on the state class. One aspect seems to be to add a word, another to pull out statistics based on the added words. The state class can accommodate all this, and provide a nice place for future extensions.
Try to think in terms of public interface methods/properties, while keeping "variables" (i.e. fields like counters or collections) private.
I also agree that your post should be improved with snippets of actual code - help us helping you.
And I hope your code is not being used to generate spam mails/posts... :-)

Looking for advice on thread safety using static methods to 'process' a class instance

I have recently inherited a system that uses a very basic approach to processing workitems, basically, it does them one by one. To be honest, up until recently this worked well. However, we are looking to implement a similiar process for another type of workitem and I have been looking into Task Parallel Library and think that will fit the bill. However, I have some concerns about Thread Safety and to be honest, this is an area that I lack knowledge, so I am asking only my 2nd question on here in hope that someone can give me some good points as I have yet to find a definitive yes or no answer for this.
So we have our 'WorkItem' class
public class WorkItem
{
public int Id {get; set;}
public string data { get; set;}
}
A List<WorkItem> will be generated and these will then be processed using a Parallel.Foreach loop.
The Parallel.Foreach will call a private method, which in turn will call static methods from another assembly;
//Windows service that will run the Parallel.Foreach
private int MainMethod(WorkItem item)
{
item.Data = Processor.ProcessWorkItemDataProcess1(item.data);
item.Data = Processor.ProcessWorkItemDataProcess2(item.data);
SendToWorkFlow(item);
}
public static class Processor
{
public static string ProcessWorkItemDataProcess1(string data)
{
//Process it here
return string
}
public static string ProcessWorkItemDataProcess2(string data)
{
//Process it here
return string
}
}
And so on. All of these methods have logic in them to process the WorkItem instance at various different stages. Once complete, the MainMethod will send the processed WorkItem off to a Workflow System.
We will be processing these in batches of up to 30 in order not to overload the other systems. My concerns are basically the potential of 30 instances of WorkItem accessing the same static methods could cause some data integrity issues. For example, ProcessWorkItemDataProcess2 is called with WorkItem1.Data and is subsequently called with WorkItem2.Data and somehow WorkItem2.Data is returned when it should be WorkItem1.Data
All of the static methods are self-contained in so far as they have defined logic and will only (in theory) use the WorkItem that it was called with. There are no methods such as DB access, file access, etc.
So, hopefully that explains what I am doing. Should I have any concerns? If so, will creating an instance of the Processor class for each WorkItem solve any potential problems?
Thanks in advance
The scenario you describe doesn't sound like it has any blatant threading issues. Your worries about a static method being called on two different threads and getting the data mixed up is unfounded, unless you write code to mix things up. ;>
Since the methods are static, they don't have any shared object instance to worry about. That's good. You have isolated the work into self-contained work items. That is good.
You will need to check to make sure that none of the static methods access any global state, like static variables or properties, or reading from a file (the same file name for multiple work items). Reading of global state is less of a concern, writing is what will throw a wrench in the works.
You should also review your code to see how data is assigned to your work items and whether any of the code that processes the work items modifies the work item data. If the work items are treated as strictly read only by the methods, that's good. If the methods write changes back to fields or properties of the work items, you will need to double check that the data in the work items is not shared with any other work items. If the code that constructs the work item instances assigns a cached value to a property of multiple work items, and the static methods modify properties of that value, you will have threading conflicts. If the work item construction always constructs new instances of values that are assigned to properties of the work item, this shouldn't be an issue.
In a nutshell, if you have multiple threads accessing shared state, and at least one is writing, then you need to worry about thread safety. If not then you're golden.

Static Method Confusion

I am working with Asp.NET and I have a class named PathFinder which has methods like StyleBarPath(string BrandId,string ProductId) which returns for example a combination of path including brandId and productId and also there are such methods in the same class.
What I am thinking to make them static methods to invoke them easily in every where by saying PathFinder.StylePath("1","2"); to use the returned values inside a user control.
But since I am working too much these days, what I know is getting complicated for some reasons. Anyways, here is my question :
Since I am using inline coding on a lot of places like <a href='<%=PathFinder.StylePath("1","2")%>'></a>, I don't want to create a lot of instances by doing this <a href='<%=new PathFinder().StylePath("1","2")%>'></a> by declaring the methods not-static.
But I am afraid of changing the methods returns values because defining the methods static. I mean when a client calls this method, it wouldn't affect the other clients who invoke the same method at the same time?
They would have different call stacks right?
Lets say :
client one invokes the method with these parameters -- {brandId:2,productId:3}
client tow invokes the method with these parameters -- {brandId:3,productId:4}
This actions happens near the same time when the server processing their requests. What I want to learn is whether the invocations affect each others and change the returning values of each other since they are defined static.
Thanks for reading so far and being a helper :)
I just don't want the clients see path/1/2/ while they are waiting for path/2/3/
Some Notes about the question :
Is it the same for static fields?
You can call a static method safely from multiple threads simultaneously and at separate times given the following:
The static method does not access variables outside of itself, or those variables are also thread safe.
The static method does not create side effects which are not thread safe.
If your method is what it looks like it is, you're simply taking some inputs adjusting them and returning the result without accessing anything outside of the function. That would be completely safe.
Static fields are not the same as methods at all. It is one copy of a variable. Any changes to that static field will affect everything else that uses it.
In C#, static means (in layman's terms) there is one copy.
If you provide arguments to the method, and you return a value based on those parameters only, then you will be perfectly safe.
The only time you might run into problems is if your static method uses any static variables to store data between calls, since that could make call-1 change the value of call-2.
From the example you gave, you are safe.
As for your question about static fields, each caller can see the same static fields, since those are shared between instances. Keep that in mind while programming!
This should answer most of you questions
http://odetocode.com/Articles/313.aspx
As I understand it, static methods are thread safe, but not static properties

Categories

Resources