Constructors vs Factory Methods

Topics: Developer Forum
Nov 5, 2010 at 7:41 PM

Hi all,

What follows is a question/suggestion for future consideration. I've recently been migrating an engine to Farseer 3.0/3.1 and I've noticed that all the constructors of the Body class have been made internal, and the main job of creating stuff relegated to factory methods and/or World.

My question is: why isn't the constructor actually used? Taking the example of the Body class, for instance, it makes sense that creation is automatically tied in to registration on a World, I agree - but it would be no problem to do it in the constructor. Actually, it appears there is now a single code path that is able to build a Body, so it makes sense for that code to be the function that constructs a Body.

The advantage of having the Body class have a constructor, besides arguably making it more conformant with standard C# practice, is that it would allow the creation of Body instances using expressions, for instance using a LINQ query, like so:

var bodies = from hit in hitList
             select new Body(world)
                 IsStatic = false,
                 IsBullet = true

It takes a rather more roundabout way of doing it without the constructor. Also LINQ queries are not the only interesting places where constructor expressions can be useful, so I think in general whenever possible I think it makes sense to keep them.

What do you think? Is there a good reason for not having constructors that I'm not considering?

Cheers and keep up the excellent work,


Nov 5, 2010 at 10:26 PM

That definitely looks like something I am willing to add. Of course using LINQ queries generate garbage, but as long as we didn't do anything like what your showing above inside the engine any garbage would be the users responsibility. The only reason we have the constructors the way they are is to keep the base engine as close to Box2D as possible. I am a big fan of making programming easier so I definitely think we should start pushing for better API's like this.

My vote is Yes!!!

Nov 7, 2010 at 1:41 AM

I see no problem with having multiple ways of creating bodies, shapes and fixtures. I've added the change to change-set 79595

Nov 7, 2010 at 9:23 PM

Hey, that was fast :)

This will make life much more easier for constructing and initializing bodies.

Thanks for the fast response and keep up the good work,


Nov 7, 2010 at 9:37 PM

The implementation has not been tested. If you find any problems using the constructors, please file an issue with the details.