"Persistence" in C#. How to store objects between procedures? - c#

I have GUI that allows an user to create and modify a point object. I need to store a list of these points to insert at a specific drawing.
Here's how I came up with it:
In the form code, I opened a private property List<Points> and I manipulate it directly inside form code. Is this the correct way to handle?
Something like:
public partial class TesteInterface_AdicionarVertice : Form {
public List<VerticeDNPM> listaVertices;
public TesteInterface_AdicionarVertice()
{
InitializeComponent();
listaVertices = new List<VerticeDNPM>();
}
}
So, what do you think about this design? Is there a better way to do it?
Thanks for all thoughs.
I will make the list read-only. thanks for that idea.
The real thing here is this: I have a button which creates points, and another that creates polygons from points.
I need to have a way to get the List of points at the time the user chooses to create that certain polygon. That is basically what i am asking :P
I though to use a class property (in this case List) to store temp points, until the user creates the polygon. Is this a valid approach?

Sorry for that. The correct code is:
public partial class TesteInterface_AdicionarVertice : Form
{
public List<VerticeDNPM> listaVertices;
public TesteInterface_AdicionarVertice()
{
InitializeComponent();
listaVertices = new List<VerticeDNPM>();
}
}

Assuming that you include the appropriate namespace inclusions and class definitions, then what you have posted is valid and does not clearly violate any best practices (unless you count naming conventions, in which case VerticeDNPM should be VerticeDnpm according to Microsoft's naming guidelines). However, in order critique your approach from a design standpoint, you'd really need to provide more information.

Thanks for all thoughs.
I will make the list read-only. thanks for that idea.
The real thing here is this:
I have a button which creates points, and another that creates polygons from points.
I need to have a way to get the List of points at the time the user chooses to create that certain polygon. That is basically what i am asking :P
I though to use a class property (in this case List) to store temp points, until the user creates the polygon. Is this a valid approach?

I'm not really sure what you are asking. Aside from moving your non-UI code out of the UI, I would change the list creation to a readonly field like so:
public partial class TesteInterface_AdicionarVertice : Form {
private readonly List<VerticeDNPM> listaVertices = new List<VerticeDNPM>();
public List<VerticeDNPM> Vertices {get; set;};
public TesteInterface_AdicionarVertice()
{
InitializeComponent();
}
}

I agree that making your list public is a bad idea as then a consumer of the class can modify the actual list object itself, which is not what you want. Instead you want to expose it as a read-only property thereby allowing consumers to access the list contents.
public partial class TestInterface_ADicionaryVertice : Form
{
private List<VerticeDNPM> listVertices = new List<VerticeDNPM>();
public List<VerticeDNPM> { get { return listVertices; } }
public TestInterface_ADiciontaryVertice()
{
InitializeComponent();
...manipulate list of points here...
}
}
In this way you are modifying a private list of points in your code while still allowing a consumer (presumably something that receives the form as a parameter?) to access the list of points and read through it.
Two additional thoughts:
1) If the only consumer is deriving from this form instead of operating on it (receiving it as a parameter somewhere) then consider making the list protected instead.
2) If you do not want the list to be modified by any consumer (i.e. the list of points can't change once you're done manipulating them) then consider exposing an enumerator for the list instead of the list itself. This way someone can enumerate the points but can't change them.
Example:
public IEnumerator GetPoints { get { return listVertices.GetEnumerator(); } }

If you give a user access to a read-only property and return the original list, then the a consumer could still modify that list. The List is still a reference type, so the property is returning a pointer to the list. A true read-only property will create a copy of the list inside the 'get' and return that instead.

I wouldn't make your list public. Then you never know who is modifying it. Make your list private, then expose it as read only.
You can read more about it here. You can also run your code through FxCop. I'm sure it would pick this up.

Related

What is the equivalent of a C/C++ global variable?

I am new to C#. Come from the C/C++ environment. My application has a List<Model> which is required all over the place, by different classes. The problem is that a copy will not do because this statement:
dataGrid.ItemsSource = myModelList;
requires the original by address. I tried changing some arguments around and passing that particular variable as ref but as soon as it is assigned with an equal sign, I end up with a copy. Correct?
You could make it a singleton.
However a concrete List needed all over the place would make me have a serious think about my design.
At the very least you should consider writing a class to control access to the list (add, remove, clear etc), and making that "global", otherwise you are going to be in deep in the brown stuff, until it hits the fan.
Create a Public Class and have the content you wish to pass declared static within the class. Then just access it as NameOfClass.NameOfMethod()
public class NameOfClass
{
public static RETURNTYPE NameOfMethod()
{
// Your Code
}
}
You can create a public class for it with a public static List inside it. That one you then can access everywhere.
eg
public class FakeGlobal
{
public static List<Model> MyModelList = new List<Model>();
}
or even make it a property with getter/setter.

C#, making public members their methods private

I the following class:
public class Humptydump
{
public Humptydump()
{ }
public Rectangle Rectangle { public get; private set; }
}
in this class the Rectangle class comes from system.drawing,
how do i make it so people cannot access the methods of the rectangle, but can get the rectangle itself?
In your case, it will "just work".
Since Rectangle is a struct, your property will return a copy of the Rectangle. As such, it will be impossible for anybody to modify your Rectangle directly unless you expose methods to allow this.
That being said, it's impossible, in general, to provide access to a type without also providing access to methods defined on the type. The methods go along with the type. The only alternative in those cases would be to create a new type that exposed the data you choose without the data or methods you wish to be exposed, and provide access to that.
If rectangle was not a struct, one possible thing would be deriving it and hiding those methods:
public class DerivedClass : BaseClass
{
new private SomeReturnType SomeMethodFromBaseClasse(SameParametersAsInBaseClassAndSameSignature
{
//this simply hides the method from the user
//but user will still have the chance to cast to the BaseClass and
//access the methods from there
}
}
Are you talking about the Rectangle object specifically, or on a more general term and just using that as an example?
If you're talking on a more general term, this is something that comes up very often in refactoring patterns. This most commonly happens with collections on objects. If you expose, for example, a List<T> then even if the setter is private then people can still modify the collection through the getter, since they're not actually setting the collection when they do so.
To address this, consider the Law of Demeter. That is, when someone is interacting with a collection exposed by an object, should they really be interacting with the object itself? If so, then the collection shouldn't be exposed and instead the object should expose the functionality it needs to.
So, again in the case of a collection, you might end up with something like this:
class SomeObject
{
private List<AnotherObject> Things;
public void AddAnotherObject(AnotherObject obj)
{
// Add it to the list
}
public void RemoveAnotherObject(AnotherObject obj)
{
// Remove it from the list
}
}
Of course, you may also want to expose some copy of the object itself for people to read, but not modify. For a collection I might do something like this:
public IEnumerable<AnotherObject> TheObjects
{
get { return Things; }
}
That way anybody can see the current state of the objects and enumerate over them, but they can't actually modify it. Not because it doesn't have a setter, but because the IEnumerable<T> interface doesn't have options to modify the enumeration. Only to enumerate over it.
For your case with Rectangle (or something similar which isn't already a struct that's passed by value anyway), you would do something very similar. Store a private object and provide public functionality to modify it through the class itself (since what we're talking about is that the class needs to know when its members are modified) as well as functionality to inspect it without being able to modify what's being inspected. Something like this, perhaps:
class SomeObject
{
private AnotherObject Thing;
public AnotherObject TheThing
{
get { return Thing.Copy(); }
}
public void RenameThing(string name)
{
Thing.Name = name;
}
// etc.
}
In this case, without going into too much detail about what AnotherObject is (so consider this in some ways pseudo-code), the property to inspect the inner object returns a copy of it, not the actual reference to the actual object. For value types, this is the default behavior of the language. For reference types, you may need to strike a balance between this and performance (if creating a copy is a heavy operation).
In this case you'll also want to be careful of making the interface of your object unintuitive. Consuming code might expect to be able to modify the inner object being inspected, since it exposes functionality to modify itself. And, indeed, they can modify the copy that they have. How you address this depends heavily on the conceptual nature of the objects and how they relate to one another, which a contrived example doesn't really convey. You might create a custom DTO (even a struct) which returns only the observable properties of the inner object, making it more obvious that it's a copy and not the original. You might just say that it's a copy in the intellisense comments. You might make separate properties to return individual data elements of the inner object instead of a single property to return the object itself. There are plenty of options, it's up to you to determine what makes the most sense for your objects.

Accessing class properties inside the class via the this.PropertyGet

I'm building a C# class for matrices. I actually found something on SO to get started with so I don't have to start from scratch. The guy's class has a private property for the rows and columns of the matrix and a get() and set() property. Sometimes the guy refers to the properties themselves by name mRowCount and mColumnCount or by the this.RowCount and this.ColumnCount inside the class for calculation purposes as seen below (I only added relevant code):
public class Matrix
{
private decimal[,] mInnerMatrix;
private int mRowCount, mColumnCount = 0;
public int RowCount
{
get { return mRowCount; }
}
public int ColumnCount
{
get { return mColumnCount; }
}
}
Sometimes in the code the guy uses the properties by name mRowCount and mColumnCount and other times using this.RowCount and this.ColumnCount instead of the former way. What is the difference? Is one way better and if so with respects to what? Particularly in boolean methods where the methods checks to see if the object/matrix is a diagonal, symmetric or square matrix the developer uses the this.RowCount and this.ColumnCount in the loops that run through the mInnerMatrix[] array that holds the matrix's data. Other times he uses the properties themselves. Can anyone explain why someone might do this or is it a mistake? What should I use and should I use it throughout the entire program?
Technically, the get and set methods can be not that straightforward. For instance if you don't store rows and cols count but instead store rows and total elements, you would have to divide total by rows to get cols:
public Cols {get {return _mTotal/_mRows;}}
This is not the best sample, but you can get the idea. In your simple case there will be no difference whether to use a field or a property (if you actually have set methods but omitted them, otherwise the properties are readonly!). But note that one day you might want to implement some logic in get. Then the code that's using properties would work fine but the code that's using fields would fail.
Outside a class you always have to use properties, if any. In fact, you would declare fields private so that only within the class you can access them. Technically you can use both fields and properties outside class, but that would lead to a chaos.
On the other hand I would disagree that mixing properties and fields access within a class is always discouraged. Sometimes you would really need this access, the easiest sample is when your property is readonly (has only get).
If you defined properties - use them wherever possible, inside or outside class, as they may contain additional logic, not only direct member access.
One valid reason not to use properties (use direct access instead) - in constructor,
every other access should be made using properties.
It's rather bad practice to mix direct access and properties within a class

Acessing an original array from another class C#

I'm working on a game where I have a class for my character and a class to handle the GUI.
In the character class I have an array of structs which hold data about the character's skills. I'm trying to access this array with the GUI class, to display the info about the skills.
To use one class in another one, I would need to initialize a new instance of it, which resets the values I might have changed in the meantime. Is there any way to pass that array? I can't make it read-only because I still have to change the array. The array is also not being modified in the GUI class.
Also, in the future I'm going to save this data in XML or in a database. Is it a possibility to get the info out of these files every time I need them? Instead of having to work with passing the array on and things like that. Or even calculate everything server side?
Thanks in advance!
Simon.
If you want to have one array for the entire program, simply make the array public static. If you want to have that class be able to access the array inside characters that you pass it, make the array public or make a property for which the get part is public.
If your class is not static (which seems not), you can define the array as a property of the character class and have access to array like: myCharacter.Skills.
If you want to have access to your Entities (character class in your case) in multiple projects, you can implement a multi-layer architecture and define your entities in an isolated class library and reference this class library in any project that should have access to you entities.
It is not good practice to pass data in to a GUI directly, if it can be avoided. I would suggest using the Model-View-Controller pattern or the Model-View-Presenter pattern. If you're using WPF, you should look at Model-View-ViewModel.
Basically, you want a class whose responsibility is to maintain the data (whether it be stored in memory, a database, etc.), the view needs some abstraction from the data, and also a means to format it for presentation/display purposes (Presenter).
Here is a brief overview : http://en.wikipedia.org/wiki/Model-view-presenter
Either your character should be static or you should store a reference to your character (or a List<Character> in your GUI class. Furthermore, it would probably be best not to provide direct access to the list of structs that maintains your character information if you just want to print. Your Character class should provide a method(s) for printing out the character data, i.e. character.printCharacterInfo() which will return a string, or maybe character.getCharacterInfo which will return the struct containing the data for that character which your GUI class can use to do whatever it wants.
Are you using structs in Array?
This way, you may be accessing the copies, they are not reference types in C#.
public struct PointStruct
{
public int X;
}
public class PointClass
{
public int X;
}
[TestMethod]
public void TestStruct()
{
var structArray = new PointStruct[1];
var classArray = new PointClass[1];
int x;
x = structArray[0].X;
try
{
x = classArray[0].X;
}
catch(NullReferenceException e)
{
Console.WriteLine(e.Message);
}
classArray[0] = new PointClass();
// It's now ok
x = classArray[0].X;
var point1 = structArray[0];
var point2 = classArray[0];
point1.X = 1;
point2.X = 1;
Assert.IsTrue(point2.X == 1);
Assert.IsFalse (structArray[0].X == 1);
structArray[0].X = 1;
Assert.IsTrue(structArray[0].X == 1);
}
I had googled my problem and was take here, I used the answers here to do mine.
When a user clicked a button I wanted the code to be carried out in another class called Logic. My main class was called MainWindow.
I had an array of colors linked to two rectangles in MainWindow. In order to be able to access the values stored in the array i simply had to do this.
public partial class MainWindow : Window
{
Rectangle[] choice;
SolidColorBrush black;
Became
public static Rectangle[] choice;
public static SolidColorBrush black;
}
in my Logic class to access it I had to do this.
MainWindow.choice[0].Fill = MainWindow.black;
Hope that helps anyone at all.

Design Question - OO food application

Say I have a number of usercontrols, each usercontrol inside a tabitem, inside a window.
For example, let say this is a food collection application. Then we have tabs Fruit, Vegetables and Snacks. Each tab will show a list of food of that subject, and allow the user to add, delete, modify the food in each section. The food is stored in seperate textfiles, i.e. Fruit.txt, Vegetable.txt, Snack.txt
The actual text files might look something like this (vegetable.txt):
Name Carbs Fat
Eggplant 2 1.1
Cucumber 3 0.5
etc
Now this is a large list and there is a load method which pulls all the vegetables out into a List
The question I have is this loadVegetables method is in the code behind file, and I end up repeating this load method all over the place, because I have another of other screens like ReviewAllFood, AddVegetable, etc. along with all the other load methods for fruit and snacks.
This is more of a design question, I'm wondering how I set this up to not repeat this code. I could have a VegetableManager (or something) class where the load method is, but does this actually mean less repeated code? Then in each screen I have to create object of VegetableManager and call its load method anyway. So I guess efficiency wise its no better, but I do achieve a better design.
I think I'm missing something here. It's been a while since I studied cohesion and coupling and I think i'm confusing myself with these concepts at the moment. Appreciate if someone could suggest a design for this situation and explain why they chose it and why its better than how i'm doing it at the moment.
Thanks for reading.
I could have a VegetableManager (or
something) class where the load method
is, but does this actually mean less
repeated code? Then in each screen I
have to create object of
VegetableManager and call its load
method anyway.
The point of doing this is not efficiency (i.e. performance). The point is to encapsulate the details of loading that data into a single isolated object. Say for example that your site gets really big and you decide to move the data storage to a database for scalability and performance. In the existing code as you described, you'll have to go through each user control or page and change the logic of the load method. At the best this is a pain, and at the worst you miss some or copy-paste incorrectly. If the logic is encapsulated into a dedicated object, whose only responsibility is to know how to load the data from somewhere, then you only have to make the change once.
codebehind of user control:
protected void Page_Load(object sender, EventArgs e) {
var veggieManager = new VegetableManager();
VeggieListControl.DataSource = veggieManager.GetAll();
VeggieListControl.DataBind();
}
VegetableManager.cs:
public class VegetableManager {
private static Collection<Vegetable> _veggies;
private static object _veggieLock;
public ReadOnlyCollection<Vegetable> GetAll() {
if (_veggies == null) {
lock(_veggieLock) { //synchronize access to shared data
if (_veggies == null) { // double-checked lock
// logic to load the data into _veggies
}
}
}
return new ReadOnlyCollection(_veggies);
}
public void Add(Vegetable veggie) {
GetAll(); // call this to ensure that the data is loaded into _veggies
lock(_veggieLock) { //synchronize access to shared data
_veggies.Add(veggie);
// logic to write out the updated list of _veggies to the file
}
}
}
Because _veggies is static, there is only one collection of veggies in memory, despite the fact that multiple callers will instantiate VegetableManager. But because it's static, if you have a multi-threaded application (e.g. a website) you must synchronize access to that field across all threads (hence the locks).
This is the tip of the iceberg in terms of good object-orientation. I recommend perusing UncleBob's SOLID principles, and Domain-Driven Design (free e-book).
So, yes you are repeating something, but all you're repeating is a method call, and that is ok to repeat. DRY means to mitigate the duplication of "logical" code, i.e. decision-making and algorithms; simple method calls do not fall under this. However, if you want, you can consolidate logic into a base class do this, effectively isolating the user controls from having to know about VegetableManager, though I think this is object-orientation overkill, or OOO :-)
public abstract class FoodUserControl : UserControl {
protected List<Vegetable> GetVeggies() {
return new VegetableManager().GetAll();
}
}
Then your actual controls would derive from this instead of from UserControl.
Update
Eager-loading VegetableManager.cs:
public class VegetableManager {
private static Collection<Vegetable> _veggies;
private static object _veggieLock;
static VegetableManager() {
// logic to load veggies from file
}
public ReadOnlyCollection<Vegetable> GetAll() {
return new ReadOnlyCollection(_veggies);
}
public void Add(Vegetable veggie) {
lock(_veggieLock) { //synchronize access to shared data
_veggies.Add(veggie);
// logic to write out the updated list of _veggies to the file
}
}
}
Notice this eager-loading version doesn't have to do double-checked locking around the load code in the constructor. Also notice that the load code is in a static constructor, since this code initializes a static field (otherwise, you'd be reloading the data from the file on every construction into the same shared static field). Because veggies are eager-loaded, you don't need to load in GetAll or Add.
I would suggest pulling the vegetables (or whatever it is you're loading) out once when you read the file. Then you store them in some underlying data model. You can bind the list, and whatever other controls you need to, to the underlying data model. The data gets loaded once, but various views can display it.
EDIT: Adding code
List<T> loadObjects(File file, ILineConversionStrategy strategy) {
// read eaqch line of the file
// for each line
T object = strategy.readLine(line);
list.add(object);
return listOfObjects;
}
EDIT 2: Data model
class FoodModel {
List<Vegetable> getVegetables();
List<Fruit> getFruit();
// etc
}
I would use the repository pattern for this. As a start, create one class containing methods to retrieve the objects from each text file:
public class FoodRepository
{
public IList<Vegetable> GetVegetables() { ... }
public IList<Fruit> GetFruit() { ... }
// etc.
}
This class should be the only class in your application that is aware that foods are actually stored in text files.
Once you get that working you might want to consider caching frequently used data to improve performance.
public interface IEatable {}
class Vegitable : IEatable
{ string Name { get; set; } }
class Fruit : IEatable
{ string Name { get; set; } }
public interface IEatableManager
{
List<Vegitables> LoadEatables(string filePath);
}
public class VetabaleManager : IEatableManager
{
#region IEatableManagerMembers
public List<Vegitable> LoadVegs(string filePath)
{
throw new NotImplementedException();
}
#endregion
}
.
.
.
There are several things you need to consider for using a design like above
Dependency Injection pattern
Continuous Integration
DRY
and a must read:
How can I practice better
object-oriented programming?

Categories