i'm working on a tile editor. In the editor you can load a tile map. Each tile map can have multiple layers. A tile map has a list of it's layers. I now need tile map properties in the layer class (things like tile width/height e.g.). I'm now asking myself what is the best way to do this.
I could make a bidirectional relationship by introducing a tilemap property in the layer class, so that i have access to everything i need from there. But then i would have to take care of two sides of the relationship.
I could give all the needed properties to the layer class with the constructor, but then they basicly become layer properties (aka they are different objects for every layer).
Same as 2 but give the properties to the layer with "ref" paramter.
I could make a class called something like TileMapLayerProperties where i put all the properties in and then pass the object to the layer classes. Advantage would be that all the properties would be the same and only the tileMapLayerProperties-reference would be per instance. Another advantage would be the "definition" of the layer constructor becoming much shorter.
So any suggestions / tips would be appreciated.
A bi-directional association (1) might be OK or not, depending on what properties and methods a tile map contains and what a layer should be able to know and access. If a tile map has a DeleteAllLayers method and layers should not be able to call it, then layers cannot have direct access to their parent.
Creating a dedicated property object (4) seems more clean to me. That way you have one object with all necessary information that you can pass around, but it does not contain more than that, especially it does not allow calling destructive methods etc.
Passing the properties to the constructor (2) is similar to (4), but more verbose and less object-oriented. It's fine when you have 1 or 2 properties, but with more than a few it gets ugly and unmaintainable.
But there is another problem: If the properties are of immutable types (e.g. int, string), then the layers do not see changes made in the map. They only see their private copy!
I don't understand (3). How does the ref keyword change (2)? It only allows the callee to change the value of a variable passed by the caller. Or do you mean objects with reference types?
Another solution
Interfaces would be another way to solve this. You could create a ITileMapLayerProperties interface that provides all the properties and pass it to the layer's constructor. The map could either implement the interface itself or contain a TileMapLayerProperties object that implements the interface. But the layer does not need to know this.
Option 2 would work for what you are trying to do, and you may not need to include the 'ref' keyword.
I'm curious, what kind of datamembers are you trying to access from the child classes? If they are collections then you may not need the 'ref' keyword.
Another option would be to make the parent class static, but I'm not sure if this is the outcome you're looking for. Can you load more than one tile map at a time? If not, consider the static class option.
I think option is 3 is better. You can pass a reference of your ParentClass to the ChildClass and can have directly access to all public properties. I suggested it better because what ever changes you will make whether from ChildClass or ParentClass, all other layers will inherit those changes.
Related
I have a question about keeping track of objects in different layers of a software application. In my application, I have objects in the domain layer (e.g. LineShape) that are used to represent business entities, and I have corresponding objects in the presentation layer (e.g. System.Windows.Shapes.Line) that are used to display these entities on the screen.
My question is, how do I keep the correspondence between the domain objects and the presentation objects, so that I can identify which domain object is represented by a given presentation object?
For example, if the user clicks on a System.Windows.Shapes.Line in the user interface, how can I determine which LineShape in the domain layer this object represents?
I have thought of a few potential solutions, but none of them seem ideal, especially for larger and more complex object models.
One solution is to use a dictionary that maps presentation objects to domain objects. In this case, when the user clicks on a System.Windows.Shapes.Line, I could look up the corresponding LineShape in the dictionary.
Another solution is to use an ID for both the presentation and domain objects. This approach has the advantage of being simple, but it seems strange to me to use IDs for every object in a domain-driven design, as IDs are typically used only for entities.
Are there any best practices or established patterns for solving this problem?
Use an Id for objects both in Presentations and Domain. This sounds a
bit strange to me, because as far as I am aware, we are not supposed
to use Id for every object in DDD, just for entities.
Perhaps you would be looking at an address rather than an ID. Even values must somehow be addressed so they can be replaced. Such an address may be a class property's name, an array's index, etc.
If you see the whole drawing as a collection of shape values then you could always use the shape's index as the address allowing to replace that specific shape value in the collection.
However, note that the address is only valid as long as you are working against the expected drawing's version.
Furthermore, you could also use the combination of all shape's properties to identify a given shape to modify. If you have two identical shapes (same shape, position, layer, etc.), does it matter which one you re-shape? The final drawing would look exactly the same.
In the end if it makes your life easier to model shapes as entities and given them an ID then perhaps that's the right model too even though you may not care about the specific shape's entire lifecycle.
Finally, note that if shapes are values then you can't possibly keep a reference to them in view models since values are immutable. Also, if shapes are entities, but the drawing is the Aggregate Root then shape entities shouldn't be accessible outside the root. Therefore it most likely only makes sense to reference a domain's Shape in the view model if it's an AR (unless you violate the visibility rule, but still enforce invariants through root-handled events). Also note that address/ID references may be the only option if your domain model lives on another tier.
You've asked a somewhat broad question, so I will give what I think is a correct but general answer.
In WPF, one way or another, the on-screen controls will have a DataContext. The DataContext generally speaking should be the object you want to get a hold of.
This should be the case more or less regardless of what method you use to populate all the screen controls.
It may suit your program to create special viewmodel classes which bridge between your "native" data objects, in which case those viewmodel classes will be set as the DataContext objects. If you don't need the viewmodel then the native data objects will play that role.
If you are using events, then in the code-behind for the event you can directly access the DataContext property, cast it to the expected type, and off you go.
If you are using commands then generally they are part of the viewmodel object in the first place, so they can just act directly on the object which owns them.
I have a database that contains "widgets", let's say. Widgets have properties like Length and Width, for example. The original lower-level API for creating wdigets is a mess, so I'm writing a higher-level set of functions to make things easier for callers. The database is strange, and I don't have good control over the timing of the creation of a widget object. Specifically, it can't be created until the later stages of processing, after certain other things have happened first. But I'd like my callers to think that a widget object has been created at an earlier stage, so that they can get/set its properties from the outset.
So, I implemented a "ProxyWidget" object that my callers can play with. It has private fields like private_Length and private_Width that can store the desired values. Then, it also has public properties Length and Width, that my callers can access. If the caller tells me to set the value of the Width property, the logic is:
If the corresponding widget object already exists in the database, then set
its Width property
If not, store the given width value in the private_Width field for later use.
At some later stage, when I'm sure that the widget object has been created in the database, I copy all the values: copy from private_Width to the database Width field, and so on (one field/property at a time, unfortunately).
This works OK for one type of widget. But I have about 50 types, each with about 20 different fields/properties, and this leads to an unmaintainable mess. I'm wondering if there is a smarter approach. Perhaps I could use reflection to create the "proxy" objects and copy field/property data in a generic way, rather than writing reams of repetitive code? Factor out common code somehow? Can I learn anything from "data binding" patterns? I'm a mathematician, not a programmer, and I have an uneasy feeling that my current approach is just plain dumb. My code is in C#.
First, in my experience, manually coding a data access layer can feel like a lot of repetitive work (putting an ORM in place, such as NHibernate or Entity Framework, might somewhat alleviate this issue), and updating a legacy data access layer is awful work, especially when it consists of many parts.
Some things are unclear in your question, but I suppose it is still possible to give a high-level answer. These are meant to give you some ideas:
You can build ProxyWidget either as an alternative implementation for Widget (or whatever the widget class from the existing low-level API is called), or you can implement it "on top of", or as a "wrapper around", Widget. This is the Adapter design pattern.
public sealed class ExistingTerribleWidget { … }
public sealed class ShinyWidget // this is the wrapper that sits on top of the above
{
public ShinyWidget(ExistingTerribleWidget underlying) { … }
private ExistingTerribleWidget underlying;
… // perform all real work by delegating to `underlying` as appropriate
}
I would recommend that (at least while there is still code using the existing low-level API) you use this pattern instead of creating a completely separate Widget implementation, because if ever there is a database schema change, you will have to update two different APIs. If you build your new EasyWidget class as a wrapper on top of the existing API, it could remain unchanged and only the underlying implementation would have to be updated.
You describe ProxyWidget having two functions (1) Allow modifications to an already persisted widget; and (2) Buffer for a new widget, which will be added to the database later.
You could perhaps simplify your design if you have one common base type and two sub-classes: One for new widgets that haven't been persisted yet, and one for already persisted widgets. The latter subtype possibly has an additional database ID property so that the existing widget can be identified, loaded, modified, and updated in the database:
interface IWidget { /* define all the properties required for a widget */ }
interface IWidgetTemplate : IWidget
{
IPersistedWidget Create();
bool TryLoadFrom(IWidgetRepository repository, out IPersistedWidget matching);
}
interface IPersistedWidget : IWidget
{
Guid Id { get; }
void SaveChanges();
}
This is one example for the Builder design pattern.
If you need to write similar code for many classes (for example, your 50+ database object types) you could consider using T4 text templates. This just makes writing code less repetitive; but you will still have to define your 50+ objects somewhere.
I have a c# factory object which creates objects through factory methods, using a list of objects as a source.
The list of objects is created like this:
public WidgetFactory()
{
widgetLibrary = new List<WidgetModel>();
//Add all widgets
widgetLibrary.Add(new ClientsWidget());
widgetLibrary.Add(new InstallationsWidget());
etc.
and various parts of my application access this list in different ways to get the type of object it needs.
But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.
How can I alter my design to accomodate this need?
But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.
How can I alter my design to accomodate this need?
Typically, objects should not rely on the factory that creates them for construction, as it causes exactly this problem. If you can push in the reference to the factory, but not use it until it's needed, it may solve the issue.
If you absolutely need to do this, then the best approach may be to lazily instantiate the objects within the factory. Instead of having your WidgetFactory contain a List<WidgetModel> internally, you could use a List<Lazy<WidgetModel>>. This would allow the individual "widgets" to only evaluate as needed, which would mean that, when the widget in question tries to reference the factory, it'll be fully loaded.
But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.
How can I alter my design to accomodate this need?
Your model is wrong. Once a car has left the assembly line at the NUMMI plant, it doesn't depend on the plant to operate properly.
Also, I question the design of your factory. Why are you new instances the constructor. What purpose is that serving?
You should probably tell us a little bit more about your model and why you think you need this. Odds are, properly done, you don't.
The constructor for the WidgetFactory should not be calling the constructers of the things that it is building. Instead, the WidgetFactory should have a method (BuildWidgets) that does all of the work.
Then the other objects can make some use of the factory without causing this cascade of activity to start over again.
For starters, move Widget creation out of the WidgetFactory's constructor. This should happen either in an initialization method or on-demand in a CreateWidget(Type) method.
To make the factory instance available to the Widget instances, you can do one of a few different things:
Have WidgetFactory pass 'this' when it creates the Widget
Use the singleton pattern: add a static property WidgetFactory.Instance and initialize it once; have all WidgetFactory users access the property rather than create a new instance.
Use the dependency injection pattern -- difficult to provide a short description here.
I've got a class called List_Field that, as the name suggests, builds list input fields. These list input fields allow users to select a single item per list.
I want to be able to build list input fields that would allow users to select multiple items per list, so I have the following dilemma:
Should I do that through implementing a multiple_choice_allowed property into the existing List_Field property, or should I implement a Multiple_Choice_List_Field subclass of the List_Field class?
What's the engineering principle that I should follow when confronted with dilemmas like this one?
Take a look at the SOLID principles. They'll help you in your designs. In particular, the single responsibility principle will tell you not to mix the two concerns in one class, and the Liskov substitution principle will tell you not to create subclasses that break the contract of superclasses, like what you're also proposing.
So what would be the solution in your case? You could create an abstract base class that would be agnostic to the type of selection and then create 2 subclasses, one for single selection and another for multiple selection.
Depends on presence/lack of object evolution - if you want special case, sub-classing or injecting (DI) "select" behaviour (strategy) is good.
But if you also want to allow Field_List to change its behaviour dynamically, then property or mutating method is the only way to go.
Example: Sign-up screen with different "plans" - basic, where you can only select one thing and premium, where you can select as much as you want. Change of plan will switch between drop-down and multiple checkboxes, while still having the very same object including its contents.
I would vote for property/mutate method.
Personally I would go for the Multiple_Choice_List_Field way. I don't think there is a strict standard or an engineering principle that would make you to do it one way instead of another.
The more important thing here is to choose one way to do it and follow it whenever you encounter such a dilemma. You should be consistent, but which way you go is your own choice.
I would choose the subclass because this way you won't have to bloat your List_Field class with additional checks and requirements. Of course there are other considerations such as if you need to switch the multiple choice and single choice at runtime it would be better to go for the boolean property (although subclass will work too, but doesn't feel natural to me).
The other thing is for List_Field you might need more than a single property to handle multiple choices, depending on your current implementation. For example a new property to return an array of the selected items.
Just do it the way it's most comfortable for you to build and maintain (and eventually extend).
Should I do that through implementing
a multiple_choice_allowed property
into the existing List_Field property
If you can do that, I think it's the best solution because this way you avoid class proliferation.
If in doing that you are complicating too much your List_Field class, maybe create a derived class can have some benefits regarding the maintainability of your code.
Personally, I would say neither: instead use a constructor that takes multiple_choice_allowed, and then have a property exposing ListFields as a collection (with just one element when only one is allowed, all of them when more than one is allowed). Make it readonly (which means that you should copy it whenever you return the list).
I actually have 2 questions related to each other:
I have an object (class) called, say MyClass which holds data from my database. Currently I have a list of these objects ( List < MyClass > ) that resides in a singleton in a "communal area". I feel it's easier to manage the data this way and I fail to see how passing a class around from object to object is beneficial over a singleton (I would be happy if someone can tell me why). Anyway, the data may change in the database from outside my program and so I have to update the data every so often. To update the list of the MyClass I have a method called say, Update, written in another class which accepts a list of MyClass. This updates all the instances of MyClass in the list.
However would it be better instead to encapulate the Update() method inside the MyClass object, so instead I would say:
foreach(MyClass obj in MyClassList) {
obj.update();
}
What is a better implementation and why?
The update method requires a XML reader. I have written an XML reader class which is basically a wrapper over the standard XML reader the language natively provides which provides application specific data collection. Should the XML reader class be in anyway in the "inheritance path" of the MyClass object - the MyClass objects inherits from the XML reader because it uses a few methods. I can't see why it should. I don't like the idea of declaring an instance of the XML Reader class inside of MyClass and an MyClass object is meant to be a simple "record" from the database and I feel giving it loads of methods, other object instances is a bit messy. Perhaps my XML reader class should be static but C#'s native XMLReader isn't static?
Any comments would be greatly appreciated.
For your first question, I would suggest putting an update method in MyClass. It sounds like you may be instantiating multiple copies of the same object, and perhaps a better solution would be to update the original MyClass objects directly through their update methods.
This would also give you the added advantage of being able to update individual objects in the future and should be more maintainable.
For your second question, it sounds like MyClass contains data from a database, making it an entity object. Entity objects shouldn't contain business logic, so I think you'd be okay having a Service class use the XMLReader to perform operations on the data and then use the getters/setters to manipulate the data in the object. Same as before, this has the advantage of keeping your code loosely coupled and more maintainable.
Do not include Update() within the class. I know it seems tempting because it the update call "easier" but what that would be creating dependencies. (Presumably) MyClass contains db data because it is a domain object which is represents the state of some real world "unit" (tangible, conceptual, or otherwise). If you include an update() method; now you're domain object is not only responsible for representing the state of some logical "thing", but it is also responsible for persistence logic (save, load, new, delete). You'd be better off creating a service which handles those responsibilities. This relates to the design principle of high cohesion, ie. each class has only 1 responsibility (or type of responsibility at least). eg.... persistenceService.saveUser(myUser);
This is basically the same question, except now you are talking about making your class directly dependant (as a descendant in this case) of a specific type of persistence (writing to xml file) which is even worse than having your class be dependent on persistence in a more generalized way.
Think about it like this when trying to make design decisions... plan on change (instability, chaos, or whatever you would like to call it). What if a month from now you need to switch out the XML persistance for a database? Or what if you all of a sudden have to deal with MyClassVariantA, MyClassVariantB, MyClassVariantC? By minimizing dependencies, when you do have to change something it won't necessitate a cascade of changes throughout every other part of your application.