Moved block of code into a function

This is for the issue #19168