I am trying to use selective features of two classes into 3rd class. For example, I have Button1 class which creates a fancy button border and Button2 class which writes a the text in colorful format. Now these classes are provided to me by 3rd party vendors where i dont have access to the code. The classes are not sealed so i can inherit and both are derived from the base Button class.
Now my requirement is to create a third class named Button3 class which had the functionality of both making fancy border and colorful text. Ideally, i would have inherited from both classes and used the specific functions. This is not possible in C# as it doesnt have multiple inheritence.
I was reading, that interfaces help achieve results in this case. I would request someone to guide me how to use the specific functionality of two classes in one class.
As others have said, if your application does truly need to inherit from the two UI classes given then you won't be able to do this.
More generally than with a UI, here's a to think about this:
Full inheritance implies an "is-a" kind of relationship. Your buttons with fancy borders are buttons, but they can't be buttons with fancy text.
Interfaces define a "has-a" relationship. Here you have the "ability to set a fancy border on a button" and an "ability to set fancy text on a button". In those terms there's nothing to stop you applying both "abilities" to the same button class.
So an interface lets you do aggregation. Consider two classes DoerOfThis: IThis and DoerOfThat: IThat. To create a third class Something that does both DoThis and DoThat, aggregate:
public class Something : IThis, IThat
{
public This DoerOfThis { set; }
public That DoerOfThat { set; }
public void DoThis()
{
DoerOfThis.DoThis();
}
public void DoThat()
{
DoerOfThat.DoThat();
}
}
Try to use Abstract Factory Pattern.
You can't just take random parts of different classes and combine them, even if C# had multiple inheritance. The problem is that the methods you need from each only work when they live inside the class and work together with the other methods and private state in that class. If you try to mix and match methods from one class with another they won't be able to share their internal state. So the next thing you might try is to use containment and have two copies of the internal state, but that leads to problems trying to keep them synchronized. Plus now both classes want access to the paint methods, etc. Instead of working together, they will most likely fight each other and paint over each others changes. It's difficult to get this right.
What you need to do is to take the source code for one of the two Button classes and modify it using the source code of the other Button class as inspiration (it's unlikely you can use the code directly). If you don't have access to (or the legal right to use) the source code then I'm afraid that you can't do it this way.
Your remaining options are:
Contact the authors of Button1 requesting them to add the desired features from Button2.
Contact the authors of Button2 requesting them to add the desired features from Button1.
Write a new button class yourself.
Interface just defines the method signature, but not the method body. Meaning that you still can't get the behavior in Button1 and Button2 even if you use interface.
You can ask your vendor to do the following:
Create interfaces that takes define the necessary properties for fancy button border and colorful text
Create methods that draw the fanciful button border and write the text in colorful format by taking in the interface defined above.
Then you inherit your button3 from both of the interfaces, call the above methods to do whatever that needs to be done.
In my opinion composition in combination with inheritance works when you want to simulate multiple inheritance. However when working with controls this usually not an option because you usually a control within another control.
Some options that you could look into would be
User Controls - If you are using winforms
Nested Controls - If you are using WPF.
Related
I am designing a base class for TextForms and derived classes for Labels , Fields, Dialogboxes... etc.
i am using the below code
public class TextForm
{
public void Refresh()
{
}
}
public class Label : TextForms
{
public void Refresh()
{
}
}
and in my program i am instanciating many Labels .. and somewhere i need to call TextForms.Refresh() which must execute all derived classes instances Refresh() method .
i can't imagine how to do?
You can't find all the instances by default. Though, there are a few design patterns that will make it easier for you to do so. There is the Composite Design Pattern Which gives you the ability to add sub components to your components. For example, a Form/Window component will be a container of sub components like Labels and TextFields for example. Then, when you will call Refresh on the container (Form/Window - for example) it can call the Refresh on all of it's sub components.
There is also the Observable Design Pattern which let components register for 'events' (not necessarily implemented via .Net's Events). Then when you call the Refresh method on the observer, it will call the Refresh methods of all the observable's that are registered.
In your question, you write TextForms so I am assuming that this is an object that is an enumerable of some sort.
Liskows substitution principle dictates that if you have a base class of any kind you can always substitute derived classes for the base class
var textForms = new List<TextForm>();
textForms.Add(new Label());
textForms.Add(new TextBox());
so now you can simply iterate through this list as such:
foreach(var textForm in textForms){
((TextForm) textForm).Refresh();
}
You may have to tweak the example a little to get it working, but that is the general answer to your question.
Like m102 said it is unpractical if not impossible to find all instances. However, assuming you use a canvas or page to display your labels on, it is possible to get all the labels in that canvas.
TextForm tf = new TextForm();
foreach (Control ctrl in yourCanvas.Children.OfType<Label>())
{
tf.Refresh();
}
This will retrieve all the controls of type label from the canvas. This will not refresh them all at once.
Note: I do not recommend changing labels that are not visible/onscreen. It would require them to be kept in memory and this is performancewise not advised. Oh and your refresh function has a capital R (This is usually reserved for classes).
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'm trying to design a interface for iTextsharp (PDF creation library) that I'm using for my project. I don't want any reference to iTextsharp in my project, just the interface.
Lets say, I have
interface IPdfTable { /* */ }
public class PdfTable : IPdfTable { /* */ }
interface IPdfCell { /* */ }
public class PdfCell : PdfCell { /* */ }
While I can easily build interfaces for each class individualy, I'm having difficulty on the implementation when these classes interact with each other. Somewhere in the code, I need tables to be able to accept an collection of cells.
The problem arrives when I have a have an collection of cells, and I need to add it to the table. Somehow I need to transform the IPdfCell into the original element that is accepted by the library (iTextSharp). I believe the quick and easy implementation was downcasting, but not a good design.
The only other solution I can think is using the interface to collection varies settings and create the orginal element (accepted by iTextsharp) on the fly when it is being passed around into other elements.
Is there a better implementation?
I don't understand the goal of such an interface. No matter what, your pdf generation code is going to be tied to the library you're using, building proxy classes/interfaces that exactly mirror the library doesn't prevent that, it just adds another layer. If you were to switch to a different PDF generation library, it is extremely unlikely that the new library would match up 1:1 with equivalents in iText, and you'd end up changing the interface and calling code anyway.
My recommendation would be to create an IPDFGenerator, and then create an iTextPDFGenerator:IPDFGenerator which IS coupled to iText, and leave it at that. You'll have the separation you want, the ability to keep iText out of your core services, but it won't require a bunch of pointless mapping between identical classes.
I think you should reevaluate the S, I, and D in SOLID and make sure you're not over-doing it.
Typically, you would have a translation layer that translates your interface facade implementation into the types supported natively by iTextSharp.
AutoMapper can help for this if you require property to property mappings and can remove a lot of the translation legwork for you.
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 strongly believe that, reading code and reading good code is key to great programming. If not one of the many.
I had been facing some problems in visualizing and having a "feel" of using inheritance to better my code architecture.
Can somebody give me some link to good code to emulate, where folks have used inheritance in an absolute "kung-fooey ruthless" manner [in a good way]
I strongly believe that, reading code and reading good code is key to great programming
Hard to disagree.
Actually the qestion is pretty hard - becouse there is some alternatives to inheritance, such as composite reuse principle, so sometimes it's very hard to diside if inheritance is used in "kung-fooey ruthless" manner or there ware some better way to implement the same wich will make code esier to understand/test/make it lossely coupled and so on.
In my humble opinion Enterprise Library Application validation block whith it's Microsoft.Practices.EnterpriseLibrary.Validation.Validator class with all it's descendants
is a very good example of inheritance, becouse
concept of validation is easy to understand
there is good example how to find common in objects of with pretty different nature (i.e. OrCompositeValidator/DateTimeRangeValidator/ObjectCollectionValidator)
many of us tried to implement something more or less like this, so this background will give more quality for understanding
this is clear(for me, but I can be wrong:) that inheritance has no alternatives there
You can download source code from codeplex.
An example of good usage of inheritance would be the .NET framework classes. You can download the MONO project to gain access to some source code. If you want to better your code architecture, invest some time in studying architectural design patterns.
Here is a personal example where I've made use of inheritance to greatly benefit a development situation:
I needed to develop a asp.net (c#) form control set, which would allow both standard web forms (bunch of form fields with submit button), as well as a secure version which talks to a web service to submit the information over SSL.
Because of all of the similarities between the controls and concepts, I developed a number of classes:
BaseWebControl
custom base control class that inherits from System.Web.UI.WebControl class (part of .NET framework
has custom properties and methods that are used in our application by all custom controls (control state info, etc.)
BaseFormControl
inherits from BaseWebControl, gaining all of its underlying functionality
handles base form functionality, such as dynamically adding fieldsets, marking required fields, adding submit button, etc. etc.
contains a label and associated control index for easy lookups
marked as an abstract class, with abstract method called SubmitForm. This method is not defined on this class, however it is called by the submit button click event. This means that any specific form control class that inherits from this base class can implement the abstract SubmitForm functionality as needed.
EmailFormControl
Inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
contains very little, except overrides the abstract method SubmitForm, and generates an email based on the form fields.
all other control functionality and event handling is dealt with by the base class. In the base class when the submit button is clicked and handled, it calls this specific implementation of SubmitForm
SecureFormControl
Again inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
In its implementation of SubmitForm, it connects to a WCF web service and passes the information in over SSL.
no other functionality is required because base class handles the rest.
In stripped down code form, the general outline is as such:
public class BaseWebControl : System.Web.UI.WebControl
{
//base web control with application wide functionality built in
}
public abstract class BaseFormControl : BaseWebControl
{
//handles all 'common' form functionality
//...
//...
//event handler for submit button calls abstract method submit form,
//which must be implemented by each inheriting class
protected void btnSubmit_Click(object sender, EventArgs e)
{
SubmitForm();
}
protected abstract SubmitForm();
}
public class EmailFormControl : BaseFormControl
{
protected override SubmitForm()
{
//implement specific functionality to email form contents
}
}
public class SecureFormControl : BaseFormControl
{
protected override SubmitForm()
{
//connect to WCF web service and submit contents
}
}
As a result of the above, BaseFormControl has about 1000 lines of code in a whole bunch of methods, properties, etc. SecureFormControl and EmailFormControl each have about 40 lines. All other functionality is shared and controlled by the base class. This promotes:
maintainability
efficiency
flexibility
consistency
Now I can create any type of web form, such as DataBaseFormControl, etc. etc. very easily. I can add great new functionality to all forms by adding methods and properties to the base classes, etc.
And the list goes on.
Phew that was a lot of typing. Hope this helps give you a good example. This was one instance where I found inheritance to be a key success point in a project.
I agree with the recommendation to look at the .NET base class library, as it has excellent examples of abstraction via both inheritance and interfaces. The goal is to insulate consumer code from having to care about the details of a particular implementation. The WinForms designer works with Controls, but it has no idea what specific kinds of Controls will be implemented. It doesn't care, because inheritance abstracts away the unnecessary details. LINQ works similarly with IEnumerable; it doesn't really matter what's being enumerated, as there are algorithms you can write that work with anything enumerable. Both are excellent examples of abstraction used well.