Reusing an Exception class for a different purpose [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it in good practice to use an exception for a different purpose than the intended one, for the name? For example, I wanted an exception something along the lines of "Already exists" and I found the exception "EntityExistsException." The name was great, but it seems it was intended for the EntityManager. Is it okay to use the class, or should I create my own?

Read the documentation. Anyone unfamiliar with your code will look at the exception, and either know its documentation or go and read it.
In this case, the documentation says the exception is
thrown by the persistence provider when EntityManager.persist(Object)
is called
so if it is thrown in other circumstances by your code then your code isn't compatible with the Java API and has a bug.
I would tend to either use or subclass IllegalStateException for your case, since that is a general purpose exception, is widely used, and the state of 'the thing already existing' falls within its specification. If I expected that client code would handle the 'already exists' state differently than other failing states, then I would subclass it, otherwise I wouldn't.

This issue is probably best answered on a case by case basis, since "different purpose than the intended one" is a little bit vague to offer a complete suggestion on.
In your case, it may come down to a matter of taste. Personally, unless your already exists exception needs are related to the persistence layer, I would advise against reusing the exception from that package since it is easy to make a new exception and will not confuse any future developers or code that may infer the exception is being passed on from the underlying implementation.

Related

why switch or if else statement is not considered polymorphic? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Every answer on stack overflow provides information on how to replace switch or if else with polymorphism but
the switch, if else constructs also help in providing different behavior of an object with respect to context and inputs.
Why if else,switch is not considered as a part of polymorphism.
Conditional becomes a code smell when we have to check an object’s type in order to make some logic or behavior decision. It doesn’t matter whether it is a stack of if/else block or a switch statement.This violates open-closed principle.
The open closed principle states that the entities(classes, modules, functions etc) should be open for extension,but closed for modification.Which means that these entities won't be allowed to make changes in its source code.
This can be achieved through Abstraction and Polymorphism.
Benifits of Polymorphism over Conditionals
instead of asking an object about its state and then performing actions based on this, it is much easier to simply tell the object what it needs to do and let it decide for itself how to do that.
Removes duplicate code. You get rid of many almost identical conditionals.
If you need to add a new execution variant, all you need to do is add a new subclass without touching the existing code (Open/Closed Principle).
Polymorphism in a concept that allows an Object to retain behavior and properties from its parent classes. Explained further here and here
if, else and switch are procedural code constructs.
The two have nothing in common.
Edit: Thanks #Ted Hopp, correcting my post.

How do you make changes in dynamic languages, and find all of the places that will be broken by that change? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am used to programming in static languages like Java, where changing the signature of a method will cause a compilation error for every line of code that calls the method I changed. This makes modifying large projects much more easy, because I can make a change, and then let the compiler tell me about all the places that I need to fix.
When dealing with a large project in a dynamic language like Python or Ruby, how do you make code changes, and still remain confident that you are not going to be surprised with a run-time error in production because of some scenario you forgot about?
I've seen my fair share of NullPointerExceptions and ArrayIndexOutOfBoundsExceptions in Java, so it's not like these things never happen in a static language, I would just think they happen a lot less.
Here are some ideas for providing some level of the protection that you are used to in Java:
As stated in a previous comment, you should definitely provide adequate unit and integration testing to prevent any issues during a refactor. Testing is even more important in a dynamic language than in a statically-typed language. You should check that values are properly passed and handled in each of your functions.
Use PyCharm and search for usages on a method prior to making the update. This is not full-proof, but does find a good amount of method usage to allow for an easier refactor.
Do a global find for the method name in your editor or search program of choice.
Provide exception handling in your functions for cases where the type is incorrect or a value is unset.
Handle args and kwargs passed into your function carefully. Perhaps provide an error or debug log if you receive an unexpected input.
Provide default values for undefined parameters to a function.
Here is an example of providing a default value for a parameter to ensure that it is defined and initialized to None (similar to null) in the function if it is not passed in with a value:
def my_function(my_parameter=None):
# Do something with my_parameter

Precautions to Secure Java Coding [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am looking to gather some professional advises and precautions to do Secure Coding using Java. Couple of them I am already considering:
Should not log unwanted/excessive/sensitive information.
SQL injection should be taken care in parameterised queries, should use PreparedStatement or CallableStatement instead of Statement.
All the resources (db connections, input/output streams) should be release carefully.
Internal Exceptions should be caught and sanitized before propagating to upstream callers as it may reveal sensitive information.
Should clear the sensitive information even from memory when done as it can appear in core dump.
In case of inter-process communication, sensitive arguments should be encrypted.
Should use private for variables unless having good reason not to.
Should provide copy methods for sensitive classes.
Should prefer static factory method for object construction over public constructor.
Should avoid serialization of class that might hold sensitive information.
Appreciate any add up from the community.
Just another that comes to mind, you should use defensive copies when returning from a getter method.
If you're looking to protect your released code, you could consider something like JET although that's not quite what your question is asking I thought I'd just mention it.

Which type of exception should be generalized or created a base class for in a Java architecture [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
As a team lead which type of exception should I create a base class for in my architecture - checked or unchecked ? My team would start development in a few weeks and I want the architecture to be conducive to them for usage. Any reasons around that would also help.
That depends on the situation.
You use checked exceptions (extend Exception) for things that can go wrong regardless of the input the caller of the method passes. For example, network connections; you can make an HTTP GET request by calling client.get("google.com"); and everything goes well, two minutes later you call once again client.get("google.com"); and then you get an exception because of a network error. As you can see, here you called the same method passing the exact same input "google.com", yet you can get an exception at anytime. Therefore, you must force the caller to catch the exception by making it "checked", so that they handle those cases in which a network error occurs.
You use unchecked exceptions (extend RuntimeException) when the error happens because of some sort of invalid input by the caller of the method. For example, you have the method Integer.parse(String);. The method cannot work properly if you pass a null string here, so you throw an exception if that happens. This case, you should not force the caller to catch it, because the caller is responsible of passing the right input.
Overall: let the them decide, start with a short discussion. Helps people getting to know each-other.
I'd avoid checked exceptions: since they need to be explicitly catched, the catch block could become part of the normal program flow. Increases complexity and thus chance of introducing bugs.
Also don't use custom exceptions when possible, use existing exceptions like IllegalArgumentException. Avoid NullPointerExceptions by never returning null. Furthermore try to use something like bean-validation. That can save a lot of errors in your code caused by invalid (combinations of) arguments. And last but not least, failing fast is better then making your own faulty retry logic.

Pro/Cons of exceptions over the errorString() method [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I normally code in C++ using Qt framework. And for error handling I use the standard that Qt uses, which is calling a function like errorString() when a function behaves unexpectedly. For the current project I'm working on, I need to write my code in Java, and it is common to use Exceptions with try-catch-finally mechanism in Java.
My question is, will it be a big mistake to use errorString() like approach for error handling in Java. What are the advantages and disadvantages of using exceptions other than errorString().
Thank you.
The advantages are (according to Oracle's Advantages of Exceptions article):
Separating error-handling code from "regular" code
Propagating errors up the call stack
Grouping and differentiating error types
It is generally a good idea to write idiomatic code, sticking to the conventions and practices of the language you develop in. As I see it, that's an advantage in itself.
As far as cons go, at the top of my head:
It's really annoying to lazy programmers because you have to surround your code in try/catch, this may make it slightly more difficult to ignore the exceptions (I see this as an advantage).
It's easily misused by programmers who are new to the concept, and in turn you get severely uglified codebase on top of an arcane home-brewed error reporting system.
As far as whether or not it will be a mistake goes, well, as long as the entire team are Qt masterminds and have to write something in Java on an accidental basis and this code will never have to be managed by anyone who is supposed to be a Java expert, then sure - make a familiar environment for yourself and your team. But in any other circumstance, I highly recommend that you use exceptions instead.
The advantage is solely dependent on your implementation... See, for instance, you can catch a particular exception, wrap it and throw its parent exception ( a mechanism which is very widely used..). This way you can have a hierarchy of exceptions and you handle all exceptions in a general way... Suppose you have a DB and assume for some reason you get a connection exception... Now, you dont have to worry about handling that exception there and then.. you say that your method "throws" this exception and let the caller worry about it..the caller might wait for some time and then try to connect to DB again,,, Furthermore you can use finally to release resources/clean up... You are doing much more than errorString() (printing an error message..) . You can also include logging in here if you want to..

Categories

Resources