Scala style: how many nest functions?

One of the advantages of Scala is that it gives you great control over the area. You can invest performs the following functions:

def fn1 = {
  def fn11 = {
    ...
  }
  def fn12 = {
    ...
    def fn121 = {
      ...
    }
  }
  ...
  def fn13 = {
    ...
  }
}

The problem here is that fn1 might start to look a little intimidating. Based on the Java background, we recommend that you keep the functions small enough so that they can be viewed on a single "page" in the IDE.

What do you think about taking fn12 from fn1 based on your reasoning: "It is only used in fn1 right now, but it may be useful somewhere else in the class later ..."

Also, do you have any preferences regarding the placement of nested functions - before or after the code that calls them?

+5
6

, .

, ( , ):

def callsRecursive(p: Param): Result = {
  def recursive(p: Param, o: OtherParam, pr: PartialResult = default): Result = {
    ...
  }
}

-:

def doesGraphics(p: Point) {
  def up(p: Point): Point = // ...
  def dn(p: Point): Point = // ...
  def lf(p: Point): Point = // ...
  def rt(p: Point): Point = // ...
  /* Lots of turtle-style drawing */
}

, .

, . , , , , , , . , , , hodge-podge , . : . , - , , , . , , , .

, . , , , . , ! , , . ( , , .)

+5

, . . , (, ), , .

, , . ( / , .)

+6

. , .

+2

, , , , , .

TDD , : .

, , , , .

, ... : 10-15 java, scala, .

, , .

+2

! ,

private[scope] def fn12 = { ... } 

scope - . Java Java.

I personally avoid nesting of the named methods ( def), while I am not against nested anonymous functions (for example, closures in programming a continuation style).

0
source

Nested functions are useful (e.g. recursion helpers). But if they become too numerous, there is nothing that will prevent you from extracting them into a new type and delegating to it.

0
source

All Articles