Instantiating various inherited classes through one method, without reflection - c#

In a project I'm working on, I have a set of blocks that make up a 3D voxel based environment (like Minecraft). These worlds are stored in an external data file.
This file contains the data for:
Each block,
its location,
and its type.
When the LoadLevel method is called, I want it to iterate over the data for every block in the file, creating a new instance of the Block object for every one. It's no problem to pass things like location. It's as simple as
CreateBlock(Vector3 position)
The issue is with the type. All types are child classes (think Abstract Block, and then subtypes like GrassBlock or WaterBlock that inherit the abstract Block's properties.) Assuming there's a child class like "GrassBlock" that I want to be created, rather than a generic block, how do I make it do this through the method? The only way I know of is through reflection, which I've been advised to stay away from. Is it possible that I can do this through generic typing or something?
This seems like such an important question in game design, but no one I've asked seems to have any idea. Any help?

Generic typing will still require reflection.
First of all: what you're looking for is the factory pattern. It creates objects for you without having to do it explicitly yourself everywhere.
Basically there are two options:
Reflection
This indeed has a performance impact connected to it but don't dismiss it if you haven't determined it to be a problem yet. It will be readable and maintainable.
Switches
Hardcode every option and create a new instance based on some sort of metadata you pass in (something that will identify the type of each block). This has the benefit of not using reflection and as such not incurring that performance penalty but it will also be less extensible and if you have 500 different blocks you can guess what your code will look like.

Of course, you can create objects without any reflection.
Simple assign each class the integer index:
Func<Vector3, Block>[] factories =
{
(v) => new GrassBlock(v), // index 0
(v) => new WaterBlock(v), // index 1
. . .
}
Save this index in the external data. At deserialization time read Vector3 v and index i, then call var block = factories[i](v);

Without reflection, you can use a factory method, with a switch. Assume BlockType is an enum.
public static Block CreateBlock(BlockType type, Vector3 position)
{
switch (BlockType type)
{
case BlockType.Grass:
return new GrassBlock(position);
case BlockType.Water:
return new WaterBlock(position);
default:
throw new InvalidOperationException();
}
}
But to have something more maintainable, you could still use reflection until it proves to be a bottleneck. In that case, you could switch to runtime code generation.
private static readonly Dictionary<Type, Func<Vector3, Block>> _activators = new Dictionary<Type, Func<Vector3, Block>>();
public static Block CreateBlock(Type blockType, Vector3 position)
{
Func<Vector3, Block> factory;
if (!_activators.TryGetValue(blockType, out factory))
{
if (!typeof(Block).IsAssignableFrom(blockType))
throw new ArgumentException();
var posParam = Expression.Parameter(typeof(Vector3));
factory = Expression.Lambda<Func<Vector3, Block>>(
Expression.New(
blockType.GetConstructor(new[] { typeof(Vector3) }),
new[] { posParam }
),
posParam
).Compile();
_activators.Add(blockType, factory);
}
return factory(position);
}
This code will generate a factory function at runtime, the first time a block of a given type is requested. And you could make this function thread-safe if needed by using a ConcurrentDictionary.
But that may be a bit overkill for your purpose ;)

Why are you avoiding reflection? If you're able to execute this code only on startup (which it sounds like you can do if you're reading a file) then I don't personally have too big a problem with using reflection.
An alternative is to store the fully qualified type name (e.g. My.System.Blocks.GrassBlock) and load that type with
var typeName = readStringTypeFromFile(file);
Block type = Activator.CreateInstance(typeName, location);
As I said, running something like this on startup is fine by me, and you can test performance of this if needs be.
Quick and dirty fiddle: https://dotnetfiddle.net/BDmlyi

Related

Implementing the strategy pattern. Do I have to 'new up' everytime?

I am trying to implement the strategy pattern. Here is part of my implementation:
public List<string> GetOrderedEmployeeNames(IOrderByStrategy strategy)
{
return GetEmployeeFullNames().OrderBy(strategy.Order);
}
now every time I call this function I have to write:
var employees = GetOrderedEmployeeNames(new OrderByFamilyName());
Is 'new-ing up' the strategy every time the right way or am I implementing this incorrectly?
If the class that implements IOrderByStrategy doesn't have any state (i.e. behaves the same every time) then you might as well store it in a field somewhere to save having to re-new it.
That said, new is a very efficient operation and if you're not calling it in a tight loop, it may be simpler to keep doing what you're doing.
Not necessarily, although it's probably not hurting anything to create objects as I'm assuming they're mostly methods and don't hold a lot of data.
Some alternatives:
Implement a StrategyFactory that either creates new instances or hold references to flyweights (small objects that are indexed by some key, like a string)
Implement the strategies as singletons, but that may be more overhead than you need if there are a lot of strategies.
You can store a property if the strategy will have same behavior. If not, you can create object with parameters.
private IOrderByStrategy orderByStrategy;
public IOrderByStrategy OrderByStrategy
{
get
{
if(orderByStrategy != null)
return orderByStrategy;
else
return new OrderByStrategy();
}
}
var employees = GetOrderedEmployeeNames(OrderByStrategy);
Second situation:
var employees = GetOrderedEmployeeNames(new OrderByFamilyName("familyname","DESC"));

Avoiding repeatedly allocating an Action object without a variable / member

Often I need to minimise object allocations within code that runs very frequently.
Of course I can use normal techniques like object pooling, but sometimes I just want something that's contained locally.
To try and achieve this, I came up with the below:
public static class Reusable<T> where T : new()
{
private static T _Internal;
private static Action<T> _ResetAction;
static Reusable()
{
_Internal = Activator.CreateInstance<T>();
}
public static void SetResetAction(Action<T> resetAction)
{
_ResetAction = resetAction;
}
public static T Get()
{
#if DEBUG
if (_ResetAction == null)
{
throw new InvalidOperationException("You must set the reset action first");
}
#endif
_ResetAction(_Internal);
return _Internal;
}
}
Currently, the usage would be:
// In initialisation function somewhere
Reuseable<List<int>>.SetResetAction((l) => l.Clear());
....
// In loop
var list = Reuseable<List<int>>.Get();
// Do stuff with list
What I'd like to improve, is the fact that the whole thing is not contained in one place (the .SetResetAction is separate to where it's actually used).
I'd like to get the code to something like below:
// In loop
var list = Reuseable<List<int>>.Get((l) => l.Clear());
// Do stuff with list
The problem with this is that i get an object allocation (it creates an Action<T>) every loop.
Is it possible to get the usage I'm after without any object allocations?
Obviously I could create a ReuseableList<T> which would have a built-in Action but I want to allow for other cases where the action could vary.
Are you sure that creates a new Action<T> on each iteration? I suspect it actually doesn't, given that it doesn't capture any variables. I suspect if you look at the IL generated by the C# compiler, it will cache the delegate.
Of course, that's implementation-specific...
EDIT: (I was just leaving before I had time to write any more...)
As Eric points out in the comment, it's not a great idea to rely on this. It's not guaranteed, and it's easy to accidentally break it even when you don't change compiler.
Even the design of this looks worrying (thread safety?) but if you must do it, I'd probably turn it from a static class into a "normal" class which takes the reset method (and possibly the instance) in a constructor. That's a more flexible, readable and testable approach IMO.

List.OfType() speed, alternative data structures

Take a look at this code.
interface ILoader
{
}
interface ILoader<T>: ILoader
{
T Load();
}
class CarLoader: ILoader<Car>
{
...
}
class TrainLoader: ILoader<Train>
{
...
}
class Container
{
List<ILoader> loaders = new ILoader[] { new CarLoader(), new TrainLoader()};
public T Load<T>()
{
// Finding right loader
var loader = loaders.OfType<ILoader<Car>>.FirstOrDefault();
return loader.Load();
}
}
I've got about 100 of loaders and I need to load a lot of Trains, Cars, etc. I think that List of loaders is very slow (has OfType() linear complexity??), what do you suggest to use instead of list? Dictionary<Type,ILoader> or Hashtable<Type,ILoader> or HashSet<ILoader>? How fast would be for example to use hashset.OfType<ILoader<Car>>(), same as list or faster?
Build a Dictionary<Type, ILoader> and populate it with the loaders. Then you can just do:
ILoader<T> loader = (ILoader<T>) loaderDictionary[typeof(T)];
On the other hand, if you've only got 100 items to look through, even a linear scan isn't exactly going to take long. Have you actually benchmarked a real usage situation and found this to be your bottleneck?
The Enumerable.OfType extension method does run in linear time and it is probably fast enough for your purposes. Don't micro-optimizate your code unless you have measured the performance and are sure that you need to optimize it.
Rather than concentrating on the performance you should first consider the suitability of your design. A good design in general does not need to inspect the types of the object - the information you need should be available in other ways. In this case for example you might want to ask if each loader is capable of loading an object by passing that object to a CanLoad method and returning true or false. This will make your design more flexible.
Loader loader = loaders.First(x => x.CanLoad(myObject));
Now you can have loaders that can load multiple types of objects.
If you want a new Loader each time and you want a one-to-one mapping another option is to also ask the object itself to create a suitable loader:
Loader loader = myObject.CreateLoader();
Each class can implement CreateLoader differently so that you get a Loader of the correct type for your object. By taking advantage of polymorphism this works without ever needing to ask an object what type it is.

thoughts on configuration through delegates

i'm working on a fork of the Divan CouchDB library, and ran into a need to set some configuration parameters on the httpwebrequest that's used behind the scenes. At first i started threading the parameters through all the layers of constructors and method calls involved, but then decided - why not pass in a configuration delegate?
so in a more generic scenario,
given :
class Foo {
private parm1, parm2, ... , parmN
public Foo(parm1, parm2, ... , parmN) {
this.parm1 = parm1;
this.parm2 = parm2;
...
this.parmN = parmN;
}
public Bar DoWork() {
var r = new externallyKnownResource();
r.parm1 = parm1;
r.parm2 = parm2;
...
r.parmN = parmN;
r.doStuff();
}
}
do:
class Foo {
private Action<externallyKnownResource> configurator;
public Foo(Action<externallyKnownResource> configurator) {
this.configurator = configurator;
}
public Bar DoWork() {
var r = new externallyKnownResource();
configurator(r);
r.doStuff();
}
}
the latter seems a lot cleaner to me, but it does expose to the outside world that class Foo uses externallyKnownResource
thoughts?
This can lead to cleaner looking code, but has a huge disadvantage.
If you use a delegate for your configuration, you lose a lot of control over how the objects get configured. The problem is that the delegate can do anything - you can't control what happens here. You're letting a third party run arbitrary code inside of your constructors, and trusting them to do the "right thing." This usually means you end up having to write a lot of code to make sure that everything was setup properly by the delegate, or you can wind up with very brittle, easy to break classes.
It becomes much more difficult to verify that the delegate properly sets up each requirement, especially as you go deeper into the tree. Usually, the verification code ends up much messier than the original code would have been, passing parameters through the hierarchy.
I may be missing something here, but it seems like a big disadvantage to create the externallyKnownResource object down in DoWork(). This precludes easy substitution of an alternate implementation.
Why not:
public Bar DoWork( IExternallyKnownResource r ) { ... }
IMO, you're best off accepting a configuration object as a single parameter to your Foo constructor, rather than a dozen (or so) separate parameters.
Edit:
there's no one-size-fits-all solution, no. but the question is fairly simple. i'm writing something that consumes an externally known entity (httpwebrequest) that's already self-validating and has a ton of potentially necessary parameters. my options, really, are to re-create almost all of the configuration parameters this has, and shuttle them in every time, or put the onus on the consumer to configure it as they see fit. – kolosy
The problem with your request is that in general it is poor class design to make the user of the class configure an external resource, even if it's a well-known or commonly used resource. It is better class design to have your class hide all of that from the user of your class. That means more work in your class, yes, passing configuration information to your external resource, but that's the point of having a separate class. Otherwise why not just have the caller of your class do all the work on your external resource? Why bother with a separate class in the first place?
Now, if this is an internal class doing some simple utility work for another class that you will always control, then you're fine. But don't expose this type of paradigm publicly.

Useful mini patterns (not design patterns)

My most used mini pattern is:
VideoLookup = new ArrayList { new ArrayList { buttonVideo1, "Video01.flv" },
new ArrayList { buttonVideo2, "Video02.flv" },
new ArrayList { buttonVideo3, "Video03.flv" },
new ArrayList { buttonVideo4, "Video04.flv" },
new ArrayList { buttonVideo4, "Video04.flv" }
};
This means that rather than a switch statement with a case for each button I can instead just compare the button that was clicked with each item in the ArrayList. Then when I've found a match I launch the correct file (although the action that's the 2nd part the "lookup" could be a delegate or anything else).
The main benefit is that I don't have the problem of remembering to add all the correct code for each switch statement case, I just add a new item to the lookup ArrayList.
(Yes I know using an ArrayList isn't the best way to go, but it's old code. And I know that looping through an array each time isn't as efficient as using a switch statement, but this code isn't in a tight loop)
Does anyone else have any mini-patterns they use that save time/effort or make code more readable? They don't have to just be GUI related.
Update: Don't copy this code, I knew it was bad, but I didn't realise how bad. Use something like this instead.
Hashtable PlayerLookup = new Hashtable();
PlayerLookup.Add(buttonVideo1, "Video01.flv");
PlayerLookup.Add(buttonVideo2, "Video02.flv");
PlayerLookup.Add(buttonVideo3, "Video03.flv");
PlayerLookup.Add(buttonVideo4, "Video04.flv");
string fileName = PlayerLookup[currentButton].ToString();
please please please omg use this version.
VideoLookup = new Dictionary<Button, string> {
{ buttonVideo1, "Video01.flv" },
{ buttonVideo2, "Video02.flv" },
{ buttonVideo3, "Video03.flv" },
{ buttonVideo4, "Video04.flv" },
{ buttonVideo4, "Video04.flv" }
};
You could just create a struct or object that has a button reference and a string representing the file name and then a List of these things. Or, you could just use a Dictionary and make it even easier on yourself. Lots of ways to improve. :)
On the subject of switches, I write this kind of thing a lot:
public Object createSomething(String param)
{
return s == null ? new NullObject() :
s.equals("foo") ? new Foo() :
s.equals("bar") ? new Bar() :
s.equals("baz") || s.equals("car") ? new BazCar() :
new Object();
}
I think it looks more readable compared to regular switch statements and has the ability to have more complex comparisons. Yeah, it'll be slower because you need to compare each condition but 99% of the time that doesn't matter.
In Java, I sometimes find that private inner classes which implement a public interface can be very helpful for objects composed of tightly-coupled elements. I've seen this mini-pattern (idiom) discussed in the context of creating UIs with Allen Holub's Visual Proxy architecture, but not much beyond that. As far as I know it doesn't have a name.
For example, let's say you have a Collection interface that can provide an Iterator:
public interface Collection
{
...
public Iterator iterate();
}
public interface Iterator
{
public boolean hasNext();
public Object next();
}
If you have a Stack that implements Collection, then you could implement its Iterator as a private inner class:
public class Stack implements Collection
{
...
public Iterator iterate()
{
return new IteratorImpl();
}
private class IteratorImpl implements Iterator
{
public boolean hasNext() { ... }
public Object next() { ... }
}
}
Stack.IteratorImpl has complete access to all of Stack's private methods and fields. At the same time, Stack.IteratorImpl is invisible to all except Stack.
A Stack and its Iterator will tend to be tightly coupled. Worst case, implementing Stack's Iterator as a public class might force you to break Stack's encapsulation. The private inner class lets you avoid this. Either way, you avoid polluting the class hierarchy with something that's really an implementation detail.
In my last job I wrote a C# version of the Enforcements concept introduced in C++ by Andrei Alexandrescu and Petru Marginean (original article here).
This is really cool because it lets you interweave error handling or condition checking in with normal code without breaking the flow - e.g.:
string text = Enforce.NotNull( myObj.SomeMethodThatGetsAString(), "method returned NULL" );
This would check if the first argument is null, throw an EnforcementException with the second argument as the message if it is, or return the first argument otherwise. There are overloads that take string formatting params too, as well as overloads that let you specify a different exception type.
You could argue that this sort of thing is less relevant in C# because the runtime checking is better and already quite informative - but this idiom lets you check closer to the source and provide more information, while remaining expressive.
I use the same system for Pre and Post condition checking.
I might write an Open Source version and link it from here.
for when I'm churning out code fast (deadlines! deadlines! why am I on stackoverflow.com? deadlines!), I wind up with this kind code:
Button1.Click += (o,e) => { DoSomething(foo); };
Will this cause me memory leaks at some point? I'm not sure! This probably deserves a question. Ack! Deadlines!
For Windows forms I'll often use the Tag field to put a psuedo-command string so that I can have a single event handler for a shared set of buttons. This works especially well for buttons that do pretty much the same thing but are parameterized.
In your first example, I would set the Tag for the buttons equal to the name of the video file -- no lookup required.
For applications that have some form of text-based command processor for dispatching actions, the Tag is a string that is just fed into the command processor. Works nice.
(BTW: I've seen the term "idiom" used for mini-patterns...)
A new idiom that I'm beginning to see in C# is the use of closure parameters that encapsulate some configuration or setup that the method will need to function. This way, you can control the relative order that code must run from within your method.
This is called a nested closure by Martin Fowler: http://www.martinfowler.com/dslwip/NestedClosure.html
Perhaps there's already a better way of doing this (vbEx2005/.Net2.0), but I've found it useful to have a class of generic delegate-creators which accept a method that takes some parameters, along with the values of either all, or all but one, of those parameters, and yields a delegate which, when invoked, will call the specified function with the indicated parameters. Unlike ParamArray-based things like ParameterizedThreadStart, everything is type-safe.
For example, if I say:
Sub Foo(param1 As Integer, param2 As String)
...
End Sub
...
Dim theAct as Action(of Integer) = _
ActionOf(of Integer).NewInv(AddressOf Foo,"Hello there")
theAct(5)
...
the result will be to call Foo(5, "Hello there") on object where Foo was declared. Unfortunately, I end up having to have separate generic classes and methods for every different number of parameters I want to support, but it's nicer to have all the cut-and-paste in one file than to have extra code scattered about everywhere to create the appropriate delegates.

Categories

Resources