I need to display some stats, numbers, and graphs about various game objects on the screen.
(examples: camera position, field of view, frames per second, fill rate, number of objects culled, etc... )
Currently any object which wants to be graphed or displayed implements an interface along these lines:
public interface IGraphable
{
float GraphableValue { get; set; }
}
Then that object can be sent to a graph component to be displayed. This has some obvious drawbacks like not being able to graph 2 different pieces of data which belong to the same class.
What I want is a way to pass a pointer to where the data is located or a pointer to a function which knows how to return the data instead of passing the object to the display component.
I believe that this is what delegates are for but I don't understand how to use them in this context (Actually I don't understand them very well at all). Also, is there another (smarter/better) way to do this?
Thanks!
Why not invert the control like this:
public interface IGraphable
{
void BuildGraphable( IGraph g );
}
interface IGraph {
void AddValue( double value );
}
this is a preferred option in OO anyway as it hides details of the IGraphable implementation. Additionally you can now extend IGraph for added functionality without breaking compatibility.
Depending on how you're doing things, you could possibly use Reflection (attributes on accessors), although that can be relatively confusing at first too. But it's a very useful tool in your arsenal, so it's well worth spending the time on. Here is a great tutorial on how to use them:
http://www.brainbell.com/tutors/C_Sharp/Attributes.htm
But then, learning delegates is also very useful, and that does sound like a good solution. I haven't looked deeply into it, but this tutorial on the same site might be useful:
http://www.brainbell.com/tutors/C_Sharp/Delegates_and_Event_Handlers.htm
I have decided to do the following:
public class GraphComponent
{
private Func<flaot> _function;
public GraphComponent(Func<flaot> function, ...)
{ ... }
}
This allows me to specify how the data is retrieved by writing something like this:
FPSComponent fpsc = new FPSComponent();
GraphComponent fpsg = new GraphComponent(delegate() { return fpsc.ApproximateFPS; }, ...);
What I want is a way to pass a pointer to where the data is located or a pointer to a function which knows how to return the data instead of passing the object to the display component.
If you don't want to add your objects to your graph component BECAUSE
This has some obvious drawbacks like not being able to graph 2 different pieces of data which belong to the same class.
Maybe a list will solve your problem ?
public interface IGraphable
{
List<float> GraphableValues { get; }
}
Related
I'm writing a permissions service for my app, and part of this service's responsibility is to check that a user has permission to access the particular object they are trying to change. There are around 6 six different objects that can be mutated, and they all possess a particular property called tenant. This tenant prop is what I need to check.
The issue is that I want to keep my code as DRY as possible, but I can't see anyway of not repeating myself in this particular situation. I have six different objects which I need to check, therefore I have six different IDs and six different calls to the database to retrieve the information I need.
I'm reluctant to write six different methods each supporting the different objects I need to check, but since the code is going to look something like the below (vastly simplified) I'm not sure if there's anything I can do differently.
public bool CheckUserHasPermissionForObject(string id)
{
var obj = _dataRepository.GetObjById(id);
var userHasPermission = UserHasPermission(obj);
return userHasPermission;
}
I was hoping delegate types would lend a hand here but I don't think they'll help either.
There are few options there.
Option 1: Using interfaces
You can create an interface class that has the property tenant:
// TODO: Rename this class
public interface IParentClass
{
string Tenant { get; set; }
}
Then derive all your six objects from that:
// TODO: Rename this class
public class ChildClass1 : IParentClass
{
public string Tenant { get; set; }
}
// TODO: Rename this class
public class ChildClass2 : IParentClass
{
public string Tenant { get; set; }
}
//... TODO: Derive the others as well
And then modify your method to check that property like this:
public bool CheckUserHasPermissionForObject(string id)
{
var obj = _dataRepository.GetObjById(id) as IParentClass;
var userHasPermission = UserHasPermission(obj);
return userHasPermission;
}
private bool UserHasPermission(IParentClass obj)
{
// TODO: Implement your check here
if (obj.Tenant == "Whatever")
{
// TODO: Implement your logic here
}
return false;
}
Option 2: Using reflections
You can get the value of the property called "tenant" of different objects with reflections like this:
var tenantValue = obj.GetType().GetProperty("tenant").GetValue(obj, null);
This will try to find a property called "tenant" in any object, and return the value.
P.S. Option 3 might be using some generics, but not sure, as the question is not that clear at this moment.
The issue is that I want to keep my code as DRY as possible, but I can't see anyway of not repeating myself in this particular situation. I have six different objects which I need to check, therefore I have six different IDs and six different calls to the database to retrieve the information I need.
If the logic for checking permissions is not the same, then by definition you aren't repeating yourself. Don't make your code arcane or unreadable all in the name of DRY.
Because you're making 6 distinct calls to the database, your options for reusing code are limited.
I'm reluctant to write six different methods each supporting the different objects I need to check.
If the objects have different ways to verify the permissions, there is no way around this. Either the objects are all the same (and can inherit some sort of shared logic), or they aren't. Objects that look similar but aren't actually the same should be kept separate.
My recommendation
In order to communicate similar functionality (but different implementation), I'd use an interface. Maybe something like
public interface IUserPermission
{
string Tenant { get; set; }
bool CheckUserHasPermissions(string id);
}
This interface makes the calling code more consistent and better communicates how the objects are meant to interact. Notably, this does not reduce the amount of code written. It just documents/explains the intention of the code.
Alternative solution
Ultimately, the code will need to be able to distinguish your different types of objects. But technically you could write one giant function that switches based on object type instead of splitting the logic across the six different objects. I personally find this organization hard to read and debug, but you could technically write some sort of utility (extension) method like this:
public static bool CheckUserHasPermissions(this object obj, string id)
{
if (obj is Type1)
return CallDatabase1(id);
if (obj is Type2)
return CallDatabase2(id);
throw new ArgumentException("Unsupported object type.", nameof(obj));
}
I'm currently working on a WPF-application (C#, using the Prism framework) that will contain a drawing pane where a user can draw polygons using his mouse.
But I'm wondering how I can make these drawings persistent.
I'm guessing that the best object to contain those drawings are the Polygon object?
I would also like to have those Polygons have certain attributes, such as a color etc. (if need be I can do this by defining my own Polygon-inherited object).
But I'm especially wondering how I can make this kind of information persistent in a database? (I'm using SQLite at the moment).
I want to be able to store Polygon information, including information such as the fill-color of that Polygon etc. in a database.
I've been googling this, but I'm not finding something useful. Could someone point me in the right direction?
Thanks for any help!
You have to create model classes in order to store the necessary information, which you would like to store.
I think it might be the best solution to use Entity Framework, so you wouldn't have to bother with creating the model classes, you could use the existing ones. But, in your case, it might saves a lot of unnecessary information into your tables.
If you are creating your own model classes, you can add a helper Extension Method to .net types, such as Polygon. That method would generate a storable model class from the .net class, which can be saved to database.
For example:
Model class:
public class PolygonDbFormat // the class which contains the information you want to store
{
public string Name { get; set; }
public Brush Fill { get; set; }
}
Defining the extension method:
public static class PolygonEx
{
public static PolygonDbFormat AsDbFormat(this Polygon polygon)
{
return new PolygonDbFormat
{
Name = polygon.Name,
Fill = polygon.Fill
};
}
}
Then you can save the Polygon class to the database this way:
var dbFormat = yourPolygon.AsDbFormat();
_yourDbManager.AddEntry(dbFormat); // your implementation to store the data in database
TL;DR: the title says it all, and a simple answer would be great if the question can be answered simply
Longer Version:
I am using a pre-existing library to build invoices, and the library holds the instantiation of the invoice object and static functions which add items to the invoice. The items on the invoice include breakdowns of sub-items, and it has about a dozen columns. No item uses all the columns, and the column usage and values depends on the item listed and it's depth within a breakdown.
So, the invoice can be built with pseudocode like this:
Invoice customerInvoice = new Invoice();
MainItem widget = new MainItem(); //the entirety of the sale, this is shown as the top-level item
SubItem component = new SubItem(widget, values[]); //a component of widget. The parameters identify the main piece that this attaches to, and a set of values for the other columns.
SubItem piece = new SubItem(widget, values[]); //another component; the values[] will be slightly different but correspond to the same columns.
SubItem bolt = new DeepSubItem(piece, lowestValues[]); //an irreducibly small item which is a part of the "piece" item, with it's own set of values which fill a different arrangement of columns
Components and sub-components are shown on indented lines below their parent object.
I am trying to create a new class structure that can help simplify this. The largest problem is that values[] here represents about 20 individual parameters. Additionally, a maze of conditional statements is necessary due to quirks of individual products, variations based on sale location or time, and many other factors. The only constant is that each function corresponds to a single line on the invoice. The original library was great at nesting objects properly, but it can't handle the logic. The SubItem instantiations of piece, bolt, and component only exist so that they can be broken down. When SubItem() or DeepSubItem() are called, the objects are attached to the object that they include in their parameter.
First question: What is a good plan/design pattern/strategy to build a new structure that can use the existing library, but provide flexible logic?
Second question: If I could create an 'instance' of the static functions, I could use that instance without the great verbosity of the parameters. Is there any way to do this, or something that will have a similar effect?
I've been thinking of creating a new class that will conduct the logic and hold the needed sets of values. That class can then create 'objects' (ideally, instances of the static functions) which I can use in the code we already have, replacing the function calls. That would allow me to separate the verbosity (which rarely needs to change) from the logic (which often needs to change). I can't simply use the object "bolt" because the moment I instantiate it, it is added to the invoice - hence why I want to treat the function like an object.
Your wise input (and/or reality check) is greatly appreciated. Thanks,
One of the ways you could do this would be to use the Func object. This allows you to pass functions by reference. Here's an example:
private static object TestStaticFunction()
{
return "test";
}
public static Func<object> GetStaticFunction
{
get { return TestStaticFunction; }
}
Then, any function that calls GetStaticFunction will get TestStaticFunction returned to it. Likewise, Console.Write(GetStaticFunction()) will display "test".
Note that if you want to pass a method that does not return a value, use Action instead.
Here's the MSDN documentation on Func: http://msdn.microsoft.com/en-us/library/bb549151%28v=vs.110%29.aspx
And another StackOverflow thread with more explanation: What is Func, how and when is it used
As far as your program design, I'm not really sure that I understand the library well enough to point you towards a better pattern. Are you forced to work within this library?
Are you talking about delegates?
class Program
{
static void Main(string[] args)
{
var returnedFunction = TestClass.FunctionToReturnAStaticMethod();
returnedFunction();
}
}
public class TestClass
{
public delegate void TypeOfFunctionToReturn();
public static TypeOfFunctionToReturn FunctionToReturnAStaticMethod()
{
return () => StaticMethod();
}
public static void StaticMethod()
{
Console.WriteLine("\"StaticMethod\" called");
}
}
For my homework, I'm implementing a course registration system for a university and I implemented a simple class for Curriculum with list of semesters and other properties like name of the department, total credits etc.
But I'm wondering if I can inherit this class from a Graph Data Structure with Edges and vertices.
Anybody done similar things before?
My current design is something like this:
public class Curriculum
{
public string NameOfDepartment { get; set; }
public List<Semester> Semesters { get; set; }
public bool IsProgramDesigned { get; set; }
public Curriculum()
{
IsProgramDesigned = false;
}
//
public string AddSemester(Semester semester)
{
As an enterprise architect I would absolutely not use a graph structure for this data. This data is a list and nothing more.
For a problem similar to this, the only reason I would ever consider using a graph structure would be to potentially create the relationship of course requirements and prerequisites.
This way you could then use the graph algorithm to determine if it is valid for a student to register for a class by making sure it is a valid addition to the tree. Same for removing classes, it could be validated to make sure you aren't dropping a class and staying enrolled in the lab for the class example.
Now if I was going to actually implement this. I would still have an overall list of classes that have a Key to the vertex in the graph representation. One thing to keep in mind is that graph algorithms are about the biggest heavy hitter you can throw at a database so minimize the amount of work done to pull the graph out is always key. Depending on the size and scope, I would also evaluate if I could store entire graphs in a serialized form or to use a document database for the same reason.
Which in this example would be the most likely route I would take. I would store the entire object of prerequisites co-requisites and so on right inline with my course object. Since the graph is a set it and done event there's no need to do an actual graph traversal and you're better off storing the pre-calculated graph.
Yes you can inherit this class from a Graph data structure. You can make it a subclass of anything you want (except for a sealed class). The question of whether or not it is a wise design is entirely dependant on what you want to do. I assume you know how, so comment if you need an example of how to implement inheritance.
IF you are wanting to write your own graphing algorithms, why not just model it yourself? It would probably be a fun exercise.
Let's say I have a long established repository like this:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts();
}
It's been around for ages, and the GetDonuts method does what it says. Then one day I need to add a new screen that shows all the donuts in the database, and it turns out that the method has a hidden feature - it filters out all donuts where stale = true. But on my new screen, I want to show all of them, even the stale ones! What is the best approach here?
Assuming that this method is used all over the place, and the default behaviour needs to stay the same, is it best to add a new method called GetAllDonuts that doesn't do the filtering, or should I just add a onlyFresh parameter onto the GetDonuts method?
I'm guessing its just down to judgement, but I'm wondering if there are any more informed answers out there?
I would overload the method creating a new overload that takes the showStale parameter and then modify the old method to use the new overload passing false for the parameter value.
The interface would look like:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts();
public IEnumerable<Donut> GetDonuts(bool showStale);
}
Or if you're using .NET 4.0, you can use an optional parameter:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts(bool showStale = false);
}
Why not use an optional parameter? This way you don't break existing code:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts(bool onlyFresh);
}
Implementation:
public IEnumerable<Donut> GetDonuts(bool onlyFresh = false)
{
if (onlyFresh)
// do stuff
else
// do other stuff
}
This really comes down to personal preference, to some extent...
If you have the ability to change the API, I would (personally) rename the current method in a way that makes it obvious that it is not returning all Donut instances. My expectation would be that a repository's GetDonuts method would get all of the donuts. This could be doing via a parameter, or a different name, at your discretion.
That being said, a method overload taking the extra parameter is probably the best option moving forward, if keeping compatibility is critical. (This depends a lot on who and where this API is used...)
Depending on the circumstancs, one might consider introducing a property for accessing the donuts.
interface IDonutRepository
{
IEnumerable<Donut> Donuts { get; }
.. or ..
IQueryable<Donut> Donuts { get; }
}
It's fairly easy to implement this interface if you're using a Linq-savvy ORM like Entity Framework or NHibernate.
The old GetDonuts method could be renamed GetFreshDonuts(), or you could refactor calls to it into the form:
repository.Donuts.Where(x => !x.Stale)
One of the growing trends in software
design is separating interface from
implementation. The principle is about
separating modules into public and
private parts so that you can change
the private part without coordinating
with other modules. However, there is
a further distinction—the one between
public and published interfaces. This
distinction is important because it
affects how you work with the
interface.
http://www.martinfowler.com/ieeeSoftware/published.pdf