2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-13 14:08:13 +02:00
https://en.wikipedia.org/wiki/Recursion[Recursion] is a technique used to define a problem in terms of the problem itself, usually in terms of a simpler version of the problem itself.
2020-06-30 12:48:39 +02:00
2023-06-07 15:41:34 +02:00
For example, the implementation of the generator for the n-th value of the https://en.wikipedia.org/wiki/Fibonacci_sequence[Fibonacci sequence] comes naturally from its mathematical definition, when recursion is used:
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,vbnet]
2020-06-30 12:48:39 +02:00
----
2023-06-01 17:49:46 +02:00
Function NthFibonacciNumber(ByVal n As Integer) As Integer
If n <= 1 Then
Return 1
Else
Return NthFibonacciNumber(n - 1) + NthFibonacciNumber(n - 2)
End If
End Function
----
As opposed to:
[source,vbnet]
----
Function NthFibonacciNumber(ByVal n As Integer) As Integer
Dim previous As Integer = 0
Dim last As Integer = 1
For i = 0 To n - 1
Dim temp = previous
previous = last
last = last + temp
Next
Return last
End Function
----
2023-06-15 08:55:51 +02:00
The use of recursion is acceptable in methods, like the one above, where you can break out of it.
2023-06-01 17:49:46 +02:00
[source,vbnet]
----
Function NthFibonacciNumber(ByVal n As Integer) As Integer
If n <= 1 Then
Return 1 ' Base case: stop the recursion
2023-06-16 11:03:44 +02:00
End If
' ...
2023-06-15 08:55:51 +02:00
End Function
2023-06-01 17:49:46 +02:00
----
It is also acceptable and makes sense in some type definitions:
[source,vbnet]
----
Class Box
Inherits IComparable(Of Box)
Public Function CompareTo(ByVal other As Box?) As Integer
' Compare the two Box instances...
End Function
End Class
----
With types, some invalid recursive definitions are caught by the compiler:
[source,vbnet]
----
Class C2(Of T) ' Error BC31447 C2(Of T) cannot reference itself in Inherits clause
Inherits C2(Of T)
2020-06-30 12:48:39 +02:00
End Class
2023-06-01 17:49:46 +02:00
2020-06-30 12:48:39 +02:00
Class C2(Of T)
2023-06-01 17:49:46 +02:00
Inherits C2(Of C2(Of T)) ' Error BC31447 C2(Of T) cannot reference itself in Inherits clause
End Class
----
2023-06-13 14:08:13 +02:00
In more complex scenarios, however, the code will compile but execution will result in a https://learn.microsoft.com/en-us/dotnet/api/system.typeloadexception[TypeLoadException] if you try to instantiate the class.
2023-06-01 17:49:46 +02:00
[source,vbnet]
----
Class C1(Of T)
End Class
Class C2(Of T) ' Noncompliant
Inherits C1(Of C2(Of C2(Of T)))
2020-06-30 12:48:39 +02:00
End Class
2023-06-01 17:49:46 +02:00
Dim c2 = New C2(Of Integer) ' This would result into a TypeLoadException
2020-06-30 12:48:39 +02:00
----
2021-06-02 20:44:38 +02:00
2023-06-13 14:08:13 +02:00
include::../resources.adoc[]
include::../rspecator.adoc[]