Does if () use accepted practice in conjunction with immediate return?

Does it use ifin combination with direct return, as in the example below, an acceptable practice instead of having ifwith a block of code inside {}? Are these equivalents in practice or is there a flaw for one approach?

An example in Java:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

ServletContext sc = this.getServletContext();       

// Throw exception for fatal error (Servlet not defined in web.xml ?)
if( sc == null )
 return; // old-style programming
 // Careful with silent bugs ! Correct way of handling this is:
 // throw new RuntimeException( "BookDetail: ServletContext is null" );

BookList bookList = WebUtil.getBookList( sc );
+3
source share
8 answers

Martin Fowler endorses the early return and calls the idea of ​​a Reservation clause .

Personally, I do not like this in Java, since I prefer one return per method. However, this is subjective, and I may be in the minority.

for .

+9

, . .

" -", .

+8

, . .

Function Blah() As Boolean
  If expr Then
     Return False
  End If
  Do Other work...

  Return result

End Function
+7

, , - , C, 30% C.

- , .

if (!_cache.has_key(key))
    return null;

return _cache[key]

, :

if (_cache_has_key(key))
{
    return _cache[key]
}
else
    return null;

, , , 5 5 if.

, null , , , , . .NET out. , Try, :

Foo foo;
if (!TryGetCachedFoo("myfoo", foo))
{
    foo = new Foo(...);
    AddToCache("myfoo", foo);
}

// do something with foo
+4

. , , , , .

+3

, , , ServletContext , - . , , , , .

, , . , , , .., , .

public void validatePhone(String phoneNumber) throws ValidationException {

if (phoneNumber == null || phoneNumber.equals("")) {
    return;
}
//do validation stuff, throwing exception if not valid

>

+3

return if; . (edit: , , ).

, , return ( ). - - , , , ( Java, , , InputStream), , return return.

.

+2

I have a few (subjective or not) comments:

  • I always use accolades with if, even if the block contains only one line
  • I do not like to have much returnfor one method
  • I do not think this check is nullnecessary. If getServletContext()returns null, then you have a much bigger problem with your webapp, which definitely needs to be fixed. In this case, the presence NullPointerExceptionlater in the code is an exceptional error, so I would not handle it.
+1
source

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


All Articles