📜 ⬆️ ⬇️

How many returns should there be in a function / method?

Recently, my colleague and I had a dispute about the number of returns that should be in the function / method. He believes that the return function should be one, and the result can be prepared in a local variable. I think that you should put return in every place where you can return a value from a function.
And how the respected Habrasoobschestvo thinks?

For example, a piece of Java code that illustrates an approach I like:
public static String getSystemLookAndFeelClassName() {
String systemLAF = ( String )AccessController.doPrivileged(
new GetPropertyAction( "swing.systemlaf" ));
if (systemLAF != null ) {
return systemLAF;
}
String osName = ( String )AccessController.doPrivileged(
new GetPropertyAction( "os.name" ));

if (osName != null ) {
if (osName.indexOf( "Windows" ) != -1) {
return "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" ;
}
else {
String desktop = ( String )AccessController.doPrivileged(
new GetPropertyAction( "sun.desktop" ));
if ( "gnome" .equals(desktop)) {
// May be set on Linux and Solaris boxs.
return "com.sun.java.swing.plaf.gtk.GTKLookAndFeel" ;
}
if ((osName.indexOf( "Solaris" ) != -1) ||
(osName.indexOf( "SunOS" ) != -1)) {
return "com.sun.java.swing.plaf.motif.MotifLookAndFeel" ;
}
}
}
return getCrossPlatformLookAndFeelClassName();
}

* This source code was highlighted with Source Code Highlighter .

In the style of my colleague, this code would look like this:
public static String getSystemLookAndFeelClassName() {
String result = getCrossPlatformLookAndFeelClassName();

String systemLAF = ( String )AccessController.doPrivileged(
new GetPropertyAction( "swing.systemlaf" ));
if (systemLAF != null ) {
result = systemLAF;
}
String osName = ( String )AccessController.doPrivileged(
new GetPropertyAction( "os.name" ));

if (osName != null ) {
if (osName.indexOf( "Windows" ) != -1) {
result = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" ;
}
else {
String desktop = ( String )AccessController.doPrivileged(
new GetPropertyAction( "sun.desktop" ));
if ( "gnome" .equals(desktop)) {
// May be set on Linux and Solaris boxs.
result = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel" ;
}
if ((osName.indexOf( "Solaris" ) != -1) ||
(osName.indexOf( "SunOS" ) != -1)) {
result = "com.sun.java.swing.plaf.motif.MotifLookAndFeel" ;
}
}
}
return result;
}


* This source code was highlighted with Source Code Highlighter .


UPD : the first option is a function taken unchanged from the Sun JDK 6.0 sources, the second option is the first version that I quickly adapted from my colleague’s style.

')

Source: https://habr.com/ru/post/67430/


All Articles