App resources vs a static variable - c#

in my App.cs i have the following
private static LayoutManager layoutManager;
public static LayoutManager LayoutManager
{
get { return layoutManager ?? (layoutManager = new LayoutManager()); }
set { layoutManager = value; }
}
I need to access this variable from another Library so I defined it in the App XAML so I could use Application.Current.FindResource("LayoutManager"), without having to reference the project that contains the App, because i would get a circular dependency
<Managers:LayoutManager x:Key="LayoutManager"/>
is adding an object to the resources the best option?
what are the best programming practices in such case?

The two methods are essentially the same, the difference is mainly semantic.
As for your first question, adding an entry to a resource dictionary creates a new object, and places it in a dictionary of that scope (App, window, panel, etc.), this applies to anything you place in a resource dictionary, so the real question is what to place there. Resources placed in xaml are usually used by the xaml code (or something that affects it), it usually keeps styles, animations and so forth. You can, of course place anything you like there, but it's less common.
As for the best practice for this situation, I think you'll do better to place the object in a static property, since you try to access it in c#, and not in xaml. It gives you a little performance boost then trying to locate the resource, and you don't have to rely on magic strings, that won't give you a compile time error when if the property changes.

Related

Refactoring; How to make one class ignorant of another?

A Quick Note
This issue does not rely on 3D based code, nor logic; it simply focuses on removing the dependency of one object from another, and I am trying to be as thorough as possible in describing the issue. While having some 3D background will probably help understand what the code is doing, it is not needed to separate class A from class B. I believe this task will be solved with some logical, yet lateral thinking.
Overview
I'm refactoring some old code (written sometime in the early 90s) and there are a few classes that rely on other classes. This question will focus on a single class that relies on another single class (no other dependencies in this case). The project is a DirectX project that simply renders a few objects to the screen for working purposes. I can't really give a thorough description unfortunately; however, I can explain the problem with the code.
There are two classes that I need to focus heavily on, one of which I am currently re-writing to be generic and reusable since we now have a secondary need for rendering.
Engine3D (Currently Re-Writing)
Camera3D
I will explain in more detail below, but the gist of the situation is that Engine3D relies on Camera3D in the Render method.
Engine3D's Current Flow
The current flow of Engine3D is heavily focused on accomplishing a single goal; rendering what the project needs, and that's it.
public void Render() {
// Clear render target.
// Render camera.
// Set constant buffers.
// Render objects.
// Present back buffer.
}
The update code and the render code are all jumbled together and every object that is rendered to the screen, is located in the Render method. This isn't good for reusability as it forces the exact same scene to be rendered each time; therefore I am breaking it down, creating a generic Engine3D and then I will utilize it in my (let's call it Form1) code.
The New Flow
The idea is to make rendering objects to the screen a simple task by making a Draw call to the Engine3D and passing in the object to be rendered. Much like the old days of XNA Framework. A basic representation of the new flow of Engine3D is:
// I may move this to the constructor; if you believe this is a good idea, please let me know.
public new virtual void Initialize() {
base.Initialize();
OnInitialize(this, new EventArgs());
RenderLoop.Run(Window, () => {
if (!Paused) {
OnUpdate(this, new EventArgs());
Render();
}
});
}
protected override void Render() {
// Clear Render Target. context.ClearRenderTargetView(...);
// Set constant buffers.
OnRender(this, new EventArgs());
// Present back buffer.
}
Where OnUpdate will be utilized to update any objects on the screen, and OnRender will handle the new Draw calls.
The Issue
The issue with this is that the old flow (within the render loop) cleared the render target, then rendered the camera, then began setting up the constant buffers. I've accomplished the first in that list rather easily, the second in the list is a simple Draw call with the new flow (and can come after setting up the buffers); but the issue is setting up the constant buffers. The following lines of code require the Camera3D object and I am having issues with moving this around.
ConstantBuffers.PerFrame perFrame = new ConstantBuffers.PerFrame();
perFrame.Light.Direction = (camera.TargetPosition - camera.Position);
perFrame.CameraPosition = camera.Position;
perFrame.CameraUp = camera.Up;
context.AddResource(perFrame);
This variable is then added to the resource list of the render target which must remain in Engine3D to prevent overly complicated drawing code.
There are other objects later in the code that rely on Camera3D's World property, but once I solve how to separate the Engine3D from Camera3D, I'm sure I can take care of the rest easily.
The Question
How can I separate this dependency from the Engine3D class?
A few things I have thought of are:
Create a method that sets the buffers that must be called prior to draw.
Make these properties static on Camera3D as there is always one camera, never more.
Create a method specifically for the camera that handles this issue.
Create a middle man class to handle all of this.
Combine the Engine3D and Camera3D classes.
If there is any confusion as to what I am trying to achieve, please let me know and I will clarify the best I can.
The refactoring you want to do is called Pure Fabrication.
A proposed solution of yours is to:
Make these properties static on Camera3D as there is always one camera, never more.
I suggest that:
Instead of making them static you can create another class (name it StudioSetup) that contains the fields which are needed in Engine3D (and you are looking to make static in your Camera3D);
Populate an object of that class with current values and pass that to Engine3D->Render();
Now the dependency on Camera3D has been replaced with a dependency on StudioSetup object.
This is similar to your "Create a middleman class to handle all of this." solution. However, the middleman does not do anything except work as a one-way courier.

Which one is better to have auto-implemented property with private setter or private field and property just getter?

My question may be a part of an old topic - "properties vs fields".
I have situation where variable is read-only for outside class but needs to be modified inside a class. I can approach it in 2 ways:
First:
private Type m_Field;
public Type MyProperty { get { return m_Field; } }
Second:
public Type MyProperty { get; private set; }
After reading several articles (that mostly covered benefits of using public properties instead of public fields) I did not get idea if the second method has some advantage over the first one but writing less code. I am interested which one will be better practice to use in projects (and why) or it's just a personal choice.
Maybe this question does not belong to SO so I apologize in advance.
The second version produces less clutter, but is less flexible. I suggest you use the second version until you run into a situation that makes the first version necessary and then refactor - changes will be local to the class anyway, so don't worry too much about that!
Generally, writing less code is a good idea. The less code you write, the less bugs you produce :)
Second version is shorter, so I think it's usually better.
The exception is, when the only write access occurs in the constructor. Then I prefer the first version as this allows the field to be marked as readonly.
The second one will pretty much compile down to the first one anyway, so IMO always use the second as it's less & neater code.
The only scenarios I tend to use the first approach are when I want to lazily load a property e.g.
private List<string> _items;
...
public List<string> Items
{
get
{
if (_items == null)
{
_items = new List<string>();
// load items
}
return _items;
}
}
Please go through the following question. IT seems like same ,
https://softwareengineering.stackexchange.com/questions/72495/net-properties-use-private-set-or-readonly-property
For debugging the second is the best. Otherwise you'll have to put breakpoins at each place where you set the field. With the second you put one breakpoint on the set of the property.
Personally I prefer the second version because it is less to write so I can use the time to do more complex coding.... plus in my opinion it promotes lazy development

C# Object construction outside the constructor

When it comes to designing classes and "communication" between them, I always try to design them in such way that all object construction and composing take place in object constructor. I don't like the idea of object construction and composition taking place from outside, like other objects setting properties and calling methods on my object to initialize it. This especially gets ugly when multiple object try to do thisto your object and you never know in what order your props\methods will be executed.
Unforunatly I stumbl on such situations quite often, especially now with the growing popularity of dependecy injection frameworks, lots of libraries and frameworks rely on some kind of external object initialization, and quite often require not only constructor injection on our object but property injection too.
My question are:
Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?
Is ther some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)
Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?
No. Init methods are a pain since there is no guarantee that they will get called. A simple solution is to switch to interfaces and use factory or builder pattern to compose the implementation.
#Mark Seemann has written a article about it: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx
Is there some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)
Builder pattern.
I think it is OK, but there are implications. If this is an object to be used by others, you need to ensure that an exception is thrown any time a method or property is set or accessed and the initialization should have been called but isn't.
Obviously it is much more convenient and intuitive if you can take care of this in the constructor, then you don't have to implement these checks.
I don't see anything wrong in this. It may be not so convinient, but you can not ALWAYS use initialization in ctor, like you can not alwats drive under green light. These are dicisions that you made based on your app requirements.
It's ok. Immagine if your object, for example, need to read data from TCP stream or a file that ciuld be not present or corrupted. Raise an exception from ctor is baaad.
It's ok. If you think, for example, about some your DSL language compiler, it can looks like:
A) find all global variables and check if there mem allocation sum sutisfies your device requierements
B) parse for errors
C) check for self cycling
And so on...
Hoe this helps.
Answering (1)
Why not? An engine needs the driver because this must enter the key for the car, and later power-on. Will a car do things like detecting current speed if engine is stopeed? Or Will the car show remaining oil without powering-on it?
Some programming goals won't be able to have their actors initialized during its object construction, and this isn't because it's a non-proper way of doing things but because it's the natural, regular and/or semantically-wise way of representing its whole behavior.
Answering (2)
A decent class usage documentation will be your best friend. Like answer to (1), there're some things in this world that should be done in order to get them done rightly, and it's not a problem but a requirement.
Checking objects' state using flags isn't a problem too, it's a good way of adding reliability to your object models, because its own behaviors and consumers of them will be aware about if things got done as expected or not.
First of all, Factory Method.
public class MyClass
{
private MyClass()
{
}
public Create()
{
return new MyClass();
}
}
Second of all, why do you not want another class creating an object for you? (Factory)
public class MyThingFactory
{
IThing CreateThing(Speed speed)
{
if(speed == Speed.Fast)
{
return new FastThing();
}
return new SlowThing();
}
}
Third, why do multiple classes have side effects on new instances of your class? Don't you have declarative control over what other classes have access to your object?

List.Add(this) inside of a class

I created a class awhile back. I used List.Add(this) inside of the class so I could access the controls I created later. It seemed to be very useful and I do not know how to create controls (more than one in the same parent control without a predefined limit) and access them later.
I was looking for Add(this) on the internet and couldn't find anymore information on it.
Is this a large resource hog or ineffective? Why can't I find more information on it? It seems very useful.
public class GlobalData
{
private static List<Member> _Members;
public partial class ChildrenPanel
{
private static List<ChildrenPanel> _ListCP = new List<ChildrenPanel>();
//X and Y position Panel | Container is the control recieving the Control
public void CreatePanel(int X, int Y, Panel Container)
{
//
// pnlStudent
//
_pnlStudent.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
_pnlStudent.Controls.Add(_lblCLastName);
_pnlStudent.Controls.Add(_lblCFirstName);
_pnlStudent.Controls.Add(_lblGrade);
_pnlStudent.Controls.Add(_lblSelected);
_pnlStudent.Controls.Add(_lblSeason);
_pnlStudent.Controls.Add(_lblAvailable);
_pnlStudent.Controls.Add(_lblGender);
_pnlStudent.Controls.Add(_ddlGrade);
_pnlStudent.Controls.Add(_ddlSelectedSports);
_pnlStudent.Controls.Add(_ddlAvailableSports);
_pnlStudent.Controls.Add(_ddlSeason);
_pnlStudent.Controls.Add(_rdbFemale);
_pnlStudent.Controls.Add(_rdbMale);
_pnlStudent.Controls.Add(_btnRemoveChild);
_pnlStudent.Controls.Add(_btnRemoveSport);
_pnlStudent.Controls.Add(_btnAddSport);
_pnlStudent.Controls.Add(_txtCLastName);
_pnlStudent.Controls.Add(_txtCFirstName);
_pnlStudent.Location = new System.Drawing.Point(X, Y);
_pnlStudent.Name = "pnlStudent";
_pnlStudent.Size = new System.Drawing.Size(494, 105);
//Still playing with the tab index
_pnlStudent.TabIndex = 10;
// Adds controls to selected forms panel
Container.Controls.Add(_pnlStudent);
// Creates a list of created panels inside the class
ListCP.Add(this);
}
Just make sure that you Remove the instance again when it's no longer needed, otherwise the List holding a reference to it will keep it in memory forever (Welcome to memory leaks in .NET after all).
I may revise this answer once I see some code, but my initial response is that it is not a resource hog. As to whether it is effective or not, some example code will be required.
Adding an object to a collection does not take up a large amount of resources because you are simply adding a reference to the object into the collection. You still only have a single object, but two (or more) variables that point to that object, so the only extra resources you are using are the minimal memory used by the references.
If your List is static or otherwise globally available, then you're doing something very bad.
ASP.Net is structured such that every request to your page - including postbacks - from every user results in a new instance of the page class. that's a lot of page instances. If references to all these instances are saved somewhere, the instances can never be garbage collected. You've created something analogous to a memory leak and you'll quickly find yourself running out of resources after you deploy to production.
The really dangerous thing here is that if you only do functional testing and no load testing the problem will likely not show up during your tests at all, because it will work fine for a few hundred (maybe even thousand) requests before blowing up on you.
If you're worried about dynamic controls, there are several better ways to handle this:
Put a fixed limit on the maximum number of controls you will allow, and add all of them to the page up front. Then only show/render them (toggled via the .Visible property) as you need them.
Make it data-driven. Rather than dynamically add a control, insert something to a database table and then bind a query on that table to a repeater or other data control (my preferred method).
Just make sure you're recreating every dynamic control you need at the right place (Pre-Init) in the page lifecycle.

Managing of shared resources between classes?

Imagine that I have a several Viewer component that are used for displaying text and they have few modes that user can switch (different font presets for viewing text/binary/hex).
What would be the best approach for managing shared objects - for example fonts, find dialog, etc? I figured that static class with lazily initialized objects would be OK, but this might be the wrong idea.
static class ViewerStatic
{
private static Font monospaceFont;
public static Font MonospaceFont
{
get
{
if (monospaceFont == null)
//TODO read font settings from configuration
monospaceFont = new Font(FontFamily.GenericMonospace, 9, FontStyle.Bold);
return monospaceFont;
}
}
private static Font sansFont;
public static Font SansFont
{
get
{
if (sansFont == null)
//TODO read font settings from configuration
sansFont = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold);
return sansFont;
}
}
}
For items you wish to create once and then re-use there are two relevant patterns: Singleton and Cache. If you will re-use the item forever, the Singleton is OK. The memory allocated to that instance will never be cleared. If you will re-use the item for a while, but then maybe that function won't be used for a few days, I suggest using the cache. Then the memory can be cleared when the item is no longer in use.
If you are using the Singleton, you probably want to just init the Fonts directly rather than using the Lazy init pattern. To me, Fonts sound pretty simple and not likely to error out. However, if the item might fail during construction (perhaps due to a missing font file or something), then lazy pattern at least allows it to retry next time. You cannot redo a static initializer later, even if it fails, without restarting the whole application. Be careful to limit those retries!
Finally, the name of your class "ViewerStatic" raises a concern. There is an anti-pattern known as the "God" object. I call it the "bucket". If you create it, stuff will come. You will soon find all kinds of stuff being dumped in the bucket. Your ViewerStatic class will become huge. It would be better to have a class called "FontFlyWeights" and then another one called "ConstantStrings" or "SystemDialogFactory" ... etc.
That seems fine to me, but is it really necessary? The simple approach would be to just create new fonts and dialogs when you need them, then Dispose them if necessary and let the garbage collector clean them up.
Have you measured to see if the simple approach has a noticeable cost that makes it worth adding the complexity of caching shared objects?

Categories