Methods calling other methods in the same class - anti-patterns

In class design, is it a bad habit if one method calls another method in the same class (For example, 3 methods call 1 method in the same class).
Thanks

Not at all, it's expected if you've designed your classes properly. You should have a small public interface, and if the implementation is complex, you'll probably end up calling many private methods in the same class.
In fact, not doing this can be an anti-pattern. If you're constantly calling methods of another class, it's called Feature Envy and you should probably combine classes. If you're putting all the implementation into one gargantuan function, that's just unmaintainable, and probably contains a lot of code duplication.
Breaking things out into other reusable methods is a good thing. Your case of 3 methods calling the same one is perfect code reuse. It would be very bad if the code of that one function was duplicated in each of the calling functions.

No. In fact it is good practice to do this. Or do you think that your three methods that do the calling should each duplicate the called code?

Methods are just functions and functions are abstractions useful for code reuse and design improvement. If three methods of one class need to do the same thing while running should they copy-paste the code for that or call a separate method?
Having some meaningful part of code separated into a method being called by other methods is just another example of code reuse which is good unless you really overdo it.

No. It appears that you have found a valid use to uphold DRY principles.

Not at all. Infact quite the opposite. Methods are there to accomplish specific tasks, and you should use them for precisely that.

Yes, if those methods are overridable, i.e. if the class and/or methods are not final. The reason being that subclasses that attempt to override behavior or to provide a layer of service cannot do so reliably because the layer can be entered multiple times.
Example (Scala pseudo code) where we assume that HashSet.addAll calls its own HashSet.add:
class MemCountingSet[T] extends HashSet[T] {
private def sizeOf(t: T) = ...
private var memCount = 0
def add(t: T) = {
memCount += sizeOf(t)
super.add(t)
}
def addAll(coll: Collection[T]) = {
memCount += coll.foreach(sizeOf)
super.addAll(coll)
}
}
When using addAll we now end up double-counting.

Related

How do you avoid subclass call-backs when using Composition?

So I tend to favour composition over inheritance and I would like non-inheritance answers for this question.
There appears to be circumstances when using composition when there is some code in the superclass that requires a call to code in the subclass. This makes for unscaleable inheritance hierarchies which defeats the purpose of using composition in the first place. Here's a demonstration of the problem in C# (although this is a general oop question):
public interface IChemistry
{
void SeparateAtom(Atom atom);
void BreakBond(Bond bond);
}
public class BaseChemistry : IChemistry
{
public void SeparateAtom(Atom atom)
{
//possible extra logic here
for(int i=0;i < atom.BondCount;i++)
{
//maybe extra logic here etc.
BreakBond(atom.Bonds[i]);
}
}
public void BreakBond(Bond bond)
{
//do some bond breaking logic here
}
}
public class RealisticChemistry : IChemistry
{
private BaseChemistry base;
public RealisticChemistry(BaseChemistry base)
{
this.base = base;
}
public void SeparateAtom(Atom atom)
{
//subclass specific logic here perhaps
base.SeparateAtom(atom);
}
public void BreakBond(Bond bond)
{
//more subclass specific logic
base.BreakBond(bond);
}
}
As you can see with this design there is a glaring problem. When the subclass' SeparateAtom() method is called it executes some of it's own logic and then delegates the rest to the base class which will then call the BreakBond() method on the base class, not on the subclass.
There are various solutions I can think of for this and almost all of them have pretty substantial setbacks:
Copy and paste. The worst option in this case would be to simply copy the loop (and additional logic) within the base class' SeparateAtom() method, to the subclass' one. I don't feel that it is necessary to explain why copy and paste is not the best practice. Another option could be to package some of the extra logic around the loop into extra methods so that it's just the loop that is copied. But the calls to the additional methods are still copied, and breaking things up into multiple methods could break encapsulation. For example what if some of that logic is dependent on the specific context of SeparateAtom()and could lead to faulty data if called out-of-context by someone who does not know the code very well?
Listen to or observe bond breaking events in base class. This solution seems problematic to me because the way in which base class functionality should be extended becomes unclear. For example, without prior knowledge if one were to try to extend the class they might intuitively implement the design above and interpret the listener as optional, when it is in fact required if one wants to extend bond breaking behaviour.
Make the base class require a delegate. For example, the base class could require a reference to a IBondBreakDelegate which is called inside of BondBreak(). This has a similar problem to the listener approach in that the mixture of composition and other approaches makes the intended usage of the base class unclear. Also, even though now there is a delegate which is actually required, thus making the intended usage a little more clear, the base class can now no longer function on its own. Also if one needs to extend the hierarchy with an additional subclass (for example public class MoreRealistiChemistry etc.), how would one go about extending the delegated behaviour through composition?
Delegate everything instead of composition. I would prefer not to go down this route because when classes need extra functionality the amount of delegates needed increases (or the amount of methods in the delegates does). Also what if some of the delegated behaviour is optional? Then either there needs to be separate optional delegates for each behaviour that the subclass implements, or you end up with lots of empty method bodies in the subclass.
In general when I commit to a type of design, I would like to do so wholeheartedly. Of course in the real-world there are a ton of caveats. But I feel like this one must be so common that someone might know a good work-around. Any ideas?
(I cannot add a comment because of insufficient reputation, but I want to point out two things.)
First, your code does not compile because the classes do not implement IChemistry.
Second, 'favour composition over inheritance' is only a guideline and is not meant to be applied mindlessly. If the model that is under consideration for the solution requires either inheritance or composition, you should choose composition.
For this particular question, inheritance (or rather, specialisation) is the more sensible approach.

Is it correct to return an object which class is not the expected class?

Well, i hope you understand me. I have two classes, A and B. B is subclass of A. They have the same public methods and means the same thing, but B does some things a little different, so it has additional methods and attributes that only uses itself. Let say, class A implements a method newFromWizard that interactively creates an object. Can I implement logic for, depending on the user input, create an object A or and object B in the newFromWizard method of A. I mean, can i create a B object from that method of A? Or i need to implement that elsewhere? How is the best way to do it? In practice, i can. But, it is correct for OOP?
By the way, if that matters, i'm using Smalltalk.
Yes, this is a well-known pattern in OO. In the Objective-C Cocoa libraries you'll find it applied systematically, and is known as class clusters. The result is that the Cocoa libraries are much easier to understand than the equivalent c# or java ones. It allows the hiding of a inheritance hierarchy behind an abstract class that has class side creation methods that return subclasses.
public class A{
public B method(){
B b = new B();
return b;
}
}
class B extends A{
}
If this is what you're talking about, it's valid.
I would say that it's not intuitive way of doing things. Let's simplify it and say that you just redefine new. Then in some point you do A new and get an instance of B. The thing that they are similar makes it not so bad. But imagine that someone else starts working with your code. And hew knows that message new should result in creation of the instance of the receiver. And then something goes different. I'd say that conceptually it's wrong. Why now to implements some builder class? And have there something like
createInstanceOfAB
|className|
className := "do what you need".
^ className asClass new.
This is a more clear way.
Once again you can make new… method to do whatever you want, even shoot fireworks, but most of the people will expect it to create instance of the same class
I think you shouldn't worry too much about whether it is "clean OO" to return an instance of a subclass. It's being used and done so often because it is very helpful and makes your code very readable compared to somme kind of factories and stuff.
My biggest concern here would be that you should name your class method carefully. Don't use #new is probably the most important rule, but you should always use a name that already says: give me an instance of what is appropriate right now.
I'd say this is not limited to subclasses, such a method can even return objects that do not inherit from the class. In a dynamically typed language, this is okay. Remember, we're in a dynamically typed language, so as long as you have polymorphic interfaces, the class of an object is not really important to its users as long as it responds to your message sends...

Is it better for class data to be passed internally or accessed directly?

Example:
// access fields directly
private void doThis()
{
return doSomeWork(this.data);
}
// receive data as an argument
private void doThis(data)
{
return doSomeWork(data);
}
The first option is coupled to the value in this.data while the second option avoids this coupling. I feel like the second option is always better. It promotes loose coupling WITHIN the class. Accessing global class data willy-nilly throughout just seems like a bad idea. Obviously this class data needs to be accessed directly at some point. However, if accesses, to this global class data can be eliminated by parameter passing, it seems that this is always preferable.
The second example has the advantage of working with any data of the proper type, whereas the first is bound to working with the just class data. Even if you don't NEED the additional flexibility, it seems nice to leave it as an option.
I just don't see any advantage in accessing member data directly from private methods as in the first example. Whats the best practice here? I've referenced code complete, but was not able to find anything on this particular issue.
if the data is part of the object's state, private/protected is just fine. option 1 - good.
i noticed some developers like to create private/protected vars just to pass parameters between methods in a class so that they dun have to pass them in the method call. they are not really to store the model/state of an object. ...then, option 1 - NOT good.
Why option 1 not good in this case...
expose only as much as you need (var scoping). so, pass the data in. do not create a private/protected var just to pass data between 2 methods.
private methods that figures out everything internally makes it very easy to understand. keep it this way, unless its unavoidable.
private/protected vars make it harder to refactor as your method is not 'self encompassing', it depends on external vars that might be used elsewhere.
my 2 cents! :-)
In class global data are not a problem IMHO. Classes are used to couple state, behaviour and identity. So such a coupling is not a problem. The argument suggests, that you can call that method with data from other objects, even of other classes and I think that should be more considered than coupling inside class.
They are both instance methods, therefore #1 makes more sense unless you have a situation involving threads (but depending on the language and scenario, even then you can simply lock/mark the data method as syncronized - my Java knowledge is rusty).
The second technique is more reminiscent of procedural programming.

How to break up a large class

I have a large Shape class, instances of which can (should) be able to do lots of things. I have many "domain" shape classes which inherit from this class, but do not provide any different functionality other than drawing themselves.
I have tried subclassing the Shape class, but then all of the "domain" objects will still inherit this subclass.
How do I break up the class? (it is 300 text lines, C#)
300 lines seems reasonable to me.
post the code if you really want better help
A couple of ideas (more like heuristics):
1) Examine the fields of the class. If a group of fields is only used in a few methods, that might be a sign that that group of fields and the methods that use it might belong in another class.
2) Assuming a well-named class, compare the name of the class to what the class actually does. If you find methods that do things above and beyond what you'd expect from the class' name, that might be a sign that those methods belong in a different class. For example, if your class represents a Customer but also opens, closes, and writes to a log file, break out the log file code into a Logger class. See also: Single Responsibility Principle (PDF) for some interesting ideas .
3) If some of the methods primarily call methods on one other class, that could be a sign that those methods should be moved to the class they're frequently using (e.g. Feature Envy).
CAUTION: Like they say, breaking up is hard to do. If there is risk in breaking up the class, you may want to put some tests in place so that you know you're not breaking anything as you refactor. Consider reading "Working Effectively with Legacy Code" and the "Refactoring" book.
you could break up by delegating functions to other helper classes.
but I agree that 300 lines of code isn't terrible.
+1 for posting the code
Thanks for the code.
Here are a few things you might try:
1) Refactor duplicate code. This kind of code was duplicated about seven times:
Visio.Cell pinX = GetLayoutCell(Visio.VisCellIndices.visXFormPinX);
if (pinX != null)
{
pinX.set_Result("cm", value);
}
Note: PinY also calculates pinX but doesn't use its value.
Similar duplication exists in: Pos{X,Y}{Start,End}
What makes this class more challenging to break up is that it's a wrapper around an already complex class.
Not knowing the domain very well (although I'm an expert with the Shape, Circle, Square concept), I'd be tempted to break the class into several classes that each share the same core Shape object.
Here is a sketch:
class EnvironShape {
private ShapeProperties _properties; // contains property management code
private ShapeCollection _children; // contains code for acting on children
private Decorators _decorators; // code for accessing decorators
private Layers _layers; // layer management code
private Position _position; // code for working with the shape's position
// Other code omitted
}
I would not immediately and directly expose these objects (e.g. public ShapeCollection GetChildren()) but I would start off making the EnvironShape delegate to these objects.

Should a long method used only once be in its own class or in a function?

A lot of times in code on the internet or code from my co-workers I see them creating an Object with just one method which only gets used once in the whole application. Like this:
class iOnlyHaveOneMethod{
public function theOneMethod(){
//loads and loads of code, say 100's of lines
// but it only gets used once in the whole application
}
}
if($foo){
$bar = new iOnlyHaveOneMEthod;
$bar->theOneMethod();
}
Is that really better then:
if($foo){
//loads and loads of code which only gets used here and nowhere else
}
?
For readability it makes sense to move the loads and loads of code away, but shouldn't it just be in a function?
function loadsAndLoadsOfCode(){
//Loads and loads of code
}
if($foo){ loadsAndLoadsOfCode(); }
Is moving the code to a new object really better then just creating a function or putting the code in there directly?
To me the function part makes more sense and seems more readible then creating an object which hardly is of any use since it just holds one method.
The problem is not whether it's in a function or an object.
The problem is that you have hundreds of lines in one blob. Whether that mass of code is in a method of an object or just a class seems more or less irrelevant to me, just being minor syntatic sugar.
What are those hundreds of lines doing? That's the place to look to implement object oriented best practice.
If your other developers really think using an object instead of a function makes it significantly more "object oriented" but having a several-hundred line function/method isn't seen as a code smell, then I think organisationally you have some education to do.
Well, if there really is "loads and loads" of code in the method, then it should be broken down into several protected methods in that class, in which case the use of a class scope is justified.
Perhaps that code isn't reusable because it hasn't been factored well into several distinct methods. By moving it into a class and breaking it down, you might find it could be better reused elsewhere. At least it would be much more maintainable.
Whilst the function with hundreds of lines of code clearly indicates a problem (as others have already pointed out), placing it in a separate instance class rather than a static function does have advantages, which you can exploit by rejigging your example a fraction:
// let's instead assume that $bar was set earlier using a setter
if($foo){
$bar = getMyBar();
$bar->theOneMethod();
}
This gives you a couple of advantages now:
This is a simple example of the Strategy Pattern. if $bar implements an interface that provides theOneMethod() then you can dynamically switch implementations of that method;
Testing your class independently of $bar->theOneMethod() is dramatically easier, as you can replace $bar with a mock at testing time.
Neither of these advantages are available if you just use a static function.
I would argue that, whilst simple static functions have their place, non-trivial methods (as this clearly is by the 'hundreds of lines' comment) deserve their own instance anyway:
to separate concerns;
to aid testing;
to aid refactoring and reimplementation.
You are really asking two questions here:
Is just declaring a function better than creating an object to hold only this function?
Should any function contain "loads of code"?
The first part: If you want to be able to dynamically switch functions, you may need the explicit object encapsulation as a workaround in languages that cannot handle functions this way. Of course, having to allocate a new object, assign it to a variable, then call the function from that variable is a bit dumb when all you want to do is call a function.
The second part: Ideally not, but there is no clear definition of "loads", and it may be the appropriate thing to do in certain cases.
yes, the presences of loads and loads of code is a Code Smell.
I'd say you almost never want to have either a block or a method with loads of code in it -- doesn't matter if it's in it's own class or not.
Moving it to an object might be a first step in refactoring 'though - so it might make sense in that way. First move it to its own class and later split it down to several smaller methods.
Well, I'd say it depends on how tightly coupled the block of code is with the calling section of code.
If it's so tightly coupled, that I can't imagine it being used anywhere else, I'd prefer sticking it in a private method of the calling class. That way it won't be visible to other parts of your system, guaranteeing it won't be misused by others.
On the other hand, if the block of code is generic enough (email validation i.e.) to possibly be interesting in other parts of the system, I'd have no problem extracting that part into it's own class, and then consider that to be a utility class. Even if it means it will be a single-method class.
If your question was more in the lines of "what to do with hundreds and hundreds of lines of code", then you really need to be doing some refactoring.
As much as a single method with lots of code is a code smell. My first thought was to at least make the method static. No data in the class so no need for creating an object.
I think i would look to rephrase the question that you are asking. I think you want to ask the questions is my class supporting singles responsibility principle. Is there anyway to decompose the pieces of your class into seperate smaller pieces that might change independently of each other (data access and parsing, etc . .). Can you unit test your class easily . .
If you can say yes to the above items, i wouldn't worry about method versus new class as the whole point here is that you have readable, maintainable code.
In my team we have red flag if a class gets long (over x amount of lines) but that is just a heuristic as if you class has 2000 lines of codes it probably can get broken down and is probably not supporting SRP.
For testability, it is definitely better to break it out into a separate class with separate method(s). It is a whole lot easier to write unit tests for single methods than as part of an inline if statement in a code-behind file or whatnot.
That being said, I agree with everyone else that the method should be broken out into single responsibility methods instead of hundreds of lines of code. This too will make it more readable and easier to test. And hopefully, you might get some reuse out of some of the logic contained in that big mess of code.