Singleton List in Abstract Class ... Am I doing it wrong? - c#

I'm loading in lots of parts that need to be assigned materials.
I have a list of Materials that I don't want to run to the database each time to get and thought that putting them inside an inherited base might make it easier for me to carry around.
public abstract class StoreBase : SecurityBase {
internal static IEnumerable<AppEntities.Material> materialsList { get; set; }
internal static IEnumerable<AppEntities.Material> MaterialsList {
get {
if (materialsList == null) {
materialsList = MaterialService.Get().Result;
}
return materialsList;
}
}
Now anytime I need to load it.. I just call
var mats = MaterialList;
However, I'm loading in thousands of parts at a time, and my material list is almost 3k items.
Suspicious that this is causing me to have some memory problems, as I can really only load in a few thousand parts before it bottoms out. (x parts times 3k seems to add up fast)
I know there has to be a better solution, but don't know how to achieve without then blowing up the database with queries.

Related

Is it ok that 2 objects reference each other?

I'm making a chess game in C#. I've got 2 classes, Field and Piece:
public class Field
{
// the piece that is standing on this field
// null if no piece is standing on it
public Piece piece { get; set; }
}
public class Piece
{
// the field this piece is standing on
public Field field { get; set; }
}
When a piece moves, this method is called (in class Piece):
public void Move(Field field)
{
this.field = field;
field.piece = this;
}
This doesn't seem to be good coding, because everytime I change the field property, I also have to change the piece property for that field. I do need both properties though, because elsewhere in my code, I need them both to do checks etc (e.g. what's the field this piece is on and by what piece is this field taken).
My question: is this completely ok, is it a bad code smell or is it totally wrong? What would be a good solution to solve this?
Any advice? Thanks in advance!
The problem I see here is that you have Piece.field and Field.piece as public properties. This means that others can set these properties without updating the corresponding one.
Additionally, when you move a piece from one field to another, you don't remove the piece from the previous field, and we allow pieces to move to occupied squares, which will result in multiple pieces referring to the same field, but the field will only refer to the last piece placed there.
To address these, I would make the properties read only (with a private setter), forcing clients to call the corresponding Set or Move method to change them. Then, in this method, we can verify that the field we're moving to is not occupied (if it is, we simply throw an exception - the client must check this first before calling Move), and that we clear the Piece from the Field we moved from.
The validation work can be done in either the Field or Piece class, or both. I put it all in the Field class to simplify things.
Even still, there are problems with this. You can call Field.SetPiece(piece) directly (instead of Piece.MoveTo(field);), which will leave the piece with a null value for Field. So this is only a slight improvement, but not the ideal solution. See below for a better idea.
public class Field
{
public Piece Piece { get; private set; }
public bool Occupied => Piece != null;
public void ClearPiece()
{
// Remove this field from the piece
if (Piece?.Field == this) Piece.MoveTo(null);
// Remove the piece from this field
Piece = null;
}
public void SetPiece(Piece piece)
{
if (piece != null)
{
if (Occupied)
{
throw new InvalidOperationException(
$"Field is already occupied by {Piece}.");
}
// Remove piece from the piece's previous field
if (piece.Field?.Piece == piece)
{
piece.Field.ClearPiece();
}
}
Piece = piece;
}
}
public class Piece
{
public Field Field { get; private set; }
public void MoveTo(Field field)
{
field.SetPiece(this);
Field = field;
}
}
After thinking a little more about this, I think a better solution would be to have a GameManager class that handles all the validation and movement, and then we can make the Field and Piece classes "dumb".
This makes sense because there is a lot more validation to be done before setting a Piece on a Field. Is it ok to move this piece to the location (i.e. if the King is in check and this doesn't block it, then it's not allowed). Is the Field a valid landing spot for the piece based on the piece's move rules (i.e. a horizontal position for a bishop would not be allowed)? Is there anything blocking the path of the piece to get to the destination? Is the destination occupied by another piece belonging to the same player? Many things to evaluate before moving a piece.
Additionally, this would allow us to reuse the Piece and Field classes in other types of games, which may have a different set of rules, and a different GameManager to enforce them.
No! This relates to concept of circular dependency. Although applied for modules, this may very well be seen as precursor for such.
More concretely, this is an ideal example for mutually recursive objects. Conceptually, if you substitute (semi-pseudocode)
public class Field
{
public Piece piece {
public Field field {
public Piece piece {
...
}
}
}
}
That's because the objects are defined in terms of each other. Then theoretically you can
do something like
this.field.piece.field.piece...

Best pattern to ensure clean code when passing variable frequently within class

Say I have a class with a number of methods - some private, some public.
In one of the public methods, I create a list of objects. This is then used across a number of other methods, which have simply been abstracted out to make code simpler.
So I might have:
public class MyClass
{
public void CreateList()
{
List<MyClass> MyList = new List<MyClass>();
... populate list
DedupeList();
ValidateList();
}
void DedupeList()
{
// do something using MyList
}
void ValidateList()
{
// do something using MyList
}
}
I was wondering what the best approach would be in this instance.
Make the list created by CreateList() a class level variable;
Pass the list a parameter to each of the sub-methods.
Ok, so it depends on what you're trying to achieve and what your classes responsibility is.
If you class represents a real thing which represents part of your domain, and which has state, then your private methods act on that state and I would therefore choose the former.
So
public class Basket
{
private IList<string> Contents;
public Basket()
{
Contents = new Contents();
}
public void Add(string Item)
{
Contents.Add(Item);
}
public void Empty()
{
Contents.Clear();
}
}
This is a trite example, but all I could think of.
If however your class doesn't represent an object with state, such as the calculator below which takes some input, acts on it, and returns it without storing anything, then the latter is better.
That said, there are other considerations, such as keeping code clean and easy to read (should be very high on your priority list), limiting the number of parameters etc being passed (any more than three is often regarded as messy). Example below of when I would elect to pass parameters.
public class InvestmentCalculator
{
pubilc IEnumerable<Stock> CalculateInvestmentValue(IEnumerable<Stock> Stocks)
{
foreach (var stock in stocks)
{
var itemValue = GetSotckValueFromMarket(stock);
stock.UpdateValue(itemValue)
AddProjection(stock);
}
}
public decimal GetStockValueFromMarket(Stock stock)
{
//Do something
}
public decimal AddProjection(Stock stock)
{
//Do something
}
}
I hope that this helps
It depends on meaning of the list. You have to find some answers. Should it be a part of the class or just a temporary variable that should live just along the method call? Is it a part of behavior of the class? How about threading? Even you may rethink if DedupeList and ValidateList methods have to be part of this class or do they deserve a separate class?
I recommend you to read "Implementation Patterns" by Kent Beck and "Clean Code" by Robert C. Martin. There are dozens of very helpful tips for these kind of little but frequent cases.

Base Class Distribution Issue

So I'm currently writing an API, but I've hit a road block in construction. The issue is a series of values will constantly be called throughout, which requires a lot of parameters to be constantly pushed into series of classes and methods throughout the API.
Which is not very elegant nor practical. As it will induce a large amount of extra code.
My thought was originally was this:
public class CustomerProfile
{
public string ParentSite { get; private set; }
public string DynamicSite { get; private set; }
public string SiteDb { get; private set; }
public CustomerProfile(string parentSite, string dynamicSite, string siteDb)
{
if (string.IsEmptyOrNull(parentSite) &&
string.IsEmptyOrNull(dynamicSite) &&
string.IsEmptyOrNull(siteDb))
{
throw new Exception("Error Message: + "\n"
+ "Null value exception...");
}
else
{
ParentSite = parentSite;
DynamicSite = dynamicSite;
SiteDb = siteDb;
}
}
}
So my thought was to have a nice class that will set the properties, will act like a container for these repeatable values.
However, my issue seems to come from the next class.
public class Configuration
{
public CustomerProfile profile;
public Configuration(string parentSite, string dynamicSite, string siteDb)
{
CustomerProfile profile = new CustomerProfile(parentSite, dynamicSIte, siteDb);
}
}
This now works throughout the class I would just use profile.SiteDb or another property that resides within it.
But is this really the best approach?
I could use simple inheritance, but I'm not really sure that is cleaner or more efficient. Any thoughts on the matter would be terrific?
Is this approach the more ideal to pass property values from one class to another, as it will be used throughout several and several methods as well. I was looking for the cleanest way to invoke.
So my question is:
Out of all the ways to pass properties, what way is the best and why?
I thought this approach would be best but as I begin to use it
throughout it seems like it may not be the most ideal.
Thank you.

Holding out on object creation

Is there ever a case where holding the necessary data to create an object and only creating it when is absolutely necessary, is better/more efficient than holding the object itself?
A trivial example:
class Bar
{
public string Data { get; set; }
}
class Foo
{
Bar bar;
readonly string barData;
public Foo(string barData)
{
this.barData = barData;
}
public void MaybeCreate(bool create)
{
if (create)
{
bar = new Bar { Data = barData };
}
}
public Bar Bar { get { return bar; } }
}
It makes sense if the object performs some complex operation on construction, such as allocate system resources.
You have Lazy<T> to help you delay an object's instantiation. Among other things, it has thread safety built in, if you need it.
In general, no. (If I understand your question correct).
Allocations/constructions are cheap in terms of performance. Unless you are doing something crazy, construct your objects when it feels natural for the design - don't optimize prematurely.
Yes if creating the object means populating it, and to populate it you need to do a slow operation.
For example,
List<int> ll = returnDataFromDBVeryVerySlowly();
or
Lazy<List<int>> ll = new Lazy<List<int>>(() =>
{
return returnDataFromDBVeryVerySlowly();
});
In first example returnDataFromDBVeryVerySlowly will be called always, even if you don't need it. In the second one it will be called only if it's necessary. This is quite common, for example, in ASP.NET where you want to have "ready" many "standard" datasets, but you don't want them to be populated unless they are needed and you want to put them as members of your Page, so that multiple methods can access them (otherwhise a method could call directly returnDataFromDBVeryVerySlowly)

Static member access

It is likely that I am going about this all wrong, but I have a user control called CategoryControl, there can be many like it, for that reason I decided that many of its functions would be better served as static methods. I wanted to know if there is a "better" way of accessing these methods then passing an instance all over the class. The methods are public static as they will be updated by other methods. The though of making extension methods comes to mind..?
public CategoryControl(UserCategory userCategory)
{
InitializeComponent();
PopulateControl(userCategory, this);
}
private static void PopulateControl(UserCategory userCategory, CategoryControl instance)
{
SetCategoryTitle(userCategory, instance);
SetPercentCorrect(userCategory, instance);
SetQuestionsMissed(userCategory, instance);
SetBackgroundBar(userCategory, instance);
SetForegroundBar(userCategory, instance);
}
Updated::
The longer story is that I have a Panel on the screen, the panel contains relevant user categories. By relevant I mean that the user has the option of changing courses thus displaying a new set of categories. A user can also change the values of a category based on their interaction with the software. So...
A panel shows the categories of a course.
I maintain a list of the active Category Controls in the panel, and the main form tells the panel when to draw a new set of categories.
public void InitializeProgressPanel(UserCategories parentCategories)
{
Contract.Requires(parentCategories != null, "parentCategories is null.");
RemoveAllControlsFromList(_categoryControls);
UserCategories sortedUserCategories = parentCategories.SortByWorst();
int categoriesCount = parentCategories.Count();
int spacer = (Height - (CategoryControl.Controls_Height * categoriesCount)) / categoriesCount+1;
for (int i = 0; i < sortedUserCategories.Count; i++)
{
CategoryControl cc = new CategoryControl((UserCategory)sortedUserCategories[i]);
cc.Left = 0;
if (i == 0)
cc.Top = spacer;
else
cc.Top = (Controls[i - 1].Bottom + spacer);
Controls.Add(cc);
_categoryControls.Add(cc);
}
}
I would certainly not make extension methods if I had a class in hand that I could extend. Remember, the purpose of extension methods is to extend types that you cannot extend yourself.
The question at hand then is, should you say:
class C
{
public void Foo() { ... }
}
or
class C
{
public static void Foo(C c) { ... }
}
I would ask some questions like:
Is the class ever going to be subclassed? If so, should this be a virtual method?
Is Foo the kind of thing that an instance does to itself, or the sort of thing that it has done to it? An animal eats on its own, but an animal is fed by someone else.
UPDATE:
Some more questions I'd ask myself:
Are the properties and whatnot you are setting ever going to change? The less mutability you have in a class, the easier it is to test, the easier it is to reason about, and the fewer bugs you'll have. If the properties and whatnot are never going to change then do not set them in any kind of method. Set them in the constructor and then never worry about them again; they're correct.
Why not make them instance members, and do it like this
private UserCategory _userCategory;
public CategoryControl(UserCategory userCategory)
{
InitializeComponent();
this._userCategory = userCategory;
this.PopulateControl();
}
private void PopulateControl()
{
// to see userCategory you'd do "this._userCategory"
// to see the specific instance you could simply do "this"
SetCategoryTitle();
SetPercentCorrect();
SetQuestionsMissed();
SetBackgroundBar();
SetForegroundBar();
}
Seems better to have the functionality on one of the two classes involved in the interaction, rather than on some third party.
Here are two ways that spring to mind:
CategoryControl could have a public function PopulateCategory(UserCategory userCat)
UserCategory could have a public function PopulateFromControl(CategoryControl ctrl)
If all those operations about title and percent etc need to be separate actions, you'd just follow the model above but have separate functions for each item.
Just a shot in the dark here, but I'd probably try for something more like this:
private void PopulateControl(UserCategory userCategory)
{
CategoryTitle = GetCategoryTitle(userCategory);
PercentCorrect = GetPercentCorrect(userCategory);
...
}
Some questions may help...(?)
What benefit do you perceive in making the methods static? Converting the method to static, you are taking away the implicit passing of "this", and passing it in manually every time. How does that help? (It won't make the code any more efficient, it just means you have to pass 'instance' into every call you make, so you need to write more code)
Does the user category change a lot? If not, rather than passing it in for every call, would it make more sense to make it a member variable?
Would you really want to call all these static methods one by one to change all the different parameters of the control? Look at how the client will use this class and you may find that you can roll all of those options into one or two methods that take a bunch of parameters and apply them all in one hit. (Often if you want to change one setting, you will want to change several settings together)

Categories

Resources