How to share local classes? - oop

I'm currently working on a rather complex ABAP application that is going to be split into several modules each performing a specific part of the job:
one for gathering some data from multiple sources;
one for displaying that data in UI (SALV grid, if that matters);
one for doing some business things based on that data.
According to my plan each module will be a global class. However, there is some logic that may need to be shared between these classes: helper subroutines, DB access logic and so on. All of this is a set of local classes at the moment.
I know could these classes global as well, but this would mean exposing them (as well as a number of internal data structures) to the public which I would not like to. Another approach would be sharing the includes with them between my global classes, but that is said to be a bad design.
So, my question is: how do real ABAPers solve problems like this?

Here is an example of how one can access a local class defined in a report.
The report with the class.
REPORT ZZZ_PJ1.
CLASS lcl_test DEFINITION FINAL.
PUBLIC SECTION.
METHODS:
test.
ENDCLASS.
CLASS lcl_test IMPLEMENTATION.
METHOD test.
WRITE 'test'.
ENDMETHOD.
ENDCLASS.
The report which uses the class.
REPORT ZZZ_PJ2.
CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
PUBLIC SECTION.
CLASS-METHODS:
main.
ENDCLASS.
CLASS lcl_main IMPLEMENTATION.
METHOD main.
DATA:
lr_object TYPE REF TO object.
CREATE OBJECT lr_object
TYPE ('\PROGRAM=ZZZ_PJ1\CLASS=LCL_TEST')
CALL METHOD lr_object->('TEST').
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
lcl_main=>main( ).
Of course this is not a clever solution as each method call would have to be a dynamic call.
CALL METHOD lr_object->('TEST').
This could be solved however by using global interfaces that would define the methods of your classes (of course if they are not static which I assume they are not). Then you have to control each of the instances through the interface. Your target would be fulfilled then, as only the interface would be exposed globally, the implementations would remain in local classes.

You may want to do some reading on Model-View-Controller design patterns. Displaying data in a UI - would be a "view". Both the gathering and updating of data would be incorporated into a "Model" . Business logic should likely be implemented as an interaction between the view and the model in a "Controller".
That said, one approach to this is would be to utilize the friendship feature offered in ABAP OO.
As an example: create the model and view classes globally but only allow them to be instantiated privately, then grant private component access to the controller. Class definitions would be follows:
CLASS zcl_example_view DEFINITION
PUBLIC
FINAL
CREATE PRIVATE
GLOBAL FRIENDS zcl_example_controller
CLASS zcl_example_model DEFINITION
PUBLIC
FINAL
CREATE PRIVATE
GLOBAL FRIENDS zcl_example_controller
CLASS zcl_example_controller DEFINITION
PUBLIC
FINAL
CREATE PUBLIC
Additionally it may be a good idea to make the controller singleton and store a reference to it in both the view and the model. By enforcing that the controller IS BOUND when the view and model are instantiated we can effectively ensure that these three classes exist as only you desire.

Stepping back to your initial problem: I sounds to me like you're already using something like a MVC pattern in your development so your only problem is that some routines shall be used publicly by both models, views and controllers.
In this case I strongly recommend to put these routines in global available classes or to implement getter methods in your already existing classes to access those functionality.
Any hacks like \PROGRAM=ZZZ_PJ1\CLASS=LCL_TEST are sometimes essential but not here imho.

If your application is as large as you make it sound, you should organize it using multiple packages. You will certainly have to deal with non-OO stuff like function modules, data dictionary objects and other things that can not be part of a class, so using classes as the basic means to organize your application won't work outside of very small and specialized applications.
Furthermore, it sounds like you have some really severe flaws embedded in your plan if you think that "DB access logic" is something that should be "shared between classes". It is hard to guess without further information, but I would strongly suggest that you enlist someone who has experience in designing and implementing applications of that scale - at least to get the basic concept right.

Related

How do I model shared code pieces differing only slightly at a specific point effectively?

I am writing a data export application that is used for many scenarios (Vendors, Customers, Cost Centers, REFX Contracts, etc).
In the end there are two main ways of exporting: save to file or call webservice.
So my idea was create an interface if_export, implement a class for each scenario.
The problem is, the call webservice code differs slightly at the point of the actual call: the called method has a different name each time.
My ideas for dealing with this so far are:
Abstract cl_webservice_export with subclasses for each scenario. Overwrite method containing the actual call.
cl_webservice_export with member type if_webservice_call. class for each scenario implementing if_webservice_call method call_webservice()
Dynamic CALL METHOD webservice_instance->(method_name) inside
concrete cl_webservice_export method containing the actual call and passing (method_name) to cl_webservice_export.
My code:
export_via_webservice is the public interface provided by cl_webservice_export or via if_export
METHODS export_via_webservice
IMPORTING
VALUE(it_xml_strings) TYPE tt_xml_string_table
io_service_consumer TYPE REF TO ztnco_service_vmsoap
RETURNING
VALUE(rt_export_results) TYPE tt_xml_string_table.
METHOD export_via_webservice.
LOOP AT it_xml_strings INTO DATA(lv_xml_string).
call_webservice(
EXPORTING
io_service = io_service_consumer
iv_xml_string = lv_xml_string-xmlstring
RECEIVING
rv_result = DATA(lv_result)
).
rt_export_results = VALUE #( BASE rt_export_results (
lifnr = lv_xml_string-xmlstring
xmlstring = lv_result ) ).
ENDLOOP.
ENDMETHOD.
Actual webservice call, overridden or provided by if_webservice_call
METHODS call_webservice
IMPORTING
io_service TYPE REF TO ztnco_service_vmsoap
iv_xml_string TYPE string
RETURNING
VALUE(rv_result) TYPE string.
METHOD call_webservice.
TRY.
io_service->import_creditor(
EXPORTING
input = VALUE #( xml_creditor_data = iv_xml_string )
IMPORTING
output = DATA(lv_output)
).
CATCH cx_ai_system_fault INTO DATA(lx_exception).
ENDTRY.
rv_result = lv_output-import_creditor_result.
ENDMETHOD.
How would you solve this problem, maybe there are other, better ways of doing it?
I know three common patterns to solve this question. They are, in ascending order of quality:
Individual implementations
Create one interface if_export, and one class that implements it for each web service export variant that you need, i.e. cl_webservice_export_variant_a, cl_webservice_export_variant_b, etc.
Major advantages are the intuitive simplistic class design and complete independence of the implementations that avoids accidental spillover from one variant to the other.
Major disadvantage are the probably massive portion of code duplication between the different variants, if their code varies in only few, minor positions.
You already sketched this as your option 2, and also already highlighted that it is the least optimal solution for your scenario. Code duplication is never welcome. The more so since your web service calls vary only slightly, in some method name.
In summary, this pattern is rather poor, and you shouldn't actively choose it. It usually comes into existence on its own, when people start with variant a, and months later add a variant b by copy-pasting the existing class, and then forgetting to refactor the code to get rid of the duplicate parts.
Strategy pattern
This design is commonly known as the strategy design pattern. Create one interface if_export, and one abstract class cl_abstract_webservice_export that implements the interface and includes most of the web service-calling code.
Except for this detail: The name of the method that should be called is not hard-coded but retrieved via a call to a protected sub-method get_service_name. The abstract class does not implement this method. Instead, you create sub-classes of the abstract class, i.e. cl_concrete_webservice_export_variant_a, cl_concrete_webservice_export_variant_b, etc. These classes implement only the inherited protected method get_service_name, providing their concrete needs.
Major advantages are that this pattern completely avoids code duplication, is open for further extensions, and has been employed successfully in lots of framework implementations.
Major disadvantage is that the pattern starts to erode when the first variant arrives that does not completely fit, e.g. because it does not only vary the method name, but also some parameters. Evolving then requires in-depth redesign of all involved classes, which can amount to considerable cost. Another disadvantage is that the inheritance setup can make it cumbersome to write unit tests: for example, unit-testing the abstract class requires to make up a test double that sub-classes it and overwrites the protected method with sensing and mocking code - all possible but not as neatly as with interfaces between the classes.
You already sketched this as your option 1. In summary, I would recommend to choose this pattern if you have control over all involved classes and are willing to spend some extra-effort to keep the pattern clean in case it doesn't fit completely.
Composition
Composition means avoiding inheritance in favor of loose interaction between indepdent classes over classes. Create the interface if_export and individual concrete implementations of it as cl_webservice_export_variant_a, cl_webservice_export_variant_b, etc.
Move out the shared code to a class cl_export_webservice_caller that receives whatever data and variant (e.g. method name) it needs. Let the variant classes call this shared code. To complete the class design, introduce another interface if_export_webservice_caller that decouples the variants classes from the caller class.
The major advantages are that all classes are independent from each other and can be recombined in several different ways. For example, if in the future you need to introduce a variant X that would call its web service in a completely different way, you can simply add it, without having to redesign any of the other involved classes. In contrast to the strategy pattern, writing unit tests for all involved classes is trivial.
There are no real disadvantages to this pattern. (The seeming disadvantage that it needs one more interface is not really one - object orientation has the aim to clearly separate concerns, not to minimize the overall number of classes/interfaces, and we shouldn't be afraid to add more of those if it adds clarity to the overall design.)
This option sounds similar to the option 3 you sketched, but I am not 100% sure. Anyway, this would be the pattern I would vote for.

About methods in OOP

I'm relatively new in OOP.
I understand classes, methods, etc, etc but I'm having troubles with the philosophy.
Right now, I'm working on a project to manage projects, with project management, class, methods, variables, users, groups, log and task management.
So, starting with Project class, i've that:
public function create_project()
public function get_projects()
public function delete_project()
Then, ProjectClass class:
public class create_class()
public class get_classes()
public class delete_class()
But then, I though that is not the right way, so I've changed to:
Project class methods:
set_name, get_name (and similar methods)
add_class
get_classes
add_log
get_logs
ProjectClass class methods:
set_project_id (and get)
add_variables (and get)
add_method
...
So, in the first case, is the Project class who create new projects, the ProjectClass class who creates the clases and the Method class who creates the methods, and in the second case, is the Project class who creates and manages its classes and is the ProjectClass class who creates and manages its methods.
So, is any of theses "styles" correct?
If is the second case the correct case, who creates the projects? Itself?
Thank you so much
In the general case it is really hard to tell if a design is better than the other if you don't have clear responsibilities to assign (and by this I mean behavior outside from getters and setters). As time went by I moved away from upfront design to a iterative/incremental one, tackling one problem at a time and refactoring the design as needed. In this case I would try to lay down the basic requirements of your system and start a design-implementation cycle for each of them, re-structuring your model as you go tackling new requirements.
Just an an example consider this question: Does it make sense to have a class that is not bounded to a project? If the answer is no then it can be a good idea to have a method like Project>>createClass(aClassName), since you are explicitly stating that a class is created in the context of a project. Also you can make the proper connections between a class and the project it belongs to inside the method's implementation. However it is also a valid approach to define a constructor in the ProjectClass class that takes a project as a parameter. In that way you are saying "if you want to create a new class, then you must provide the project where it belongs to". Which approach to use depends on many things, one of them being programmer tastes :), so it is really hard to state if one is better than the other without having a specific context to evaluate them.
Finally, if it helps, there are a few things that are worth mentioning:
Assuming that public function create_project() is an instance method, why does an instance of a Project know how to create other projects? At first it doesn't make much sense, since that is basically a class-side responsibility, unless you have a specific motivation for this (e.g. like the Prototype pattern).
Why does a project answer to get_projects()? Are they related in some way? Or it just list all the projects? Then again, this sounds like a class-side responsibility.
I generally don't like to add the concept that the message receiver represents as part of the message. So, I wouldn't call the message delete_project(), since it is redundant to state $project->delete_project() (you already know the receiver of the message is a project).
You should be consistent with your class names. If you use ProjectClass to represent classes then you should use ProjectMethod to represents methods (though I personally don't like these names, IMHO they are misleading). It is quite important to chose proper names and keep them consistent in your domain model.
HTH

Worker vs data class

I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.
My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.
So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?
My code:
class RefData
{
Matrix mX;
Vector mV;
int mA;
bool mB;
getX();
setB();
update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.
}
or,
class RefDataUpdater
{
update(RefData*); // something like this ?
}
There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.
And the answer is it depends. It depends on what you are trying to accomplish in your design--and
if you might have more than one data-object that exhibit similar behaviors.
First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.
So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.
All this being said, as Robert Martin points out in the book:
There are ways around this that are well known to experienced
object-oriented designers: VISITOR, or dual-dispatch, for example.
But these techniques carry costs of their own and generally return the
structure to that of a procedural program.
Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.
As already written, it depends, but I'd probably go with an external support class that handles the update.
For once, I'd like to know why you'd use such a method? I believe it's safe to assume that the class doesn't only call setter methods for a list of parameters it receives, but I'll consider this case as well
1) the trivial updater method
In this case I mean something like this:
public update(a, b, c)
{
setA(a);
setB(b);
setC(c);
}
In this case I'd probably not use such a method at all, I'd either define a macro for it or I'd call the setter themselves. But if it must be a method, then I'd place it inside the data class.
2) the complex updater method
The method in this case doesn't only contain calls to setters, but it also contains logic. If the logic is some sort of simple property update logic I'd try to put that logic inside the setters (that's what they are for in the first place), but if the logic involves multiple properties I'd put this logic inside an external supporting class (or a business logic class if any appropriate already there) since it's not a great idea having logic reside inside data classes.
Developing clear code that can be easily understood is very important and it's my belief that by putting logic of any kind (except for say setter logic) inside data classes won't help you achieving that.
Edit
I just though I'd add something else. Where to put such methods also depend upon your class and what purpose it fulfills. If we're talking for instance about Business/Domain Object classes, and we're not using an Anemic Domain Model these classes are allowed (and should contain) behavior/logic.
On the other hand, if this data class is say an Entity (persistence objects) which is not used in the Domain Model as well (complex Domain Model) I would strongly advice against placing logic inside them. The same goes for data classes which "feel" like pure data objects (more like structs), don't pollute them, keep the logic outside.
I guess like everywhere in software, there's no silver bullet and the right answer is: it depends (upon the classes, what this update method is doing, what's the architecture behind the application and other application specific considerations).

Make this more OOPey? - good structure?

I just want advice on whether I could improve structure around a particular class which handles all disk access functions
The structure of my program is that I have a class called Disk which gets data from flatfiles and databases on a, you guessed it, hard disk drive. I have functions like
LoadTextFileToStringList,
WriteStringToTextFile,
DeleteLineInTextFile
etc
which are kind of "generic methods"
In the same class I also have some more specific methods such as GetXFromDisk where X might be a particular field in a database table/query.
Should I separate out the generic methods from the specialised. Should I make another class which inherits the generic methods. At the moment my class is static as there is no need to have an internal state of the class.
I'm not really OOPing am I?
Thanks
Thomas
If you are using only static static functions you are not really OOPing as you said. It is writing procedural code in OO language.
You should look to create classes which represent objects in your problem domain like File and TextFile. These classes should have operations like DeleteLine, WriteLIne, Load etc.
Also, in which ever language you are programming, it is likely to have a good File IO library. Try to use that in your code as much as possible. If needed just write wrappers over the library classes to provide some additional functionality.
Well, what you seem to have in your code is a Utilities class where you bundle in all the file methods.
This could indicate some design issue but IMHO it is ok, since it is common to have utility classes in OOP designs.
It haves the benefit of being able to add extra methods or modify existing ones easy since you will not have any derived classes extending the Utility class to be affected.
For example java has static methods everywhere. E.g. Collection class.
I would suggest to have the class's contructor be private and have the naming such that is obvious that this is a Utilities class.

A use for multiple inheritance?

Can anyone think of any situation to use multiple inheritance? Every case I can think of can be solved by the method operator
AnotherClass() { return this->something.anotherClass; }
Most uses of full scale Multiple inheritance are for mixins. As an example:
class DraggableWindow : Window, Draggable { }
class SkinnableWindow : Window, Skinnable { }
class DraggableSkinnableWindow : Window, Draggable, Skinnable { }
etc...
In most cases, it's best to use multiple inheritance to do strictly interface inheritance.
class DraggableWindow : Window, IDraggable { }
Then you implement the IDraggable interface in your DraggableWindow class. It's WAY too hard to write good mixin classes.
The benefit of the MI approach (even if you are only using Interface MI) is that you can then treat all kinds of different Windows as Window objects, but have the flexibility to create things that would not be possible (or more difficult) with single inheritance.
For example, in many class frameworks you see something like this:
class Control { }
class Window : Control { }
class Textbox : Control { }
Now, suppose you wanted a Textbox with Window characteristics? Like being dragable, having a titlebar, etc... You could do something like this:
class WindowedTextbox : Control, IWindow, ITexbox { }
In the single inheritance model, you can't easily inherit from both Window and Textbox without having some problems with duplicate Control objects and other kinds of problems. You can also treat a WindowedTextbox as a Window, a Textbox, or a Control.
Also, to address your .anotherClass() idiom, .anotherClass() returns a different object, while multiple inheritance allows the same object to be used for different purposes.
I find multiple inheritance particularly useful when using mixin classes.
As stated in Wikipedia:
In object-oriented programming
languages, a mixin is a class that
provides a certain functionality to be
inherited by a subclass, but is not
meant to stand alone.
An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality.
But they may also inherit from other classes as part of their normal class structure, so it is quite common for these classes to use multiple inheritance in this respect.
An example of multiple inheritance:
class Animal
{
virtual void KeepCool() const = 0;
}
class Vertebrate
{
virtual void BendSpine() { };
}
class Dog : public Animal, public Vertebrate
{
void KeepCool() { Pant(); }
}
What is most important when doing any form of public inheritance (single or multiple) is to respect the is a relationship. A class should only inherit from one or more classes if it "is" one of those objects. If it simply "contains" one of those objects, aggregation or composition should be used instead.
The example above is well structured because a dog is an animal, and also a vertebrate.
Most people use multiple-inheritance in the context of applying multiple interfaces to a class. This is the approach Java and C#, among others, enforce.
C++ allows you to apply multiple base classes fairly freely, in an is-a relationship between types. So, you can treat a derived object like any of its base classes.
Another use, as LeopardSkinPillBoxHat points out, is in mix-ins. An excellent example of this is the Loki library, from Andrei Alexandrescu's book Modern C++ Design. He uses what he terms policy classes that specify the behavior or the requirements of a given class through inheritance.
Yet another use is one that simplifies a modular approach that allows API-independence through the use of sister-class delegation in the oft-dreaded diamond hierarchy.
The uses for MI are many. The potential for abuse is even greater.
Java has interfaces. C++ has not.
Therefore, multiple inheritance can be used to emulate the interface feature.
If you're a C# and Java programmer, every time you use a class that extends a base class but also implements a few interfaces, you are sort of admitting multiple inheritance can be useful in some situations.
I think it would be most useful for boilerplate code. For example, the IDisposable pattern is exactly the same for all classes in .NET. So why re-type that code over and over again?
Another example is ICollection. The vast majority of the interface methods are implemented exactly the same. There are only a couple of methods that are actually unique to your class.
Unfortunately multiple-inheritance is very easy to abuse. People will quickly start doing silly things like LabelPrinter class inherit from their TcpIpConnector class instead of merely contain it.
One case I worked on recently involved network enabled label printers. We need to print labels, so we have a class LabelPrinter. This class has virtual calls for printing several different labels. I also have a generic class for TCP/IP connected things, which can connect, send and receive.
So, when I needed to implement a printer, it inherited from both the LabelPrinter class and the TcpIpConnector class.
I think fmsf example is a bad idea. A car is not a tire or an engine. You should be using composition for that.
MI (of implementation or interface) can be used to add functionality. These are often called mixin classes.. Imagine you have a GUI. There is view class that handles drawing and a Drag&Drop class that handles dragging. If you have an object that does both you would have a class like
class DropTarget{
public void Drop(DropItem & itemBeingDropped);
...
}
class View{
public void Draw();
...
}
/* View you can drop items on */
class DropView:View,DropTarget{
}
It is true that composition of an interface (Java or C# like) plus forwarding to a helper can emulate many of the common uses of multiple inheritance (notably mixins). However this is done at the cost of that forwarding code being repeated (and violating DRY).
MI does open a number of difficult areas, and more recently some language designers have taken decisions that the potential pitfalls of MI outweigh the benefits.
Similarly one can argue against generics (heterogeneous containers do work, loops can be replaced with (tail) recursion) and almost any other feature of programming languages. Just because it is possible to work without a feature does not mean that that feature is valueless or cannot help to effectively express solutions.
A rich diversity of languages, and language families makes it easier for us as developers to pick good tools that solve the business problem at hand. My toolbox contains many items I rarely use, but on those occasions I do not want to treat everything as a nail.
An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality.
This example doesn't really illustrate the usefulness of multiple inheritance. What being defined here is an INTERFACE. Multiple inheritance allows you to inherit behavior as well. Which is the point of mixins.
An example; because of a need to preserve backwards compatibility I have to implement my own serialization methods.
So every object gets a Read and Store method like this.
Public Sub Store(ByVal File As IBinaryWriter)
Public Sub Read(ByVal File As IBinaryReader)
I also want to be able to assign and clone object as well. So I would like this on every object.
Public Sub Assign(ByVal tObject As <Class_Name>)
Public Function Clone() As <Class_Name>
Now in VB6 I have this code repeated over and over again.
Public Assign(ByVal tObject As ObjectClass)
Me.State = tObject.State
End Sub
Public Function Clone() As ObjectClass
Dim O As ObjectClass
Set O = New ObjectClass
O.State = Me.State
Set Clone = 0
End Function
Public Property Get State() As Variant
StateManager.Clear
Me.Store StateManager
State = StateManager.Data
End Property
Public Property Let State(ByVal RHS As Variant)
StateManager.Data = RHS
Me.Read StateManager
End Property
Note that Statemanager is a stream that read and stores byte arrays.
This code is repeated dozens of times.
Now in .NET i am able to get around this by using a combination of generics and inheritance. My object under the .NET version get Assign, Clone, and State when they inherit from MyAppBaseObject. But I don't like the fact that every object inherits from MyAppBaseObject.
I rather just mix in the the Assign Clone interface AND BEHAVIOR. Better yet mix in separately the Read and Store interface then being able to mix in Assign and Clone. It would be cleaner code in my opinion.
But the times where I reuse behavior are DWARFED by the time I use Interface. This is because the goal of most object hierarchies are NOT about reusing behavior but precisely defining the relationship between different objects. Which interfaces are designed for. So while it would be nice that C# (or VB.NET) had some ability to do this it isn't a show stopper in my opinion.
The whole reason that this is even an issue that that C++ fumbled the ball at first when it came to the interface vs inheritance issue. When OOP debuted everybody thought that behavior reuse was the priority. But this proved to be a chimera and only useful for specific circumstances, like making a UI framework.
Later the idea of mixins (and other related concepts in aspect oriented programming) were developed. Multiple inheritance was found useful in creating mix-ins. But C# was developed just before this was widely recognized. Likely an alternative syntax will be developed to do this.
I suspect that in C++, MI is best use as part of a framework (the mix-in classes previously discussed). The only thing I know for sure is that every time I've tried to use it in my apps, I've ended up regretting the choice, and often tearing it out and replacing it with generated code.
MI is one more of those 'use it if you REALLY need it, but make sure you REALLY need it' tools.
The following example is mostly something I see often in C++: sometimes it may be necessary due to utility classes that you need but because of their design cannot be used through composition (at least not efficiently or without making the code even messier than falling back on mult. inheritance). A good example is you have an abstract base class A and a derived class B, and B also needs to be a kind of serializable class, so it has to derive from, let's say, another abstract class called Serializable. It's possible to avoid MI, but if Serializable only contains a few virtual methods and needs deep access to the private members of B, then it may be worth muddying the inheritance tree just to avoid making friend declarations and giving away access to B's internals to some helper composition class.
I had to use it today, actually...
Here was my situation - I had a domain model represented in memory where an A contained zero or more Bs(represented in an array), each B has zero or more Cs, and Cs to Ds. I couldn't change the fact that they were arrays (the source for these arrays were from automatically generated code from the build process). Each instance needed to keep track of which index in the parent array they belonged in. They also needed to keep track of the instance of their parent (too much detail as to why). I wrote something like this (there was more to it, and this is not syntactically correct, it's just an example):
class Parent
{
add(Child c)
{
children.add(c);
c.index = children.Count-1;
c.parent = this;
}
Collection<Child> children
}
class Child
{
Parent p;
int index;
}
Then, for the domain types, I did this:
class A : Parent
class B : Parent, Child
class C : Parent, Child
class D : Child
The actually implementation was in C# with interfaces and generics, and I couldn't do the multiple inheritance like I would have if the language supported it (some copy paste had to be done). So, I thought I'd search SO to see what people think of multiple inheritance, and I got your question ;)
I couldn't use your solution of the .anotherClass, because of the implementation of add for Parent (references this - and I wanted this to not be some other class).
It got worse because the generated code had A subclass something else that was neither a parent or a child...more copy paste.