I have a C# base class that I was to associate information with on a per-type (rather than per-instance) basis. Essentially I want all child classes to present an Icon and a FriendlyName that represents the type. I'd like to not have to create a type instance to get this information and I want to require that all child classes provide this information. Ideally it would be in the interface that the base derives from.
I tried to use a class Attribute, but it requires a constant value, so while I can set the FriendlyName, I can't set the Icon, and I can't see a way to make the Attribute required anyway, so child classes could get away with not having it (until run time).
I added a static Property to the base that children can hide, but that's kind of ugly and the values from the base are really nonsensical. It can't know what the name would be for a child. I could have the base throw in the Property, but again, that wouldn't get caught until run time.
Anyone have any ideas on how I might implement something like this? Is there a pattern I'm missing? Any out-of-the-box thinking is encouraged as well.
Edit: Really what I need to the ability to require class Attributes along an inheritance tree and be able to use an embedded resource to set those attributes. All of the information that will be returned really is static and known at compile. I just can't figure out a way to nicely expose it.
Edit 2: Here's a more concrete example of what I need:
Let's assume I have a base class:
abstract class Vehicle { ... }
I then have two children:
class Car : Vehicle { ... }
class Truck : Vehicle { ... }
I'd like to be able to get an Icon representing a "Car" or a "Truck" without having to create an instance of one (a la Car.Icon) since all vehicles of a given type will all have the same icon.
I also want to ensure that all Vehicle-derived Types expose the same way to get this Icon in case someone comes along in the future and adds a new class
class Airplane : Vehicle { ... }
Edit 3: Why do I need this? Well we have an app that can take plug-ins. The plug in is defined by a type, and when the type is loaded, we show the user an icon and name. When they click the icon, it creates an instance of that type (and gives them a dialog for naming the instance, etc). I don't need or want to have to create an instance of the type to get the icon.
If you want to absolutely dictate that the child implement this, then the only way I see doing it is making the base class abstract, and expose instance properties to return the icon and friendly name.
These would be abstract, not virtual, so you force the implementation by the derived class. I know it's not clean, in that it is information that is better stored on the type level, but it's the only way I can see to enforce this requirement at compile-time.
I think the point you may have missed is that you can't override static properties for a good reason -- namely that when you're writing code to call it, you don't have an instace, so the complier will statically link it at that time -- if you need polymorphism, you need to be working with an instance for the runtime to work out which version of the method to call.
EDIT: (In response to your EDIT2)
What scenario would you want to be calling this from?
If you're wanting to show your icon against an instance, you've got an instance, so why not have it as a property on the instance (because, after all, somebody might override your Car to create a SportsCar and want a different icon for it) -- in effect you're asking for a property of your object, albeit one that matches the conceptual model (so it's not the number of wheels, the max speed, etc; but something to visualise it to the end user)
EDIT2: (In response to your EDIT3)
The approach I'd do would be something along the lines using an attribute to identify which embedded resource to use as the icon for the respective type (so you don't need an instance), and use reflection to read the value. You could define your own custom attribute, or look at ToolboxItemAttribute which might be of use.
Maybe what you can do is to define an attribute that will be used for registering that object in your plugin system.
This way you will enforce the developer of the class to assign the attribute in order to work within your plugin system.
Maybe you can use an approach like the ToolboxBitmapAttribute, where you can set an image found into a resource of your dll.
Related
We have a system that creates dynamically defined objects as a core aspect of the processing. I would like to be able to create an class object and make these objects instances of this class, implementing all of the functionality that this particular object has.
The problem is, these objects really need to dynamically inherit from a base class, and override null methods etc. In essence, I need something of a dynamic class structure (and I have proposed compiling the definitions into a proper class model, but that is some distance away). The best approach i can come up with is to create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented.
I have also looked at Castles DynamicProxy approach, which might be a useful route (intercepting the calls and actioning them if appropriate), but this seems more complex than it should be.
So any suggestions? What would the best, most .Net-like approach to this be? As I look at the problem, it seems like there should be a really good and easy solution.
Just to help, a simple example (semi-pseudocode - I know it is not fully working):
class thing
{
public void Process()
{
foo();
bar();
}
private foo(){}
private bar(){}
}
a=new thing() {foo=DoFoo}
b=new thing() {bar=DoBar}
I want to be able to call a.Process and b.Process, and have them both run. Bear in mind that these objects have some 20-30 properties/methods that might need setting (setting them is easy, but some of them might be substantial methods)
create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented
This sounds a lot like the "decorator" design pattern might be a good choice for you here. You basically implement a set of functionalities and then build your objects by subsequently assigning several "decorations" (functionalities) to a baseobject.
http://www.codeproject.com/Articles/479635/UnderstandingplusandplusImplementingplusDecoratorp seems to be a very good summary with clear examples on how and when to use decorator patterns
However if your properties heavily interact with each other, or need a significant different implementation depending on other "decorations" i would not suggest using a decorator. In that case you might need to get a bit more specific on your requirements.
Not sure if I really understand your requirements, but have you looked at the DynamicObject class?
The idea behind it is that you derive from it, and every time a member is accessed, it gets a call to TryGetMember, TrySetMember, or TryInvokeMember for methods, where you can do your custom logic.
You can make a base class inheriting from DynamicObject then make the set of classes you want by deriving from that base class, implementing the logic on each one of them, this way you can have both defined members, and other non-defined ones which you can use using a dynamic type.
Check the documentation on MSDN for DynamicObject
Alternative
Otherwise, as a very simple solution and based on the pseudo-code you provided only (which admittedly might be a little simple for the requirements stated in the question), you could just make a Thing class which has Action properties:
class Thing
{
public void Process()
{
if(Foo!=null) Foo();
if(Bar!=null) Bar();
}
public Action Foo {get;set;}
public Action Bar {get;set;}
}
var a=new Thing() {Foo=DoFoo};
var b=new Thing() {Bar=DoBar};
a.Process();
b.Process();
I am writing a class library to model a car. I have a base class called "Dimension", which provides the properties/methods for measurements of the cars (Eg length, width, etc). This is for the entire car in general.
However, I need to provide dimensions on individual parts too (E.g. wheels). Wheels, for example, only use a subset of the information. Eg the width, and not every readily available property. Does it make sense to use the same base class for this or do I need to look into something more sophisticated to model this accurately?
Thanks
A Car has Dimension; a Car is not a subclass of Dimension.
By making Car inherit from Dimension you are squandering the only available inheritance slot available to you in C#.
There is little benefit to be had from using inheritance to share properties amongst concrete subclasses, especially now that C# has things like automatic properties to save typing. Better to save your inheritance slot for some future requirement.
I would suggest instead giving the Car object properties to define the dimensions as appropriate, and perhaps have it (and Wheel) implement an interface, say IDimension, to allow you to treat Car and Wheel polymorphically if you want to write code that can be applied to any objects that have dimensions:
Why not just use the base class with only the properties that are shared by all the children and then add as needed. I had a similar issue and in my first draft did what you did. After I had finished a lot of my application I broke it down and rewrote most of it so the base class had just what was necessary and then added on as needed. I think first method is a lot quicker and when you have time you can go back and make it all nice and pretty.
If everything has dimensions then put it in your base class, if not then use an interface.
It makes sense for the base class to only contain methods or properties that are common between all derived classes. If you find that a subset of children also contain some similar properties it may also be worth creating a second base class which is derived from the first. I usually end up with a set up of an interface which a few base classes implement followed by a number of concrete classes.
Though granted this may not be visible always at time of coding. I always find refactoring code good practice near the end of the code completion.
Though in your case dimension may not be the best base class. It may be worth using a dimension interface instead to allow car to extend from a different class if needed.
I'm trying to make a small application that can edit the data files from an earlier project. I have access to that projects "data classes" (pretty dumb classes whose main purpose is to expose it's (public) member variables) that can read/write to the files. All I have to do is make a GUI that can edit the different member variables that each data class have (preferably without modifying the data class) and I'm trying to figure out how to do this so that it will be easy to adapt for future changes/additions.
(I don't feel like I can assume that all member variables should be editable, might only be a selection of them).
All the data can be converted to/from strings (numbers and text) and I don't see much problem in generating textboxes and/or something like a DataGridView in the GUI, but I'm not sure as to how I would like to represent the data needed to generate those.
My first thought was to use a list with all variables for each data class. With each row in the list containing the name+description of the variable (for the GUI), a pointer to the variable in the data-class and perhaps some form of validation-function for different variables.
Store that list in a class that inherits the original data-class (and that implements an interface/abstract-class for any specific GUI-related functions (load/save etc.)).
The thing that makes me worry about this solution is just that I feel like this should be a somewhat common problem and I'm a bit rusty when it comes to OO and this solution smells like something I'd write if I had to do it in C.
There might even be a handy language construct, design pattern or something that is suitable but I don't know what to search for.
Does this approach even seem sensible?
Reflection is your friend in this case. Your data classes have a structure which can be explored using that class's Type. A Type is the base class for metadata concerning a class or structure, and includes methods to, for instance, get a list of all fields, properties and/or methods belonging to that class. The objects representing these class "members" can then be used to set or get field or property values, or invoke methods, given an instance of an object of that type.
A reflective algorithm can be designed to handle any object structure it is given, and it doesn't have to know those structures at compile-time unlike an algorithm based on static types. The downside? It's slow, and you get very little compile-time checking of your algorithm so it can fail at run-time in unexpected ways.
Here's something to get you started:
//statically set up an instance of some arbitrary object
MyClass myObject = new MyClass();
myObject.Field1 = "Hello";
myObject.Field2 = "World";
//This method is available on any object, and produces a Type representing the class definition
Type myType = myObject.GetType();
//C# also has a typeof() keyword that works when you have a static type and not an instance
myType = typeof(MyObject);
//Interrogate the Type instance to get its fields
FieldInfo[] fields = myType.GetFields();
//then, iterate through the fields to perform some (useful?) work.
//Here, we are outputting a list of paired field names and their current values.
//You will probably want to instantiate a Label and Textbox representing this value
//and show them on a Form.
foreach(FieldInfo field in fields)
Console.WriteLine(String.Format("{0}: {1}", field.Name, field.GetValue(myObject));
To handle editability, you will need some sort of record of what the user has permission to change and what they don't. If that information will never change from user to user, you can incorporate that information into the data class itself using attributes (which won't change the "interface" of the object; it'll still have all the same members, but those members will have additional metadata). You could also create another set of classes that implement an interface defining each one as a set of "field permissions" for its parent class, and then you can dynamically construct an instance of the "field permission" class with a Type instance representing your object definition, and knowledge of the name of the interface that field permission objects implement.
I got a requirement in my project to add another property to some class.
Now I want to avoid changing the class because I figured it shouldn't be aware that he has this property (this property only has significance in the context of this project).
The way I thought to accomplish this was (Please critic this because I wanna know if there are simpler ways of doing this)
Adding a new singleton class that has a mapping between objects of my class and the type of the property I wanted to add
adding in this class an extension method (extension property?) to access the mapping and fetch the property.
Is there a simpler alternative?
Is this just unnecessary complexity? Maybe I should just add a new property to my class?
Thanks!
The design you've described is actually the one used by Microsoft to implement the DependencyProperty system and, in particular, Attached Properties, though in the greater context of a binding framework. That said, using a dictionary with 'attached' data is a very typical solution when you need to tag a class with additional context for a particular use, but don't want to modify the class.
Why do you say "not inheritance"? Surely the way to do this, if you don't want to alter the original class, would be to inherit from the original class and then add your property to the derived class?
BTW, there are only extension methods, not properties, so you can't do it via property.
I would suggest the DECORATOR pattern. I know you say you don't want to use inheritence, but sometimes it's cleaner to do so. The pattern only uses inheritance to define the interface.
An extension method makes sense and it's also relatively simple.
[visibility] [type] [methodName](this [class to extend] c, ... more args if necessary)
{
....
}
Adding a property doesn't break the class's interactions with existing clients, so that really seems the "simplest" approach.
More important, though, is the function of the new property. Is it logically part of the existing class? Change the class. If not, then an extension method might be preferable, but the problem then becomes the visibility of the extension method, and scope of its clients.
As always, complexity is the enemy. In this case, it sounds as though the singleton is a very complex solution, and the extension method is hit-and-miss, depending on scope and visilbity issues. Changing the class is simplest, and will probably make long-term maintenance much easier.
UPDATE: Note that extension methods are static, and that makes it pretty difficult for the extension method to hold data of any time, as a property would be exptected to do.
SECOND UPDATE: If you have access to the source for the class, consider making it a partial class, and put your new property in a separate file, but part of the same partial class. This keeps it separate from the main body of the class for maintenance purposes, and will work with most ORMs. However, there is a restriction that the partial class members have to be in a single assembly.
Define a Nullable values with their Properties(while the Property has significance only for this project)
your major problem is that you don't want to change the class itself because this requirement is ONLY for 1 project (build), i think you are considering SOLID priniciples, one of these principles is OCP (Open-Closed Principle), that is,
your Entity must be open for extension
but closed for modification
I have a warehouse. Sometimes I want to lookup a box location by a name, sometimes by a description, sometimes by a UPC, maybe something else, etc. Each of these lookup methods call the same various private methods to find information to help locate the data.
For example, upc calls a private method to find a rowid, so does name, so does X. So I need to have that method for all of them. I might use that rowid for some way to find a shelf location (it's just an example.)
But my question is should I have an abstract class (or something else) because I am looking up my box in different ways.
In other words, say my code for lookups is very similar for UPC and for location. Each method may call something with (select * from xxxx where location =, or select * from xxxx where upc =). I could just create two different methods in the same class
LocateByUPC(string upc)...
LocateByLocation(string location)...
LocateByDescription(string description)
... again, this would be in one big class
Would there be any reason that I would want a super class that would hold
abstract class MySuper
{
properties...
LocateBox(string mycriteria)...
}
and then inherit that and create a second class that overrides the LocateBox method for whichever version I need?
I don't know why I'd want to do this other than it looks OOD, which really means I'd like to do this if I have a good reason. But, I know of no advantage. I just find that my class gets bigger and bigger and I just slightly change the name of the methods and a little bit of code and it makes me think that inheritance might be better.
Using C# if that matters.
Edit - Would I do this if I only gave someone a .dll with no source but the class definition? The class def. would tell my properties, etc. and what methods to override.
Neither
neither using an abstract class nor an interface will simplify the protocol, i.e. you will still end up with a bunch of LocateXXX methods
I would recommend having a generic Locate(string criteria) method as the basis, and only defining specialized method signatures for the ones you know you will use frequently; the generic can be a catch-all for future expansion in case you need it (and relying on the generic simplifies coding and testing)
It sounds like you might want to implement the design pattern called Template Method. Basically you would define the outline of the lookup algorithm in a base class as final methods, placing common code in those methods. For the methods that require different behavior depending on the type, simply have the base class' final methods call protected methods in the children, and have each child type implement that behavior.
You can take a look online at some resources, just do a google search for Template Method design pattern. Hopefully it will shed some light on your question.
Abstraction helps when you have multiple implementations. And for future-proofing (hoping that a newer implementation will crop up). An interface acts as a contract between the client and the implementer. This is an invariant. Implementations are free to add any number of methods they wish to. Do you have any such needs?
Does that help answer your question?
What you are proposing is (basically) the Strategy pattern. I don't like to link to wikipedia, but its a good place to start at least. Take a look at the pros and cons and see if it would be beneficial to you.
I don't think there's really a need for you to do it this way. You can simply make the LocateBox method public and have it call private helpers based on which search you want to do. It's generally a bad idea to overly complicate your class structure just for the sake of using some OO design principles. Wait until you find a need for them, and then refactor appropriately. This will help point out what is really necessary and what is a waste of your time.
Edit: Another approach that I was thinking of would be to create a data class that has properties based on the various things you could search by. Ie. a BoxSearchData class that has properties such as UPC, etc, and then pass that to LocateBox() and construct the query as necessary based on the properties that are null. This would help you construct searches on multiple criteria later down the line.
It wouldn't seem necessary in my opinion. Just have a single repository that has the different search functions. Then just use the functions you need when they're needed.
However, the interface portion would only become useful if you have tools that are queueing up different types of searches. Then you could have a factory creating different types of Search classes that all implement an Interface. At which point you could enumerate through your queued Search classes, cast to the interface, and execute the function which would be virtual and point to the correct search type. Example: ReturnDataObject GetItem(object param);
On a side note, there are other uses for interfaces when pulling data. That is just the first example that comes to mind.
When in this example you look closely, you see that only the property, used for lookup, changes. When representing this in an OO way, you end up with a class I would call "Lookup" (representing a search, maybe in SQL, maybe in another query language: an object that can return a rowId based on some property and searched-for value of that property.
The real behavioral change would be in the query language. So if you are to create an abstract class or an interface, it should serve that purpose. The concern of variation in property and value can be separated by adding a "property" argument to the query call.
An abstract class is useful when you need a substantial amount of
functionality to be identical across the subclasses, for example in a
shopping cart with multiple methods of payment available, you could
have an abstract class which defines a generic payment method, and
have subclasses inherit from the superclass for each actual payment
method you want to support (paypal, credit card, account, etc). The
mechanics of how a payment is authorized would be different for each
subclass, but they all perform essentially the same function - they
validate that a user can prove that they can pay for the goods or
services in question.
An example of where an interface is useful is where you have unrelated
items that need to provide some similar functionality in a uniform
way. For example, you might have a CMS where articles are stored in a
database, but where the system caches them to disc as well as HTML
pages until the article in the database is modified, at which point
the physical file is deleted until the next time someone access the
copy in the database. Your CMS might also support the ability for
users to upload images, PDFs, etc to be stored for access on the disc,
but you definitely don't want these files to be deleted as the copy on
the disc represents the file itself and not a cached version. In this
case, you could create a Cacheable interface that says what methods a
class which is cached to disc needs to implement, while leaving it up
to the class itself to implement them. This makes more sense as
classes that represent different kinds of data almost certainly need
to implement their caching scheme (if any) differently.
Every class that allows caching would be defined as Class
implements Cacheable, which is something you can then check for in
your code. Less experienced coders might test the class of an object
they are working with by getting the class and processing the result
with a big switch statement. This isn't the correct approach because
it means that you're assuming that certain classes objects implement
certain functionality, and if you add a new class to the system you
need to modify every switch statement in your software to take it into
account. If yo uimplement an interface you can test if an object
implements that interface with the instanceof keyword.
if ($thisObject instanceof Cacheable)
{
// Manage item's cache
}
This approach is better because it eliminates the switch statement and
thus makes your software easier to maintain. If you add a new class
to the system that also implements its own caching scheme then you
just need to declare that it implements Cacheable. As the interface
requires all classes to implement it to declare the methods specified
in the interface you can be sure that any class that implements
Cacheable will provide certain methods for you to use. Your code
doesn't need to know how the class implements these methods, just that
it does implement them.
These concepts are somewhat trickier to explain than to actually learn
to use I'm afraid, hopefully I've got the basic ideas across well
enough for you to figure them out for yourself.
Obviously the entity that is polymorphic here is the constraint. Using string is the quick and dirty way of achieving the same but your type system is completely out of the loop and garbage string values will be just as valid for input as meaningful constraint specs.
So,
LocateBy (Constraint constraint);
and
abstract class Constraint {
String toString ();
}
class LocationConstraint extends Constraint { /* ... */}
etc.