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 5 years ago.
Improve this question
I have a class with functions to read data files. When read the class stores this datas in public properties.
After that I write the content of the puplic properties into a database.
Then it repeates. This means I read again datas with this class.
Before it repeates I want to clean the class.
What is the best way to do it?
Is it better to clear the content of the public properties manually or is it better to dispose the class. Maybe this is the more elegant way to do it?
Let's assume your class looks similar to:
public class MyClass
{
public double IntField { get; set; }
public string StringField { get; set; }
}
And your application something like:
public class MyApp
{
public void Execute() {
var myClass = new MyClass();
// set properties
myClass.IntField = 123;
myClass.StringField = "Hello";
// save to DB
}
}
Each time your application runs, it will run the Execute method which will create a new instance of your class. This way all class properties will be empty or "clean" as you call it.
create new method , name it let say "clear_data" , call it before load data from function that do it . also may be you will need call it from destructor to prevent memory leaks (in case you have pointers that point to some allocated memory ).
What about Memento pattern? Might be useful for you:
https://www.codeproject.com/Articles/186184/Memento-Design-Pattern
Or, as already pointed out, you have 3 other good possibilities:
- Create a method Clear() that sets properties to default value,
- If you have some unmanaged resources, you can use IDisposable interface,
- Create static readonly property holding Empty instance of the class and reassign it. But I would go with Memento/Clear way.
Related
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
I want to understand the use of "protected" keyword in the following code (line 3).
public class PlayerData
{
static protected PlayerData instance;
static public PlayerData Instance { get { return instance; } }
public int health;
}
public class GameManager
{
PlayerData.Instance.health = 10;
}
A private field is not accessible from a child class.
A protected field can be.
If the field is protected, we can inherit from this class and use this field instead of the property.
This avoids the use of the getter which is a method, and that is a crazy time consuming via a CPU PROC CALL and RET using the CPU STACK to return the reference.
Thus it is more speed optimized to use the field instance instead of teh property Instance because we directly use the reference without the need of a method call that will slow down the process and the current thread, thus the game.
Approximately ~5x faster, way to speak vaguely, for each usage.
But that said, we must be carefull to not change the underlying object instance, unless we have a good reason. This field could be read-only, but it is not, who knows why. Perhaps to be able to change the object... either it is just an oversight, or this ref is assigned outside a constructor, or can be reassigner at any time.
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 2 years ago.
Improve this question
I am trying to figure out the best way to change an existing class.
So the class is called ExcelReport and it has one method Create(data,headings). This is live and used in many places. Now recently I want to change the method so I can format columns in Excel.
Create(data, headings, columnformats)
So as not to upset my existing programs the best I can come up with is to add another method Create2(data,headings,columnformats) to the class.
I got a lot of suggestions saying I should modify the existing class with a overloaded method, which I did. But does this not break the Open/Close Principle as my existing class was in production?
Should I have created a new class ExcelReport2(and Interface) with the new improved method and passed this into my new program using dependency injection?
OCP
In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification";[1] that is, such an entity can allow its behaviour to be extended without modifying its source code.
Your solution
You will most likely want to create more options later on for this.
And since you asked for an open/closed principle answer we need to take that into account (open for extension, closed for change).
A more robust alternative is to create a new overload:
void Create(CreationOptions options);
Looks trivial, right? The thing is that any subclass can introduce their own options like MyPinkThemedFormattedCellsCreationOptions.
So your new option class would look like this as of now:
public class CreationOptions
{
public SomeType Data { get; set; }
public SomeType Headings { get; set; }
public SomeType[] ColumnFormats { get; set; }
}
That's open for extension and closed for change as new features doesn't touch the existing API, since now you only have to create sub classes based on CreationOptions for new features.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have huge class that implements usage of some client:
public class Client : IClient
{
internal Client(string username, string password){
//login process here
}
//some private methods that make sure connection stays alive, etc
public void Action1(string param1){
//something here...
}
public void Action2(string param1, string param2){
//something else here...
}
}
As it currently is, it's 5000+ lines long mainly because of lots of different public methods.
I'm wondering what is the best practice to properly organize and refactor this, preferably without making method calls more complicated?
Use partial classes and group things into logical sets per each partial class.
Also, if some methods make logical set, consider wrapping them into separate class.
Those 2 should reduce your lines of code per file dramatically.
Usually big class are "hiding" inside other classes (see uncle Bob on "Clean Code").
In your case I'd split the class creating Action classes and making some machanics that lets the Client use some sort of IAction or BaseAction. Thus splitting the logic of every action into a separate class.
To be more precise I'd rather need some more info and code.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
In my program, I have to add new instance of a given class to an ArrayList each time a method is invoked. My code looks like.
public class A
{
List<Object> myList = new List<Object>();
void resetMyList()
{
myList.Clear();
myList.Add(new B());
// Add more strings
// Call other methods
// ...
// Get a list of strings
}
}
public class B
{
public override string toString()
{
return "I'm B";
}
}
One of my colleague suggested to add new property to class A that refers to one instance of class B. So class B will only be created once and stay in the memory. With this solution, we can avoid to make the garbage collector works on creating and deleting new instance of B. Here is his code:
public class A
{
List<Object> myList = new List<Object>();
private B b = new B();
void resetMyList()
{
myList.Clear();
myList.Add(b);
// Add more strings
// Call other methods
// ...
// Get a list of strings
}
}
So which suggestion is better, design and performance wise?
Edit: Please I know that using:
Using List is better than using ArrayList
Codes are not equivalent
I just want to keep the example simple and my concern is about design and memory. Whether to add private member and keep it in memory or create new instance each time and avoid extra members.
Any way I will change the code to use List
Well, First of all - these codes are not equivalent - While in the first code you create a new instance of B every time you clear the ArrayList, in the second one you use the same instance of B all the time. This means that any changes made to this instace (assuming that B is not immutable) will be "canceled" every time you clear the ArrayList in the first code, but persist in the second one.
As to the question of which one is better "performance wise" - It usually depends on so many factors that it's almost always impossible to answer with complete confidence. In fact, it's so hard to answer this question correctly that Eric Lippert wrote an entire blog post about it - and if it's hard for someone like him to answer - it's hard for anyone (unless your name is Jon Skeet :-))
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 8 years ago.
Improve this question
I am working with C#.NET and basically have a page containing many areas.
In my code-behind, I basically want to be able to do something like:
bool result1 = MyClass.Section["area1"].Process();
bool result4 = MyClass.Section["area4"].Process();
I need to write a class that would call some kind of "Process" method and be able to have it accept a parameter like "area1" inside that method.
Any help on getting me started with this would be greatly appreciated, thank you!
Following the normal .NET naming conventions I'll assume you mean, by your example, that MyClass is being referenced statically rather than by instance (which may not be a big change). Given that assumption, it appears you have a class like:
static class MyClass
{
public static IIndexer Section { get; }
}
IIndexer in this case could be any type that implements an indexer property that takes a string and returns a type that has a method named Process which in turn returns a bool. IIndexer could theoretically look like:
interface IIndexer
{
ISomething this[string] { get; }
}
Next we'll fill in the ISomething blank above with a simple IProcess interface so we don't have to know anything about your specific implementation:
interface IProcess
{
bool Process();
}
So now the indexer above can be changed to:
IProcess this[string] { get; }
Of course, none of the above has any real executable code, but outlines the objects necessary to do what you're after. Now when you go to run your code using your fulfilled contracts the call chain is pretty simple:
bool result1 = MyClass.Section["area1"].Process();
// MyClass.Section > IIndexer.this[string] > IProcess.Process
To POC the idea, a good way to mock the IIndexer implementation might be to use Dictionary<string, IProcess> as it'll give you a usable indexer for your purposes.