Deutsch

Можно ли возвращать null из функции?

14.04.24 04:22
Re: Можно ли возвращать null из функции?
 
uscheswoi_82 коренной житель
uscheswoi_82
в ответ AlexNek 09.04.24 18:52

Гугл не советует:

Is Returning null a Bad Practice? Returning null can be considered bad practice because the caller has to explicitly handle the null checks and forgetting that can lead to unhandled exceptions.08.11.2023


В StackOverflow советуют так см. https://stackoverflow.com/questions/1626597/should-functio...:

Should functions return null or an empty object?
Returning null is usually the best idea if you intend to indicate that no data is available.

An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.


А так вы сами писали раньше в этом форуме про вот такие переменные:int?, String?, итд... т.е. если написать метод вот так, то возращает пустоту без ошибок:

using System;
public class Program {
 public static int? WhatAge() {
   return null;
 }
 public static void Main() {
   Console.WriteLine(WhatAge());
 }
}



А в Си в 90х часто пользовались проверкой NULL, допустим если делать проверку на открытие файла, т.к. в языке Си нет try-catch:

FILE *f = fopen("test.txt", "r");
if (f == NULL) {
    printf("Такой файл не существует!\n");
    return 1;
}



Если посмотреть в Си файл stddef.h, там NULL так описывается, т.е. NULL=0:

#define NULL ((void *)0)
#define NULL 0



Я сам только что затестил в Си:

#include <stdio.h>
int main(int argc, char *argv[]) {
 if(0 == NULL)
   printf("0 == NULL\n");
if(((void *)0) == NULL)
   printf("((void *)0) == NULL\n");
 return 0;
}



Выдаёт в консоли:

0 == NULL
((void *)0) == NULL



С Java уже давно не работал, насколько помню, там при объявление переменных нужно обязательно указать null. Например:

public class MySQLAccess {
    private Connection connect = null;
    private Statement statement = null;
    private PreparedStatement preparedStatement = null;
    private ResultSet resultSet = null;
кто как обзывается, тот так сам называется... маску ношу чтобы не заразить антиваксеров... Дневник тяжелобольного инвалида
 

Перейти на