Безопасное программирование: инструкции в Java

Решение только для Mac:

system("open", "http://stackoverflow.com/")

или

`open http://stackoverflow.com/`
8
задан Konrad Rudolph 25 September 2009 в 11:45
поделиться

10 ответов

Different groups have different standards.

Firstly, I assume you know the difference between RuntimeExceptions (unchecked) and normal Exceptions (checked), if not then see this question and the answers. If you write your own exception you can force it to be caught, whereas both NullPointerException and IllegalArgumentException are RuntimeExceptions which are frowned on in some circles.

Secondly, as with you, groups I've worked with but don't actively use asserts, but if your team (or consumer of the API) has decided it will use asserts, then assert sounds like precisely the correct mechanism.

If I was you I would use NullPointerException. The reason for this is precedent. Take an example Java API from Sun, for example java.util.TreeSet. This uses NPEs for precisely this sort of situation, and while it does look like your code just used a null, it is entirely appropriate.

As others have said IllegalArgumentException is an option, but I think NullPointerException is more communicative.

If this API is designed to be used by outside companies/teams I would stick with NullPointerException, but make sure it is declared in the javadoc. If it is for internal use then you might decide that adding your own Exception heirarchy is worthwhile, but personally I find that APIs which add huge exception heirarchies, which are only going to be printStackTrace()d or logged are just a waste of effort.

At the end of the day the main thing is that your code communicates clearly. A local exception heirarchy is like local jargon - it adds information for insiders but can baffle outsiders.

As regards checking against null I would argue it does make sense. Firstly, it allows you to add a message about what was null (ie node or tokens) when you construct the exception which would be helpful. Secondly, in future you might use a Map implementation which allows null, and then you would lose the error check. The cost is almost nothing, so unless a profiler says it is an inner loop problem I wouldn't worry about it.

7
ответ дан 5 December 2019 в 05:08
поделиться

Стандартное исключение Java - IllegalArgumentException . Некоторые выбросят NullPointerException , если аргумент равен нулю, но для меня NPE имеет коннотацию «кто-то облажался», и вы не хотите, чтобы клиенты вашего API думали, что вы не знаете, что вы делаю.

Для общедоступных API: проверьте аргументы и завершите работу рано и чисто. Время / стоимость не имеют значения.

12
ответ дан 5 December 2019 в 05:08
поделиться

В Java обычно возникает исключение IllegalArgumentException

7
ответ дан 5 December 2019 в 05:08
поделиться

Если вам нужно руководство о том, как писать хороший код Java, я настоятельно рекомендую книгу Джошуа Блоха Эффективная Java .

2
ответ дан 5 December 2019 в 05:08
поделиться

Похоже, это подходящее использование для assert :

public void setTokens(Node node, int newTokens) {
    assert node != null;
    tokens.put(node, newTokens);
}
2
ответ дан 5 December 2019 в 05:08
поделиться

Ваш подход полностью зависит от того, какой контракт ваша функция предлагает вызывающим абонентам - это предварительное условие, что узел не null?

Если это так, то вы должны сгенерировать исключение, если node имеет значение NULL, поскольку это нарушение контракта. Если это не так, ваша функция должна молча обрабатывать нулевой узел и отвечать соответствующим образом.

2
ответ дан 5 December 2019 в 05:08
поделиться

I think a lot depends on the contract of the method and how well the caller is known.

At some point in the process the caller could take action to validate the node before calling your method. If you know the caller and know that these nodes are always validated then i think it is ok to assume you'll get good data. Essentially responsibility is on the caller.

However if you are, for example, providing a third party library that is distributed then you need to validate the node for nulls, etcs...

An illegalArugementException is the java standard but is also a RunTimeException. So if you want to force the caller to handle the exception then you need to provided a check exception, probably a custom one you create.

1
ответ дан 5 December 2019 в 05:08
поделиться

Лично я бы хотел, чтобы исключения NullPointerExceptions происходили ТОЛЬКО случайно, поэтому необходимо использовать что-то еще, чтобы указать, что было передано недопустимое значение аргумента. IllegalArgumentException подходит для этого.

if (arg1 == null) {
 throw new IllegalArgumentException("arg1 == null");
}

Этого должно быть достаточно как для тех, кто читает код, так и для бедняги, которой позвонят в службу поддержки в 3 часа ночи.

(и ВСЕГДА предоставляйте пояснительный текст для ваших исключений. , вы их оцените в один печальный день)

1
ответ дан 5 December 2019 в 05:08
поделиться

как и другой: java.lang.IllegalArgumentException. О проверке нулевого узла, как насчет проверки неверного ввода при создании узла?

0
ответ дан 5 December 2019 в 05:08
поделиться

Мне не нужно никому угождать, так что теперь, как канонический код, я делаю

void method(String s) 

if((s != null) && (s instanceof String) && (s.length() > 0x0000))
{

, что заставляет меня много спать.

Другие не согласятся.

0
ответ дан 5 December 2019 в 05:08
поделиться
Другие вопросы по тегам:

Похожие вопросы: