1:1:1 Coupling or 1:2 Coupling for OOP? - oop

For example, is it better to have class A use class B and class B use class C OR to have class A use both class B and class C. I know it might depend on the context, but is there a good guideline for this?
Thank you

You shouldn't really have this option. Classes are not written just for fun, they model something, usually the business domain.
So the question you should ask yourself is, does/should the concept of A know about both B and C, or does B make sense without C, etc.?
Usually the domain should sort these things out. If it doesn't, then it by definition doesn't matter.
If the business doesn't matter for this code, i.e. you are writing some technical parts, like Services that just call each other, or something similar, then you are already in "questionable design" territory.

Related

CBO coupling between object

I don't understand what "CBO-Coupling between object classes" really means. The definition I found is so short that I think I'm missing something, so it would be great if you help me with an example.
Here is the definition I found:
"The coupling between object classes is a count of the number of other classes to which it is coupled."
Thanks in advance.
Coupling between objects (CBO) is a count of the number of classes that are coupled to a particular class i.e. where the methods of one class call the methods or access the variables of the other. These calls need to be counted in both directions so the CBO of class A is the size of the set of classes that class A references and those classes that reference class A. Since this is a set - each class is counted only once even if the reference operates in both directions i.e. if A references B and B references A, B is only counted once.
This is the definition given here - www.virtualmachinery.com/sidebar3.htm
There is some more detail in the link - as well as an interesting general discussion of the Chidamber and Kemerer metrics - CBO is a part of these metrics.
Here's an example with UML that complements the other answers:
Notes:
CBO doesn't care about the direction of a dependency. D has a CBO of 1 because C depends on it, even though D depends on no other classes. B and C are similar cases.
Coupling can be via attributes (composition), associations, local variables, instanciations or injected dependencies (arguments to methods).
Coupling is when a class (A) depends (knows about, requires, uses) on another specific class(B). This means when you change a public member B that is used by A, you have to change A as well. You want low coupling between types, so that you can change classes without many side effects. Usually, coupling 'comes' together with bad encapsulation so you'll have A knowing information that should be private to B.
Some types are generic enough (like List in C#) and you can use them directly without fearing side effects. But whatever classes you define for your own app, you need to be aware that those might change. So in many situations, you are more interested in some behaviour (or attributes) of B, instead of A using the whole B. In those cases, it's better to extract an interface (to abstract the desired behaviour) and then A will know only about an abstraction, while B will implement it. This allows you to have more than one concrete implementation (useful every time you're dealing with things like databases, network, import/export etc) and A won't know about B.
Thus, A can unknowingly use any of B,C,D etc as long as they implement the interface and you can change things in B,C,D as long as this doesn't break the public contract (the interface).
While we usually want our classes to be decoupled, but cohesive (as in to work together), in many situations coupling won't really hurt you, as decoupling might require more effort than provide value. It's up to the developer to identify those situations and to make a proper decision. However, this comes with experience, so in the mean time, just try not to couple your classes too much.

Can Coldfusion components share methods without being descendants of the same super class

We have used a homegrown version of object oriented coldfusion for a while and I'm just starting to experiment with cfc's and how it "should" be done...
If I understand correctly, cfinterface defines the signature of functions, and any class that implements that interface must have their own functions to do whats defined in the interface.
I'm kind of trying to do the opposite - the interface doesn't just define the function's signature, but also defines the logic of the function and anything that implements that interface can use its functions without having to define it itself. Does that exist besides creating subclasses?
For example, say you have classes A,B,C,D that all belong to the Animal class
A & B can walk
A & C can talk
B & D can sleep
Suppose the logic of walk, talk & sleep (if the object can do it) is the same regardless of the class doing it
Ideally, if A & B both implement the walking interface, they can walk without defining a separate walk method in each class.
Or borrowing a better example from this java multiple inheritance question
A Pegasus is a mix of a Horse and a Bird because it runs like a horse
but flies like a bird
Is that possible? (I think this is multiple inheritance?)
In short: no, an interface only defines a contract, it does not (and cannot) define functionality). Also CFML does not have the concept of multiple inheritance.
You will have to use single-inheritance and concrete implementations to effect what you need. I can't be bothered assessing your implementation-sharing requirements to work out what an approrpriate class hierarchy might be to minimise code duplication. I'm sure you can do that yourself (and it's not really part of your question anyhow).
One tactic you could try is to use mixins for your common methods. Store the common methods in a different library, and then inject them into your objects as required. So basically Mixins.cfc would implement walk(), talk(), sleep(), and you'd have an AFactory.cfc, BFactory.cfc, CFactory.cfc. When asking a factory for a new A, B or C, and the factory method injects the mixin methods before returning the instances. Obviously this is a fairly cumbersome process, and you'd want to use some sort of IoC container to manage all this.
A better question might come out of you showing us more real world examples... I suspect your domain design could perhaps stand improvement if you find yourself needing to do what your example suggests. Actual design requirements are seldom exposed with examples using animals.
You can do similar things with WireBox and its Virtual Inheritance feature:
http://wiki.coldbox.org/wiki/WireBox.cfm#Virtual_Inheritance
// Declare base CFC
map("BaseModel").to("model.base.BaseModel");
map("UserService").to("model.users.UserService").virtualInheritance("BaseModel");
It's basically very similar to what Adam described above; a base class is created, and references to it's public members are placed in the sub class.
https://github.com/ColdBox/coldbox-platform/blob/master/system/ioc/Builder.cfc#L535
There's no reason why you can't build something similar but you should know this has already been done.
Full disclosure, I am a contributing member of the *Box community.

Expand object oriented code

Are there any tools that will expand object oriented code so there is no sharing of any kind? For example if I have two classes A and B which inherit C then the tool would adjust classes A and B to no longer use C. It would also be nice if the tool did this and it still compiled and produced the same results. I think the main difficulty would be adjusting any conditional logic if class type is checked dynamically.
I know this is totally pointless from a machine perspective, but it would be a fun academic exercise.
While there are various refactoring tools out there, I doubt your question has practical application as it would require substantial contextual knowledge and human intervention to perform that kind of automatic manipulation.
In your example, it's not just enough that A and B obtain C's methods and properties, but the fact that in many cases, there are places where you want to hand A (or B) to a method and have it treated like a C. Or, you might want to hand it to something that takes a C, but have A's (or B's) specific behavior invoked --- imagine a collection that invokes .DoThing() on whatever object is inside of it.
You'd have to not only bust apart the classes, but have all kind of other overloaded functions with lots of redundant looking code (especially for the types, not just the behaviors).
I'd say while an interesting thought experiment, perhaps we should place it in the bad idea pile. I doubt it would help for readability, extensibility, or performance.
The problem with this is that code which uses C rather than A or B is hard to deal with:
public void workWithSomeC( C useThis ) { ... }
in our OO code we can pass either an A or a B to that function. Can't do that if A and B no longer have anything in common.
I would think by duplicating such code something could be made to work, but good grief what a horrible idea ;-)

Should I be using inheritance?

This is more of a subjective question, so I'm going to preemptively mark it as community wiki.
Basically, I've found that in most of my code, there are many classes, many of which use each other, but few of which are directly related to each other. I look back at my college days, and think of the traditional class Cat : Animal type examples, where you have huge inheritance trees, but I see none of this in my code. My class diagrams look like giant spiderwebs, not like nice pretty trees.
I feel I've done a good job of separating information logically, and recently I've done a good job of isolating dependencies between classes via DI/IoC techniques, but I'm worried I might be missing something. I do tend to clump behavior in interfaces, but I simply don't subclass.
I can easily understand subclassing in terms of the traditional examples such as class Dog : Animal or class Employee : Person, but I simply don't have anything that obvious I'm dealing with. And things are rarely as clear-cut as class Label : Control. But when it comes to actually modeling real entities in my code as a hierarchy, I have no clue where to begin.
So, I guess my questions boil down to this:
Is it ok to simply not subclass or inherit? Should I be concerned at all?
What are some strategies you have to determine objects that could benefit from inheritance?
Is it acceptable to always inherit based on behavior (interfaces) rather than the actual type?
Inheritance should always represent an "is-a" relationship. You should be able to say "A is a B" if A derives from B. If not, prefer composition. It's perfectly fine to not subclass when it is not necessary.
For example, saying that FileOpenDialog "is-a" Window makes sense, but saying that an Engine "is-a" Car is nonsense. In that case, an instance of Engine inside a Car instance is more appropriate (It can be said that Car "is-implemented-in-terms-of" Engine).
For a good discussion of inheritance, see Part 1 and Part 2 of "Uses and Abuses of Inheritance" on gotw.ca.
As long as you do not miss the clear cut 'is a' relationships, it's ok and in fact, it's best not to inherit, but to use composition.
is-a is the litmus test. if (Is X a Y?) then class X : Y { } else class X { Y myY; } or class Y { X myX; }
Using interfaces, that is, inheriting behavior, is a very neat way to structure the code via adding only the needed behavior and no other. The tricky part is defining those interfaces well.
No technology or pattern should be used for its own sake. You obviously work in a domain where classes tend to not benefit from inheritance, so you shouldn't use inheritance.
You've used DI to keep things neat and clean. You separated the concerns of your classes. Those are all good things. Don't try and force inheritance if you don't really need it.
An interesting follow-up to this question would be: Which programming domains do tend to make good use of inheritance? (UI and db frameworks have already been mentioned and are great examples. Any others?)
I also hate the Dog -> Mammal -> Animal examples, precisely because they do not occur in real life.
I use very little subclassing, because it tightly couples the subclass to the superclass and makes your code really hard to read. Sometimes implementation inheritance is useful (e.g. PostgreSQLDatabaseImpl and MySQLDatabaseImpl extend AbstractSQLDatabase), but most of the time it just makes a mess of things. Most of the time I see subclasses the concept has been misused and either interfaces or a property should be used.
Interfaces, however, are great and you should use those.
Generally, favour composition over inheritance. Inheritance tends to break encapsulation. e.g. If a class depends on a method of a super class and the super class changes the implementation of that method in some release, the subclass may break.
At times when you are designing a framework, you will have to design classes to be inherited. If you want to use inheritance, you will have to document and design for it carefully. e.g. Not calling any instance methods (that could be overridden by your subclasses) in the constructor. Also if its a genuine 'is-a' relationship, inheritance is useful but is more robust if used within a package.
See Effective Java (Item 14, and 15). It gives a great argument for why you should favour composition over inheritance. It talks about inheritance and encapsulation in general (with java examples). So its a good resource even if you are not using java.
So to answer your 3 questions:
Is it ok to simply not subclass or inherit? Should I be concerned at all?
Ans: Ask yourself the question is it a truly "is-a" relationship? Is decoration possible? Go for decoration
// A collection decorator that is-a collection with
public class MyCustomCollection implements java.util.Collection {
private Collection delegate;
// decorate methods with custom code
}
What are some strategies you have to determine objects that could benefit from inheritance?
Ans: Usually when you are writing a framework, you may want to provide certain interfaces and "base" classes specifically designed for inheritance.
Is it acceptable to always inherit based on behavior (interfaces) rather than the actual type?
Ans: Mostly yes, but you'd be better off if the super class is designed for inheritance and/or under your control. Or else go for composition.
IMHO, you should never do #3, unless you're building an abstract base class specifically for that purpose, and its name makes it clear what its purpose is:
class DataProviderBase {...}
class SqlDataProvider : DataProviderBase {...}
class DB2DataProvider : DataProviderBase {...}
class AccountDataProvider : SqlDataProvider {...}
class OrderDataProvider : SqlDataProvider {...}
class ShippingDataProvider : DB2DataProvider {...}
etc.
Also following this type of model, sometimes if you provide an interface (IDataProvider) it's good to also provide a base class (DataProviderBase) that future consumers can use to conveniently access logic that's common to all/most DataProviders in your application model.
As a general rule, though, I only use inheritance if I have a true "is-a" relationship, or if it will improve the overall design for me to create an "is-a" relationship (provider model, for instance.)
Where you have shared functionality, programming to the interface is more important than inheritance.
Essentially, inheritance is more about relating objects together.
Most of the time we are concerned with what an object can DO, as opposed to what it is.
class Product
class Article
class NewsItem
Are the NewsItem and Article both Content items? Perhaps, and you may find it useful to be able to have a list of content which contains both Article items and NewsItem items.
However, it's probably more likely you'll have them implement similar interfaces. For example, IRssFeedable could be an interface that they both implement. In fact, Product could also implement this interface.
Then they can all be thrown to an RSS Feed easily to provide lists of things on your web page. This is a great example when the interface is important whereas the inheritance model is perhaps less useful.
Inheritance is all about identifying the nature of Objects
Interfaces are all about identifying what Objects can DO.
My class hierarchies tend to be fairly flat as well, with interfaces and composition providing the necessary coupling. Inheritance seems to pop up mostly when I'm storing collections of things, where the different kinds of things will have data/properties in common. Inheritance often feels more natural to me when there is common data, whereas interfaces are a very natural way to express common behavior.
The answer to each of your 3 questions is "it depends". Ultimately it will all depend on your domain and what your program does with it. A lot of times, I find the design patterns I choose to use actually help with finding points where inheritance works well.
For example, consider a 'transformer' used to massage data into a desired form. If you get 3 data sources as CSV files, and want to put them into three different object models (and maybe persist them into a database), you could create a 'csv transformer' base and then override some methods when you inherit from it in order to handle the different specific objects.
'Casting' the development process into the pattern language will help you find objects/methods that behave similarly and help in reducing redundant code (maybe through inheritance, maybe through the use of shared libraries - whichever suits the situation best).
Also, if you keep your layers separate (business, data, presentation, etc.), your class diagram will be simpler, and you could then 'visualize' those objects that aught to be inherited.
I wouldn't get too worried about how your class diagram looks, things are rarely like the classroom...
Rather ask yourself two questions:
Does your code work?
Is it extremely time consuming to maintain? Does a change sometimes require changing the 'same' code in many places?
If the answer to (2) is yes, you might want to look at how you have structured your code to see if there is a more sensible fashion, but always bearing in mind that at the end of the day, you need to be able to answer yes to question (1)... Pretty code that doesn't work is of no use to anybody, and hard to explain to the management.
IMHO, the primary reason to use inheritance is to allow code which was written to operate upon a base-class object to operate upon a derived-class object instead.

Multiple Inheritance Criticisms

I was investigating the concept of Multiple Inheritance (it's been almost 10 years since I have coded C++ in anger, and was simply academically interested in the concept). I found this reference on Wikipedia.
One criticism of MI they list is "Not being able to explicitly inherit multiple times from a single class". I'm confused about this statement, and not 100% sure what this is referring to.
Surely a class inheritance describes the structure of a class, and to inherit multiple times from the same class would simply reiterate the same class contract, so I can't see what benefit it would give to justify the criticism. Would explicit inheritance suppose multiple instances of the class functions and properties?
I would like to understand what this criticism is referring to, and why it is implicitly unavailable to Multiple Inheritance enabled languages.
This is called the Diamond Problem. Most modern languages that allow MI have a solution for this.
In short, you have this class tree:
class A { public int f = 0; };
class B extends A { f = 1; };
class C extends A { f = 2; };
class D extends B, C {};
What will D.f print? If you put some value into D.f, where should it be stored? Should the two fields B(A).f and C(A).f be merged into one or should they stay separate? If you override a method x of A in B and in C, what should D.x() do? Call both? In which order? What about the return value?
I think they mean that a class Car cannot inherit from its four wheels (eg. inherit four times the class Wheel). [See the C++ stanza on the same Wikipedia page]
However, I think this "omission" is actually a positive feature, because inheritance is there to express subtyping, and there is no "multiple subtyping from single type". This "explicit multiple inheritance" would be no better than simple composition.
Similarly I've not coded C++ in anger for over 5 years now having switched to C#. I can't really remember whether I used multiple inheritance much, but I don't miss it, especialy as I can code to interfaces and that I use composition more these days.
However, in the best OO book ever - probably ;) - Betrand Meyer makes a good defense of multiple inheritance. He also makes a similar defense here.
I think the problem is with that particular Wikipedia article. It contains more than one awkward or vague statement, such as these jewels:
Tcl allows multiple parent classes- their serial affects the name resolution for class members.
and
However, these six languages allow classes to inherit from multiple interfaces, recreating some of the problems mentioned while avoiding others.
I frankly don't know what the author intended by the sentence in your question. It's just another example of vagueness in a poorly-written article, IMHO.
Multiple Inheritance is the GOTO of object oriented programming. It arose because of the approaches adopted by the early OOP langauges (C++,etc). It works well in the right hand, but it confusing most of the other times.
One of the leading goals of OOP was reuse of behavior. This turned out to be a chimera. Useful in some cases but in rest of the cases what we are really interested in is defining how objects interact. Look at how many patterns in Design Patterns use interface as opposed to inheritance.
Implementing Interfaces, followed by explicit Aggregation are clearer more maintainable ways of doing the same things that multiple inheritance does. Nearly all OOP have some method of defining a interface, nearly all OOP can aggregate objects together. However OOP handle the issues raised by multiple inheritance (the Diamond Problem, etc) in subtle different ways. Like the GOTO when you look over code using multiple iheritance it is not clear what is going on. However like GOTO it can be useful in different circumstances.
For me the primary consideration for using any difficult language construction is whether I have to maintain the application over the long haul. If I do then I opt for the clearest more easily maintained approach even if takes a little more programming now. Like everything else it is a Judgment call. Note that most of the time we wind up sticking with the program we developed far longer than we ever figured.
Actually, in C++ a class can inherit multiple times from the same class:
class A {};
class B : public A ();
class C : public A ();
clsss D : public B, public C {};
Now D ends up with two copies of A. This is is generally regarded as "a bad idea" and C++ provides virtual inheritance to control it.