Calling methods on objects from 'opposite ends' of a program - class

I have been developing my skills at creating large object orientated programs (30+ classes).
I am trying to make my code as clean as possible after reading a fantastic book called clean code.
One problem I am having is to do with calling a method on an object from "across the program"
Say I have 5 classes.
`ClassA
ClassB
ClassC
ClassD
ClassE`
an instance of ClassA contains an instance of ClassB, which in turn contains an instance of classC, so
`ClassA > ClassB > ClassC`
I'm not saying that this is the inheritance chain, rather that in the constructor of classA an instance of ClassB is created and so on.
Now, say that ClassD > ClassE in a similar way. ClassD is instansiated with an instance variable containing an instance of ClassE.
This is all well and good, and the classes are small and only handle one job, and it all seems nice and clean.
However, say that at some point in the program I need the instance of classC to call a method on the instance of ClassE.
The two objects are on 'opposite sides of the program' so to speak. Yet the method call is necessary.
I am left with three options as I see it
make the instance of classE a global variable, so that classD AND classC can access it (as well as anything else in the program). I feel like this is bad form as global variables are generally considered bad news
Create the instance of ClassE at the top level, then pass it in as an argument to the constructors of ClassA, ClassB, and ClassC. The trouble with this is that I would end up with really long constructor argument lists if this is happening more than once, and it seems like lots of work to pass ojects down chains of constructors like this
Move the object of ClassE to be instantiated by ClassC. The trouble with that is that its more strongly coupled with ClassD and only needs to be called once in the entire running of the program by ClassC.
So what do I do in situations such as these? And are there any resources I can read about this. I know that I could use the observer pattern for situations similar to this, but when its just for one method call it seems excessive, as I would be making things observable all over the program. I want my code as clean as possible!
Thanks in advance :)

Three words: Single Responsibility Principle. If you worry that your class has too many constructor arguments it's probably because this class needs to deal with too many different things. If you keep classes focused, they will be small.
You correctly indicate the coupling problem in the third solution you've described. The coupling problem is also present in the first solution (depending on a global variable is even harder to find/diagnose later). So the second option seems to be the best - as long as you refactor the code to keep your classes simple.

You could read up on Law of Demeter (Short explanation on wikipedia: http://en.wikipedia.org/wiki/Law_of_Demeter or a longer but very well written example http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf)
Depending on the context / content of your example you could for instance: Build your Class D as a wrapper to your class E (or similar facade / adapter). Meaning if your class c sometimes needs to talk to an E instance it does so via it's class D instance.
Another way to go would be to provide a reference to a class E instance to those objects that need one.
If all your objects are talking to the same instance of E you could also think about the singleton pattern where there is only one instance of a class. But this instance is more or less globally available.
Give a bit more context info and we can develop this further.
EDIT: btw. a funny explanation of lad of demeter can be found here:
http://www.daedtech.com/visualization-mnemonics-for-software-principles
EDIT Nr.2 (your comment): ad. 1.) Maybe you can implement your class D in a way that reliefs your other classes of ever talking directly to an E object. Instead they ask their D instance to do something (not knowing that D delegates the call to E). Depending on what you are trying to do this might be an option for you.
ad. Singleton.) Yes and No. The Singleton main use is that it guarantees (if implemented correctly) that only one instance of the singleton object exists. If you are talking about config settings this might not be a requirement. You are right however that basically the thing is kind of a global variable with all it's downsides. Your object D sounds as if it's immutable in a sense that it does not change it's state while your program is running so maybe the problem is not that you create a complex dynamic behaviour but that you create too many dependencies.
Just another link/principle to get you thinking:
What is Inversion of Control?

Related

Is it better to implement two classes or one class in the following case?

I have a class "Vertex" with 4 attributes and a class "Vertex_" with one attribute. The one attribute in Vertex_ is also in Vertex. Is it a good design to keep the two classes or is it better to program just the class Vertex, although there will be 3 variables, which are not used, when I instantiate an object which needs just the one attribute?
Class Vertex_ is actually somewhat a duplicate of Class Vertex.
I would suggest using inheritance and having Class Vertex inherit the attribute from the parent Class Vertex_ while having the 3 other attributes Class Vertex_ does not have.
TL;DR
This is a question that deserves a very long answer.There are two reasons for inheritance and the reason for doing it can depend on the language being used. One reason is for code reuse. Without knowing anything else about your situation, it would seem you are inheriting simply to reuse an attribute (but I suspect there could be more you will be reusing). But, there are other ways of getting code reuse without inheritance, for example containment, which is often a better way.
A powerful feature of object-oriented programming is the ability to substitute one type of object for another. When a message is sent to that object, the correct method implementation is invoked according the actual type of object receiving the message. This is one type of polymorphism. But in some languages the ability to substitute one object for another is constrained. In Java I can only substitute an instance of class B for an instance of class A if B is a descendant of A. So inheritance becomes important in Java to support polymorphism.
But what does it mean to be able to substitute a B instance for an A instance? Will it work? Class A has established a contract stating what each of its methods requires before you can successfully call it and at the same time states what each method promises to deliver. Will the methods of class B live up to that contract? If not, you really cannot substitute a B for an A and expect the program to run correctly. B may be a subclass of A but it is not a subtype of A (see Liskov substitution principle]).
In a language such as Python, inheritance is not required for polymorphism and coders are more apt to use it as code-reuse mechanism. Nevertheless, some people feel that subclassing should only be used to express subtyping. So, if Vertex_ is only using one of the four attributes it has inherited, I am doubtful that an instance of Vertex_ could be safely substituted for an instance of Vertex. I would not do the inheritance unless the language were C++ and then I would use private inheritance.

What's the correct way of thinking C# protected accessor in swift?

In c# we have the protected accessor which allows class members to be visible on inherited clases but not for the rest.
In Swift this doesn't exist so I wonder what's a correct approach for something like this:
I want to have a variable (internal behavior) and and a public method using this variable on a base class. This variable will be used also on inherited clases.
Options I see
Forget about base class and implement variable and methods everywhere I need it. WRONG, duplicated code
Implement inheritance by composition. I'd create a class containing common methods and this will be used by composition instead of inheritance. LESS WRONG but still repeating code that could be avoided with inheritance
Implement inheritance and make variable internal on base class. WRONG since exposes things without any justification except allowing visibility on inherited clases.
Implementation Details for Base Class
I want to have a NSOperationQueue instance and and a public method to cancel queued operations. I add new operations to this queue from inherited classes.
In Swift the correct answer is almost always protocols and extensions. It is almost never inheritance. Sometimes Cocoa stands in our way, because there are classes in Cocoa more often than protocols, but the goal is almost always protocols and extensions. Subclassing is our last choice.
Your particular case is confusing because NSOperationQueue already has a public method to cancel queued operations (cancelAllOperations). If you want to protect the queue from outside access (prevent callers from using addOperation directly for instance), then you should put the queue inside another type (i.e. composition), and forward what you want to the queue. More details on the specific problem you're solving would allow us to help suggest other Swift-like solutions.
If in the end you need something that looks like protected or friend, the correct solution is private. Put your subclass or your friend in the same file with the target, and mark the private thing private. Alternately, put the things that need to work together in a framework, and mark the attribute internal. The Swift Blog provides a good explanation of why this is an intentional choice.

Tracing back method call of overridden method in eclipse

I am looking at a source code and it has a method named updateDisplayList. There are various methods in this source code with similar name. However I am interested in one particular updateDisplayList method. I want to check where this method is getting called. I have tried using CTRL+SHIFT+G in eclipse which returns me all the references of this method in that source code. However as there are many methods with same name, those references are also getting returned. How can I know where that particular updateDisplayList method is getting called?
As stated in the comments updateDisplayList() is a Flex component life cycle method. Practically every Flex component implements this method.
If you've modified this method in one class, lets call it ClassA, and you're also seeing the effects of this modification in other classes, it must mean that the other classes inherit from ClassA in some way.
To determine who's inheriting from ClassA, you can just search for that class name in your project. This will likely find the other class that you're looking for. However, there could be a series of classes that inherit from ClassA so you might have to look deeper than that (find all the classes that extend ClassA and then search for those classes). This might be a slippery slope and may not be fruitful.
Another approach is to set a breakpoint in the updateDisplayList() method in ClassA. As I mentioned, you'll hit this breakpoint frequently. In FlashBuilder/Eclipse, you can use the "expressions" window and inspect the value of this. If this is ClassA, it's not the droid(s) you're looking for, so let execution resume.
I'm sure there are a handful of other ways to get to the bottom of this. But updateDisplayList() is such a common method, there's no point in searching for that method name :)

Are static classes and methods bad? Global variables frowned upon?

I have an application that has database connectivity and although there are obviously objects that correspond to data in my database, I find that all my data processing methods could be static as there is no real need for an instance of the object as my classes simply operate on the data and spit something out, no need to store anything outside the method's scope. If I can make a method or class static should I?
Also I use a utility singleton class for common (single instance) "global data". I want to have a good design, but are these frowned upon?
Let me give you an example of what I'm doing. I load some data from my database using a static method to place it into a global varaiable in my Singleton class (a list of a custom object)
So my singleton class has something like
List<MyCustomObject> SomeList
and my static class has
static void LoadData()
foreach(data in database something or other)
singletonClass.SomeList.Add()
So the code above might load in some records from the database into SomeList, where each item in SomeList is of type MyCustomObject, which contains a single record of information.
Is this good implementation? Is this how you would code it?
Then in my presentation layer I would make calls to another static class of methods to get data from the singleton class in to a format required.
It doesn't feel very OOPey. But I can't really think how to do it another way you do it.
Allow me to direct you toward an excellent article on this topic: Singletons are Pathological Liars.
The problem is that the need to call your LoadData() function isn't self-evident. Compare your situation to that described in the article and I think you'll see some parallels.
Statics and singletons are frowned upon somewhat. But only the same way as starting a sentence with “but” — bad when overused, but sometimes it's what works best.
In your example, why have separate classes, one a singleton and one static? A singleton is in many ways equivalent to a class with only static data and methods. If you already have a singleton, I'd say you should add the methods to load the data to it rather than to a separate class. A class with static methods would be more appropriate if, say, you have utility code common to all of your stored data types.
(Also, I wouldn't worry too much about what's OOPey and what's not. Overengineering in the blind service of OOP principles can be a serious problem, speaking as someone who's had to wade through the Eclipse code base …)
Singletons is one but static is another very big one.
OOP or not, static variables have many drawbacks but little coding convenience.
Can't determine exact allocation time, life span
Can't work well in multi-threaded
Future problem to program expansion
...

Pseudo-multiple-inheritance with extension methods on interfaces in C#?

Similar question but not quite the same thing
I was thinking that with extension methods in the same namespace as the interface you could get a similar effect to multiple inheritance in that you don't need to have duplicate code implementing the same interface the same way in 10 different classes.
What are some of the downsides of doing this? I think the pros are pretty obvious, it's the cons that usually come back to bite you later on.
One of the cons I see is that the extension methods can't be virtual, so you need to be sure that you actually do want them implemented the same way for every instance.
The problem that I see with building interface capability via extension methods is that you are no longer actually implementing the interface and so can't use the object as the interface type.
Say I have a method that takes an object of type IBar. If I implement the IBar interface on class Foo via extension methods, then Foo doesn't derive from IBar and can't be used interchangeably with it (Liskov Substitution principle). Sure, I get the behavior that I want added to Foo, but I lose the most important aspect of creating interfaces in the first place -- being able to define an abstract contract that can be implemented in a variety of ways by various classes so that dependent classes need not know about concrete implementations.
If I needed multiple inheritance (and so far I've lived without it) badly enough, I think I'd use composition instead to minimize the amount of code duplication.
A decent way to think about this is that instance methods are something done by the object, while extension methods are something done to the object. I am fairly certain the Framework Design Guidelines say you should implement an instance method whenever possible.
An interface declares "I care about using this functionality, but not how it is accomplished." That leaves implementers the freedom to choose the how. It decouples the intent, a public API, from the mechanism, a class with concrete code.
As this is the main benefit of interfaces, implementing them entirely as extension methods seems to defeat their purpose. Even IEnumerable<T> has an instance method.
Edit: Also, objects are meant to act on the data they contain. Extension methods can only see an object's public API (as they are just static methods); you would have to expose all of an object's state to make it work (an OO no-no).