I am developing a silverlight application (C#) in which I use a custom control Square and the following global variables.
Square[,] arrSquare = new Square[customRows,customColumns]
List<Square> lstSelection;
List<Square> lstEditable;
List<Square> lstSetSquares;
List<Square> lstCancelled;
The lists are time and again used for updating purposes.
The arrSquare comes in picture only when I have to update my above segregated lists.
I have two options in my mind:
follow my current architecture of having global variables and not using my primary array arrSquare frequently
Use LINQ (on arrSquare converted to locally declared Lists) in methods so that the local objects get destroyed when method gets completed?
If there is any better way, please suggest that.
Please note, the data that I will be dealing with, will be huge.
The question should not be about global vs local variables, it should rather be phrased as "is it better to keep cached copies of calculations or to produce them on the spot as needed?".
Since your dataset will be huge then obviously performing all calculations on demand is a no-go, so that question is easy to answer.
Related
I am wonder what is best to do.
I have main function with iteration loop.
For each item in the list I need to get data from the db by using NHibernate.
There are sub functions which are called in the iteration loop body.
In each sub function I need to use data from the item association tables.
for ex. If the Item is Teacher, each func need the Teacher.Students and etc. In my case the record list include many items.
So my question what is better:
1 - To send the Teacher.Students to each sub func.
or 2 - Declare a class variable that all the func know it and it will initialized on each iteration.
Thank in advance!
Imagine you would maintain the code, but somebody else wrote it. It would be much easier for you to understand what a function does if you see what it is receiving as input. So you know what kind of data a function processes. You should not use a class variable if you can just call your function with this data as input.
You can read about good programming style at Elements of Programming Style
From there you get:
Use variables at the smallest possible level of scope. One implication of this rule is that you should minimize the use of global variables. There is a place in good programming style for global variables, and that is for a body of knowledge that will be acted on by many sections of the program, and which is in some sense the major essence of that program. Don't use global variables as a convenient means to communicate between two subroutines.
You should avoid using any kind of global variables and always store your data in the smallest possible scope. This is one of the principles of good design.
The code is so clearer easier to understand, maintain, reuse and change. Dependencies are kept low.
Imagine you need to change this code in the future. If you touch a global variable, you might possibly break some code on the other side (as other methods can use the same variable). If it is localizes, you just need to analyse the impact inside of the method.
Besides, the method with parameters is nicelly encapsulated and its signature is self-explanatory. YOu can even possibly reuse it in the future!
UPDATE
There are a lots of resources on internet, here is a good start: http://www.oodesign.com/design-principles.html
In your case the use of global variables clearly breaks the Open-closed Principle:
Software entities like classes, modules and functions should be open
for extension but closed for modifications.
If you use the global variable instead of sending parameter (Teacher.Students), your method is obviously not closed for modifications, as any change to this global variable (not part of the method!) cause potential crash in the method. With the parameter, your method is closed and protected.
I too think on the line of using functions instead class level variables.
I've got a search function that on completion, stores data in a generic list (List<ViewModel>). Up until now, I've been assigning the viewmodel value to a static variable to allow me to re-use the data over any page requests that the user may use.
After some reading today though, it seems that the static variable value can be shared across threads, meaning that there is a possibility if I'm viewing the site, that the static variables that contain my search data could be modified by another user.
In the course of my reading I've seen solutions such as adding [ThreadStatic] attribute to the variable, although this not only didn't work, but was roundly dismissed by my further reading as an improper solution.
Others talked about storing variables in HttpContext.Current.Items, but my understanding of that is that it only lasts for a single request.
So, I'm unsure of the best solution here - ideally I 'd rather not make too many fundamental changes to my application, but in short I'd like to be able to share complex objects across many requests? What is the best method of doing this?
Thanks very much
You can store objects that should be persisted in memory for each user individually in a session (HttpContext.Session) object. Your deployment will of course have to support sessions.
Couldn't you just use the OutputCacheAttribute?
Static variable is a bad choise. You can use sessions or ViewState. As for me - the first one is better. As expample
if (Session["tmp"] == null) Session["tmp"]=new DataSet();
DataSet ds = (DataSet)Session["tmp"];
{
...Do something with ds
}
Session["tmp"] = ds;
You can pass this dataset between pages or handlers, but you have to look after the lifetime of your session
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... :-)
Why do we need reference types in .NET?
I can think of only 1 cases, that it support sharing data between different functions and hence gives storage optimization.
Other than that I could not enumerate any reason, why reference types are needed?
Why do we need reference types in .NET? I can think of only one reason: that it support sharing of data and hence gives storage optimization.
You've answered your own question. Do you need a better reason than that?
Suppose every time you wanted to refer to the book The Hobbit, you had to instead make a copy of the entire text. That is, instead of saying "When I was reading The Hobbit the other day...", you'd have to say "When I was reading In a hole in the ground there lived a hobbit... [all the text] ... Well thank goodness for that, said Bilbo, handing him the tobacco jar. the other day..."
Now suppose every time you used a database in a program, instead of referring to the database, you simply made a full copy of the entire database, every single time you used any of it in any way. How fast do you think such a program would be?
References allow you to write sentences that talk about books by use of their titles instead of their contents. Reference types allow you to write programs that manipulate objects by using small references rather that enormous quantities of data.
class Node {
Node parent;
}
Try implementing that without a reference type. How big would it be? How big would a string be? An array? How much space would you need to reserve on the stack for:
string s = GetSomeString();
How would any data be used in a method that wasn't specific to one call-path? Multi-threaded code, for example.
Three reasons that I can think of off the top of my head.
You don't want to continually copy objects every time you need to pass them to a Method or Collection Type.
When iterating through collections, you may want to modify the original object with new values.
Limited Stack Space.
If you look at value types like int, long, float you can see that the biggest type store 8 bytes or 64 bits.
However, think about a list or an array of long values, in that case, if we have a list of 1000 values then the worst case will take 8000 bytes.
Now, to pass by value 8000 bytes will make our program to run super slow, because the function that took the list as a parameter will now have to copy all these values into a new list and by that we loose time and space.
That's why we have reference types, because if we pass that list then we don't lose time and space to copy that list because we pass the address of the list in the memory.
The reference type in the function will work on the same address as the list you passed, and if you want to copy that list you can do that manually.
By using reference types we save time and space for our program because we don't bother to copy and save the argument we passed.
I am working on some software that should be used for a special type of experiment.
The experiments are performed using:
1) A "Chip" (basically an XY grid of known dimensions).
2) Each Chip contains "Electrodes", identified by their X and Y coordinate on the chip and by a unique ID. Each electrode can also hold or not hold a sample, indicated by a simple bool (it's a biosensing chip).
I have objects that represent this hardware in C#.
I now need to use the hardware in an experiment;
1) I have an "Experiment" which exposes an IEnumerable holding "ExperimentStep" objects.
2) An "ExperimentStep" holds a name, and a limited list of "Electrodes" involved among other things.
Some experiment steps could run concurrently and could change the "HasSample" property of an electrode. Therefore, when I perform an "ExperimentStep" it might be good to know what the initial "HasSample" property is at any one time.
This is where my problem lies;
If I just pass "Electrode" objects to my "ExpermentStep" they will probably be passed by Value... Is it possible to create an IEnumerable that holds references to the unique electrodes so that each time I want to run an "ExperimentStep" the list of "Electrodes" used in that step holds the most recent value for "HasSample"? Should I use pointers for this?? From my limited knowledge of C++ I would expect that this would be trivial in that language (since you work with pointers most of the time). But in C# I really have no clue (and I am not experienced enough).
In c# a class is reference type. This means that if you create list of instances of a class and then also add the instances to another list then its the same items. Each list will hold a reference. So to that effect yes you can up the items using an IEnumberable.
I suspect you don't understand the difference between reference types and value types, and what pass by value really means in C#.
Assuming Electrode is a class, you can modify the properties of an instance of it and those changes will be visible via any reference to the same object.
I strongly recommend you make sure you have a firm understanding of the .NET type system before trying to develop a lot of production code. The consequences of not understanding what's going on can be disastrous.
A couple of my articles on these topics:
Reference types and value types in .NET
Parameter passing in C#
... but I suggest you get a good introductory C# book as well.