Reputation: 682
A simple example: I got three methods [A & B & C], and their relationship is easy. In A method it calls B; in B method it calls C. So if I draw on paper it looks like:
I would like to make the "code" itself can clearly reveal this relationship so that as we read the code we can understand "how they call each other" in a big picture. Rather than we keep doing "find usage" or something else.
I know it's a little bit hard since we sometimes can not force [B only be accessible by A] and [C only accessible by B]. ( Although we can actually make it by inner class, but if there're only three methods it's a little bit pain for creating three classes. )
The way I now try to achieve this is to make the "method name" somehow reveals their relationship. But it is not a really realistic way to do it.
Apart from how can this be implemented in Java, does any other programming language have this kind of feature? I would also really like to know how does the mechanism implemented.
Many thanks for any advice or response.
Upvotes: 0
Views: 237
Reputation: 26926
Is possible to create such kind of relationship only passing B as parameter to A and C as parameter to C.
This can be accomplished with lambda expressions since Java 8 or with anonym classes prior java 8.
Other systems are not possible because you can't be sure that other methods can't call it.
Functional languages handle that very well. Here is an example using javascript:
var a = function(fn) {
// Do something
fn();
}
var b = function(fn) {
// Do something
fn();
}
var c = function() {
// Do something
}
// To call it
a(b(c));
Note that this solution define the relationship between a, b and c at execution time of the code a(b(c))
In java this is more difficult to do (prior of lambda expressions):
public interface Command {
public void execute();
}
public class X {
public void a(Command comm) {
// Do something
comm.execute();
}
public void b(Command comm) {
// Do something
comm.execute();
}
public void c() {
// Do something
}
}
final X x = new X();
x.a(new Command() {
public void execute() {
x.b(new Command() {
public void execute() {
x.c();
}
});
}
});
Upvotes: 1
Reputation: 189
It seems to me that you should realize the reason why you want to split this the code on three methods.
If you can create these three methods A, B, C in one single class and make B and C methods private, so this makes you sure that nothing will call B and C outside your class.
But if your goal is to make some restrictions inside the class, so maybe it's better to keep A, B, C as a single method, because in Java you can't restrict methods in such way.
Upvotes: 2