Are there any languages that let you specify that a function can only be called from a single call site? [closed]

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/388574

  •  22-02-2021
  •  | 
  •  

Question

Out of curiosity, are there any languages that let you tag a function with an attribute that indicates that it may only be called from a single call-site, such that if any code tries to call the function from a second call site, the second call-site is flagged as a compile-time error?

For example (pseudocode):

unique_call_site void myFunction(int a, int b, int c) {...}

[...]

myFunction(1, 2, 3);  // ok
myFunction(1, 2, 3);  // error -- second call site not allowed!

Motivation for the question: it's sometimes desirable to break functionality out of a function and into its own separate sub-function (if only to keep the original function from getting too large and complicated), but once you do that, then anyone examining the sub-function now has to consider all the different calling-contexts that the sub-function might possibly be called from, and that consideration re-introduces a bit of complexity. Having the sub-function tagged with a keyword that indicates that it can be called from only a single context (and having the compiler enforce that property) would allow the reader to know right away that they only need to consider that single calling-context when studying how the sub-function might be used.

Was it helpful?

Solution

Not that I am aware of, but many languages allow something like this:

void SomeFunction() {
  void InnerFunction(int a, int b, int c) {
    // do stuff!
  }

  // blah blah
  InnerFunction(1,2,3);
}

// some other context
InnerFunction(1,2,3); // error!

Which allows you to limit the scope of your sub-functions to the single place they're used.

I personally don't care for this syntax since it hinders testability, adds complexity to the language (parser, name resolution, tooling to name a few), and doesn't provide a whole lot of readability benefit over a more general feature (like simple private functions). If you need to know how often something is used, something like CodeLens does that better without modifying the language. YMMV.

OTHER TIPS

Many OO languages support private methods/functions, that are located within a class, and can only be called from within that class.
You can simply make a small class that conatins only your private method and the method that is allowed to call it.

Licensed under: CC-BY-SA with attribution
scroll top