Pergunta

Dê-me alguns de seus pensamentos sobre o que é uma prática melhor de codificação / torna o código mais eficiente / parece mais bonita / whatever: Aumentar e melhorar a sua capacidade de utilização if para antecipar e pegar potenciais problemas? Ou simplesmente fazer bom uso de try / catch em geral?

Vamos dizer que isto é para Java (se importa).

Editar: Estou presentemente a transição me longe de algumas práticas de codificação atuais reconhecidamente fora de moda e constrangidos, mas eu sou um pouco rasgada sobre a necessidade de fazê-lo em alguns pontos (tais como esta). Estou simplesmente pedindo algumas perspectivas sobre este assunto. Não é um debate.

Outras dicas

blocos if são ligeiramente mais rápido; se você não vai precisar de uma dúzia deles, eles são uma ideia melhor do que try/catches. Exceções devem ser excepcionais, não cada vez que o código é executado. Eu uso Exceções para eventos raros como desconexões servidor (mesmo que eles acontecem algumas vezes todos os dias), e blocos if para qualquer um dos meus variáveis ??controláveis.

Independentemente do que o código que você está escrevendo, você vai acabar usando ambos. Eu não posso falar para o tempo de execução Java, mas no .NET runtime há um desempenho hit associado com o uso de blocos try-catch. Como resultado, eu tento usá-los somente em áreas onde eu tenho uma forma clara para lidar com a exceção uma vez capturados (mesmo que seja apenas registrando a existência de um problema).

Se você está usando um monte de ambos os blocos try-catch ou blocos if-else em seu código, ou seus métodos tendem a ser bastante longa, considere refatoração do código em um número maior de métodos menores. A intenção de sua lógica será mais fácil seguir -., Bem como mais fácil de teste de unidade

Eu acho que se as declarações são melhores. Você não pode cercar cada linha de código com um try..catch (bem você pode, mas você não deve fazê-lo). Você pode cercar um bloco de código com try catch, mas não todas as linhas.

E exceções coisas abrandar.

My 2p: Using try/catch is best:

  • it makes it absolutely clear to other coders that you are doing exception handling
  • the compiler understands what you are doing and can perform more appropriate compile-time checks for you

In my experience, using if-conditional-logic makes it more difficult to distinguish error handling from business logic.

From what I've been told by more experienced developers and analysts, try/catch is more object oriented and if is more procedural.

I personally don't care.

I'm aware of the fact that a try/catch is slower and causes a performance hit, but if I'm going to use a dozen ifs to validate before I can do what I want to do, I will always use a try/catch to save on the number of lines of code.

It makes my life so much easier to not have to validate anything and if the statement fails, just do what I would have done in my 'else' block...in my 'catch' block.

Sometimes, I obviously enclose some if statements in a try/catch, but anyways.

I use an if when there's only a small number of things to validate (1 or 2) before doing what I need to do.

There's one thing that hasn't been mentioned here.

With an if-else statement, every time the code runs, at least 1 of the condition is guaranteed to be evaluated executed. I'm sure we all know how an if-else-elseif works, but to be clear... the if portion of the statement will always be evaluated, if it's false then the following else-if is evaluated, and so forth until only the else is left to evaluate.

So using an if-else statement will impact your performance. Not significantly (in most cases), but it does take CPU time to perform the evaluations.

try-catch statements, and correct me if I'm wrong, don't get considered at runtime until they're required (i.e. an exception is thrown). So simply wrapping your code in a try-catch will not affect performance until an exception is actually caught by it.

Also, it is not the catch that causes the performance hit, but the throw.

And one major point to make is, try-catch statements should NEVER be used for conditional logic. They should only be used for what they're designed for: exception handling!

Catching exceptions is essential, if you know what to do with them. If you have no way of properly handling the exception then you should let it go, for some code further up the chain may have a better way to handle it.

Its usually a good idea to have an exception hander at the absolute top level of your application to catch exceptions before they are seen by the user. In ASP.NET you can do this in the Application_Error event of the global.asax. In other languages/environments you would do so in your main loop, whatever that may be.

But note, there are some exceptions that are always best left uncaught. Sometimes when an exception happens it is an indicator that the state of your application has been severely compromised and cannot be trusted. The only safe thing to do is to kill and restart.

@PersonalPerson - Sorry, but this is just lazy coding. Rather than using a try-catch because there's too many if statements, why not refactor your code (i.e. put your validation logic in its own method). This will keep your code cleaner and more readable and maintain best practices for performance.

Never try to write your code to achieve the least # of lines. This will always end up badly. Sure you can find a more elegant way to write something that your coder-buddies will ooh and aah at, but it just makes things less readable.

I swear, I've worked with your code before, and it made my head hurt.

Using exceptions is universal method to notify other part of code that something wrong happened in loosely coupled way. Let imagine that if you would like to handle some exceptional condition by using if.. nad else.. you need to insert into different part of your code some arbitrary variables and other stuff which probably would easily led to have spaghetti code soon after.

Let next imagine that you are using any external library/package and it's author decided to put in his/her code other arbitrary way to handle wrong states - it would force you to adjust to its way of dealing with it - for example you would need to check if particular methods returns true or false or whatever.

Using exceptions makes handling errors much more easy - you just assume that if something goes wrong - the other code will throw exception, so you just wrap the code in try block and handle possible exception on your own way.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top