P
P
Pavel Klochkov2021-02-01 23:47:32
PHP
Pavel Klochkov, 2021-02-01 23:47:32

What should the method return?

Hello! help resolve the issue.
I'm trying to write a class to clean up data. It is assumed that all data of any form will pass through the corresponding static methods of this class.
However, the IDE swears at me how much in vain and PHP itself is also dissatisfied with my crooked hands and not very smart brains.

While trying to write a method to clear an int, I ended up with the following:

public static function cleanInt($int)
    {
        $int = trim($int);
        try {
            if ($int = (int) $int) {
                return $int;
            }
            throw new Exception('Not int ');

        } catch (Exception $e) {
            echo $e->getMessage();
        }

        return false;
    }


This is where I have questions.
If I expect the method to return int, then the idea of ​​returning false is the wrong solution, but what if instead of int, abracadabra came to the method? what should the method return if not false? Return 0 in this case and consider it an error? Also a so-so solution, will you have to check every time if the result is not equal to 0? But what if a case occurs in which 0 is quite acceptable?
Or, after throwing an exception, return nothing at all? In this version, the IDE says that my hands are crooked and I have already drunk my brains away and in general I should not do this at that age.

There is another thought, but I don't know how to approach it yet.
And can score on the opinion of the IDE and still return nothing? And write your own Exception which will alert the user that he made a mistake when entering data. Such a path is certainly difficult and thorny, but so far it seems to me the most correct.
Can you tell me if I'm thinking in the wrong direction?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Developer, 2021-02-02
@samodum

You cannot mix int and boolean.
There are several options here.
The simplest is to use exceptions, but it's expensive.
If the function returns 0, then in most cases it means ok. You can return -1 as an error.
Another option is to return a class like ErrorType { errorCode, errDescription }.
The variant is more difficult - to write a class, inside of which this method, but not static. And write the execution results in the fields of this class - errCode, errDescription
...
There are a lot of options, but not the same as yours

A
Alexander Lykasov, 2021-02-02
@lykasov-aleksandr

Alternatively, you can look in C#. There are implemented a couple of methods for the classes Int, Float (and others): Int.Parse(string)and Int.TryParse(string). The first throws an exception in case of an error, the second silently returns 0. Depending on the logic, either one or the other is used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question