I am developing a space shooter game with customizable ships. You can increase the strength of any number of properties of the ship via a pair of radar charts*. Internally, i represent each ship as a subclassed SpaceObject class, which holds a ShipInfo that describes various properties of that ship.
I want to develop a relatively simple API that lets me feed in a block of relative strengths (from minimum to maximum of what the radar chart allows) for all of the ship properties (some of which are simplifications of the underlying actual set of properties) and get back a ShipInfo class i can give to a PlayerShip class (that is the object that is instantiated to be a player ship).
I can develop the code to do the transformations between simplified and actual properties myself, but i would like some recommendations as to what sort of architecture to provide to minimize the pain of interacting with this translator code (i.e. no methods with 5+ arguments or somesuch other nonsense). Does anyone have any ideas?
*=not actually implemented yet, but that's the plan.
What about the Builder pattern? You could have a static FillDefaults method on your ShipInfo class and then assign each property of the ShipInfo via an instance method that returns the instance that you're working with, like this:
ShipInfo.FillDefaults().CalculateSomething(50).AssignName("Testing...").RelativeFiringPower(10).ApplyTo(myShip);
Within ShipInfo, this would look something like:
public static ShipInfo FillDefaults()
{
ShipInfo newInstance = ...;
// Do some default setup here
return newInstance;
}
public ShipInfo CalculateSomething(int basis)
{
// Do some calculation
// Assign some values internally
return this;
}
// Keep following this pattern of methods
public void ApplyTo(SpaceObject obj)
{
// Some checks here if you want
obj.ShipInfo = this;
}
I would say the Facade pattern is perfect for that kind of problem. If you have 5+ arguments on your methods, consider encapsulating at least part of them in a new type.
Seems like you want to set some properties but not the others, but not in a particular order of importance so that you could define overloads with incrementally more arguments.
You could implement a constructor with minimum required values that sets default values for the other, and then use object initializer to set the remaining relevant values:
// Didn't set properties 2 3 and 6, only set the ones needed in this case.
SpaceObject ship = new SpaceObject(someRequiredValue) {
Property1 = 50,
Property4 = Game.Settings.Ships.Armor.Strong,
Property5 = new PropertySet1{
Prop51 = "Enterprise",
Prop53 = true,
Prop57 = false
};
To me this looks like a case for the decorator pattern.
Related
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");
}
}
To give some background on what I am doing:
I have a program that allows a user to modify and create a general calibration. Inside this calibration includes groups. Groups differ by the type of analysis they perform. These groups also included spectral sets with each set containing data for only one molecule. Inside these sets also includes spectral data at varying concentrations. Each spectra data is a discrete set of data which is specified by its resolution (x-axis space between each point) and its spectral range (x axis range).
One of the main aspects of building these calibration files is to keep the resolution and spectral range consistent in all spectral data in each set. This means that spectral data cannot be added unless it matches the spectral data of the rest. Also, if the user deletes all spectral data the resolution and range is reset allowing Spectra data of any range or resolution to be added to the calibration.
The question is: How can I provided an effective way to prevent adding spectral data to the calibration that doesn't match the current resolution and spectral range???
Below is a general description of a calibration class. This is a very general description and contains the only info needed to explain what I am trying to do.
class calibration
{
List<Group> groups;
}
class Group
{
List<SpectralSet> sets;
}
class SpectralSet
{
List<SpectraData> spectras;
}
class SpectraData
{
double firstXPoint;
double lastXPoint;
double resolution;
double[] Ypoints;
}
I'm sure you could apply all sorts of fancy design patterns to enforce the rules you mention.
However, for the sake of simplicity, I would just encapsulate the logic in the calibration class with an AddGroup method which validates the added group conforms to the calibration's requirements. Similarly, I would create an AddSpectralSet method to the group class as a gate keeper into the sets collection.
At that point, depending on how often these things change, I would think about exposing the groups collection and sets collection as ReadOnlyCollection to ensure code doesn't try to add items without using the prescribed methods.
Hope this helps.
Your approach will probably vary a bit, but here's an outline of how you could achieve this. You need to do the following:
Only expose immutable public collection properties, along with an Add method, so that you can do your own validation.
For example, you don't want to do:
class Group
{
public List<SpectralSet> sets;
}
Because then anyone can just do myGroup.sets.Add(mySet), without you getting a chance to do any validation on the set. One common pattern to achieve this is as follows:
class Group
{
private List<SpectralSet> _sets;
public IEnumerable<SpectralSet> Sets { get { return _sets; } }
public void Add(SpectralSet set)
{
//Do validation here, throw an exception or whatever you want to do if the set isn't valid
_sets.Add(set);
}
//Have a similar Remove method
}
Store the criteria that the data must match
I'm not quite sure what a spectral range is, so I'll just use the resolution as an example. You can extend this to whatever the range criteria is simply. There's at least three possible ways you could do this:
When you construct a class, pass it the resolution that it's allowed in the constructor, and make this immutable.
When adding and removing, update the allowed resolution as necessary.
Don't store the resolution explicitly, calculate it every time you add or remove.
Out of those, option 1 is by far the simplest. Life is always much easier when you can keep things as immutable as possible. So you'd do something like:
class Group
{
private List<SpectralSet> _sets;
public IEnumerable<SpectralSet> Sets { get { return _sets; } }
public readonly double Resolution;
public Group(double resolution)
{
Resolution = resolution;
}
public void Add(SpectralSet set)
{
if(set.Resolution != resolution)
//Throw an Exception here, or however you want to handle invalid data
_sets.Add(set);
}
//Have a similar Remove method
}
Following this example, each of the classes you included would need a Resolution parameter with the same kind of logic, just checking the Resolution of any direct child you tried to add. Likewise with whatever you use for spectral range.
You also want to be able to change the resolution allowed if all data is cleared. The simplest way to do this is just create new objects whenever the data is cleared, rather than just clearing out the collections in existing objects.
Make SpectraData immutable
All this is useless if you can get a SpectraData out of one of the carefully gated collections and change it arbitrarily. Make anything that needs to be validated immutable, only allowing it to be set on construction. If you have a requirement not to do that, you need to think very carefully about how you will allow it to be changed.
I want to create a GUI application (MVC asp web application) to create business rules that can be used for my business rules engine.
For this I have several objects (Request Objects) with various variables that can be used to create these rules. Because these request objects are also used in the validation of these rules.
An example, I have a TripRequest Object with a string variable 'Airline' and an int variable 'Price'.
I want in my GUI that when you select 'TripRequest' from a dropdown menu from various request objects. That a second dropdown menu is filled with all its fields (airline, price, etc).
Then when you select one of these fields, it needs to read its type (string, int) so that the GUI can give the appropriate operations (equals, not equals, larger, smaller than, etc) for the business rules.
My idea so far for creating such a GUI is to use reflection to read out all the field and method names from the various objects and use them to fill the GUI. Is this a good practice to use reflection?
I haven't used reflection before so I am wondering if there might be a better way to do it. I don't want to hard-code everything in because the application needs to be extend-able (new Request objects, new fields added to objects) without having to add more code to the GUI aswell.
my question:
-Is reflection a good practice to use for this problem?
-If not, what would you recommend using or looking at?
This is my first question on stackoverflow, if I did anything wrong please let me know so I can edit or change it.
Thank you for reading :).
You don't have to use reflection. Alternatives would include using some kind of external metadata to match up UI and data (and possibly generating code and UI from that metadata) or trying to statically analyse your code (perhaps using Roslyn!) to generate a suitable UI. However, reflection is likely to be far less painful. Potential downsides...
If you have deeply nested or complicated data structures you want to expose in the UI, it can be quite difficult to decide how best to do this.
If you don't have a clear set of 'UI-facing' objects with consistent rules for visibility, you'll have to spent time creating some kind of attribute or convention-based scheme to ensure you only expose the things you want to expose.
You may only find out at runtime (worst-case, in deployment) that you fail to correctly expose some rarely-used type.
Having said all that, if your data-types are generally just bags of properties, reflection is very straightforward. Here's some toy code that shows most of the relevant tricks you'll need, including setting up data-binding. Note that it is conventional to use properties rather than bare fields when reflecting over objects.
class Program
{
[STAThread]
static void Main(string[] args)
{
var request = new TripRequest() {Airline = "Reflection Airways"};
var window = new Window();
var stackPanel = new StackPanel();
window.Content = stackPanel;
foreach (var property in request.GetType().GetProperties())
{
Console.WriteLine("Property named {0} has type {1}", property.Name, property.PropertyType);
if (property.PropertyType == typeof(string))
{
var textBox = new TextBox();
var binding = new Binding();
binding.Source = request;
binding.Path = new PropertyPath(property.Name);
BindingOperations.SetBinding(textBox, TextBox.TextProperty, binding);
stackPanel.Children.Add(textBox);
}
// etc for other types you care about
}
window.ShowDialog();
Console.WriteLine("Airline is now {0}",request.Airline);
Console.WriteLine("Finished");
}
}
class TripRequest
{
public string Airline { get; set; }
public int Price { get; set; }
}
I'm new to the .NET world having come from C++ and I'm trying to better understand properties. I noticed in the .NET framework Microsoft uses properties all over the place. Is there an advantage for using properties rather than creating get/set methods? Is there a general guideline (as well as naming convention) for when one should use properties?
It is pure syntactic sugar. On the back end, it is compiled into plain get and set methods.
Use it because of convention, and that it looks nicer.
Some guidelines are that when it has a high risk of throwing Exceptions or going wrong, don't use properties but explicit getters/setters. But generally even then they are used.
Properties are get/set methods; simply, it formalises them into a single concept (for read and write), allowing (for example) metadata against the property, rather than individual members. For example:
[XmlAttribute("foo")]
public string Name {get;set;}
This is a get/set pair of methods, but the additional metadata applies to both. It also, IMO, simply makes it easier to use:
someObj.Name = "Fred"; // clearly a "set"
DateTime dob = someObj.DateOfBirth; // clearly a "get"
We haven't duplicated the fact that we're doing a get/set.
Another nice thing is that it allows simple two-way data-binding against the property ("Name" above), without relying on any magic patterns (except those guaranteed by the compiler).
There is an entire book dedicated to answering these sorts of questions: Framework Design Guidelines from Addison-Wesley. See section 5.1.3 for advice on when to choose a property vs a method.
Much of the content of this book is available on MSDN as well, but I find it handy to have it on my desk.
Consider reading Choosing Between Properties and Methods. It has a lot of information on .NET design guidelines.
properties are get/set methods
Properties are set and get methods as people around here have explained, but the idea of having them is making those methods the only ones playing with the private values (for instance, to handle validations).
The whole other logic should be done against the properties, but it's always easier mentally to work with something you can handle as a value on the left and right side of operations (properties) and not having to even think it is a method.
I personally think that's the main idea behind properties.
I always think that properties are the nouns of a class, where as methods are the verbs...
First of all, the naming convention is: use PascalCase for the property name, just like with methods. Also, properties should not contain very complex operations. These should be done kept in methods.
In OOP, you would describe an object as having attributes and functionality. You do that when designing a class. Consider designing a car. Examples for functionality could be the ability to move somewhere or activate the wipers. Within your class, these would be methods. An attribute would be the number of passengers within the car at a given moment. Without properties, you would have two ways to implement the attribute:
Make a variable public:
// class Car
public int passengerCount = 4;
// calling code
int count = myCar.passengerCount;
This has several problems. First of all, it is not really an attribute of the vehicle. You have to update the value from inside the Car class to have it represent the vehicles true state. Second, the variable is public and could also be written to.
The second variant is one widley used, e. g. in Java, where you do not have properties like in c#:
Use a method to encapsulate the value and maybe perform a few operations first.
// class Car
public int GetPassengerCount()
{
// perform some operation
int result = CountAllPassengers();
// return the result
return result;
}
// calling code
int count = myCar.GetPassengerCount();
This way you manage to get around the problems with a public variable. By asking for the number of passengers, you can be sure to get the most recent result since you recount before answering. Also, you cannot change the value since the method does not allow it. The problem is, though, that you actually wanted the amount of passengers to be an attribute, not a function of your car.
The second approach is not necessarily wrong, it just does not read quite right. That's why some languages include ways of making attributes look like variables, even though they work like methods behind the scenes. Actionscript for example also includes syntax to define methods that will be accessed in a variable-style from within the calling code.
Keep in mind that this also brings responsibility. The calling user will expect it to behave like an attribute, not a function. so if just asking a car how many passengers it has takes 20 seconds to load, then you probably should pack that in a real method, since the caller will expect functions to take longer than accessing an attribute.
EDIT:
I almost forgot to mention this: The ability to actually perform certain checks before letting a variable be set. By just using a public variable, you could basically write anything into it. The setter method or property give you a chance to check it before actually saving it.
Properties simply save you some time from writing the boilerplate that goes along with get/set methods.
That being said, a lot of .NET stuff handles properties differently- for example, a Grid will automatically display properties but won't display a function that does the equivalent.
This is handy, because you can make get/set methods for things that you don't want displayed, and properties for those you do want displayed.
The compiler actually emits get_MyProperty and set_MyProperty methods for each property you define.
Although it is not a hard and fast rule and, as others have pointed out, Properties are implemented as Get/Set pairs 'behind the scenes' - typically Properties surface encapsulated/protected state data whereas Methods (aka Procedures or Functions) do work and yield the result of that work.
As such Methods will take often arguments that they might merely consume but also may return in an altered state or may produce a new object or value as a result of the work done.
Generally speaking - if you need a way of controlling access to data or state then Properties allow the implementation that access in a defined, validatable and optimised way (allowing access restriction, range & error-checking, creation of backing-store on demand and a way of avoiding redundant setting calls).
In contrast, methods transform state and give rise to new values internally and externally without necessarily repeatable results.
Certainly if you find yourself writing procedural or transformative code in a property, you are probably really writing a method.
Also note that properties are available via reflection. While methods are, too, properties represent "something interesting" about the object. If you are trying to display a grid of properties of an object-- say, something like the Visual Studio form designer-- then you can use reflection to query the properties of a class, iterate through each property, and interrogate the object for its value.
Think of it this way, Properties encapsulate your fields (commoningly marked private) while at the same time provides your fellow developers to either set or get the field value. You can even perform routine validation in the property's set method should you desire.
Properties are not just syntactic sugar - they are important if you need to create object-relational mappings (Linq2Sql or Linq2Entities), because they behave just like variables while it is possible to hide the implementation details of the object-relational mapping (persistance). It is also possible to validate a value being assigned to it in the getter of the property and protect it against assigning unwanted values.
You can't do this with the same elegance with methods. I think it is best to demonstrate this with a practical example.
In one of his articles, Scott Gu creates classes which are mapped to the Northwind database using the "code first" approach. One short example taken from Scott's blog (with a little modification, the full article can be read at Scott Gu's blog here):
public class Product
{
[Key]
public int ProductID { get; set; }
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category category { get; set; }
}
// class Category omitted in this example
public class Northwind : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
You can use entity sets Products, Categories and the related classes Product and Category just as if they were normal objects containing variables: You can read and write them and they behave just like normal variables. But you can also use them in Linq queries, persist them (store them in the database and retrieve them).
Note also how easy it is to use annotations (C# attributes) to define the primary key (in this example ProductID is the primary key for Product).
While the properties are used to define a representation of the data stored in the database, there are some methods defined in the entity set class which control the persistence: For example, the method Remove() marks a given entity as deleted, while Add() adds a given entity, SaveChanges() makes the changes permanent. You can consider the methods as actions (i.e. you control what you want to do with the data).
Finally I give you an example how naturally you can use those classes:
// instantiate the database as object
var nw = new NorthWind();
// select product
var product = nw.Products.Single(p => p.ProductName == "Chai");
// 1. modify the price
product.UnitPrice = 2.33M;
// 2. store a new category
var c = new Category();
c.Category = "Example category";
c.Description = "Show how to persist data";
nw.Categories.Add(c);
// Save changes (1. and 2.) to the Northwind database
nw.SaveChanges();
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; }
}