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 11 days ago.
Improve this question
I'm in a situation where I have a parent class
class Parent<T extends Entity> {
...
public List<T> selectSomething() {
String sql = "SELECT " + getColumns() + " FROM " + getTable() + " WHERE ...";
TypedQuery<T> query = this.entityManager.createQuery(sql, T.class);
return query.getResultList();
}
}
(For sake of simplicity, there is only a method described but in practice there are more with the same format)
And many child classes :
class Child1 extends Parent<EntityChild1> { ... }
class Child2 extends Parent<EntityChild2> { ... }
...
class Child50 extends Parent<EntityChild50> { ... }
My issue is that this piece of code in the Parent is detected as a security issue by tools like SonarQube for possible SQL injection, and this warning is a blocking point that I need to correct or bypass.
I precise the both method getColumns() and getTables() are 100% controlled by me and I do know for sure that there is no way for a user to interfere in any way with the returned values of those methods. So even if it's detected as SQL injection, I do know it's not one.
To fix this, I can't just use a prepared statement since the whole point of a prepared statement is to prevent to inject SQL code, so you can't use them for dynamic columns name or table name.
I'm considering two options :
Make the selectSomething method from the Parent abstract and reimplement it in each child with a fixed string for the request directly containing the table name and columns name.
This would work fine and fix the warning, but due to the high number of Child it makes the code much less maintainable and evolutive (especially considering that the number of Child class could increase over time).
Simply let it as is and use a #SupressWarning annotation in the selectSomething method from the Parent this make the tools like SonarQube ignore this.
Again, it's a solution that would work but which is not very clean and filling code with many #SupressWarning is a bad practice.
Is there any good way to handle this situation ? If not, is there any reason I should stick with a solution above the other ?
Reflect whether this isn't a design flaw on your inheritance model. If it isn't, well, stick with the solution that's less likely to introduce errors.
Warnings are just that, warnings, you may proceed with caution. Having a lot of code duplication is more likely to introduce errors, in my personal experience. But make sure the methods are actually 100% controlled by you. Make the possible security concerns clear in the documentation, both for you and future maintainers. That documentation will serve to avoid having it being falsely flagged as a security flaw and to help prevent someone from introducing that same security flaw. As referenced in the comments, pass as many things as you can to a Set or another data structure that maps a specific input to a specific output, with special attention to the special output, both for performance reasons and some peace of mind.
See Variable column names using prepared statements for a similar question.
Related
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 3 years ago.
Improve this question
I am new to java, was using php, python and js before. Lately python, so get used to something like "if myVar is None:". Here is my problem: I am getting locale from some library as Optional, I need to return a language only, or something else if timeout happened, or some errors, etc. Then I need to pass language to some object (context), and somewhere later convert context to request's parameters. So I do something like
String getLanguage(){
try {
Optional<String> locale = getLocale();
if (locale.isPresent()){logging, locale.get()-to-language conversion, language validation,
logging, return language}
else (logging, return null;)
} except {logging error, return null};
}
Context c = new Context();
c.setSomething(something);
c.setLanguage(getLanguage());
and somewhere later:
Request r = new Request();
r.addParam(something, c.getSomething());
if (c.getLanguage() != null) {r.addParam(language, c.getLanguage())
I have got a suggestion to rewrite everything using Optional. Replace my first method with something like.
Optional<String> getLanguage(){
try {
Optional<String> locale = getLocale();
return locale.ifPresent(logging)
.map(locale-to-language conversion, language validation, logging, return language}
.orElse(logging, return Optional.isEmpty())
} except {logging error, return Optional.isEmpty()};
}
and then somewhere later c.getLanguage().ifPresent(x -> r.addParam(language, x))
I never used Optional before, so I am happy to learn something new, and I assume for person who get used to Optional my code is not good. From other side I see that Optional here is overkill here - I need to modify my data class Context to deal with Optional, my map() and orElse() are ugly - they have 2-5 lines of code, etc. also unit tests need rework. So, my question is - are those changes to Optional adding some benefits or we are just following fashion without thinking.
So, my question is - are those changes to Optional adding some benefits ...
Well there are definitely advantages and disadvantages for both approaches:
Looking from the Optional side, the main "plus" is that you eliminate a major source of bugs; i.e. NPE's caused by not dealing with a possible returned null correctly. The main "minuses" are the verbosity of code that uses Optional, and that it doesn't actually eliminate all bugs; e.g. if you call Optional.get on an "empty" Optional you will get an exception.
Other Q&A's go into more detail:
Null check vs Optional is present check
Uses for Optional
Optional vs. null. What is the purpose of Optional in Java 8?
Is using Optional.ofNullable as a replacement for the ternary operator a good practice?
... or we are just following fashion without thinking.
That is a different question!
Now I imagine some people may be using Optional without thinking, but I don't see much evidence of that. It is clear that there are advantages AND disadvantages, and that thought is required.
So you should really be asking (yourself!) if >>you<< just following fashion without thinking? Or to put it another way, are you just treating this as a (so-called) "best practice", or are you making a reasoned choice between the two approaches depending on the context?
I have got a suggestion to rewrite everything [in my example] using Optional.
Here's what I suggest.
Create a branch in your version control system.
In the branch, change your API method to use Optional, and change all of the places in your code that use the API method.
Make a judgement: has this improved things? was the effort worth it?
If the API is currently or going to used by other people's code, ask their opinions too.
Decide whether to proceed or not, implement decision, and move on to the next issue.
If that sounds like too much work, another option is to quietly ignore that suggestion.
Either way, we (the StackOverflow community) can't decide for you. We don't have the context1, and even if we did, there would be a range of opinions and no clear correct answer.
1 - For instance, what is the likelihood of there being no locale, and no determinable language. What the application as a whole should do about it? Should it bail out? Should it substitute a default? Could the default be substituted ... here? We can't see "the big picture".
I would say Optional is good when your code knows how to deal with the null situation. For example you can write
public String helloWorld(Optional<Long> input){
String toReturn = "Hello "+ input.orElse("0")+ " times";
return toReturn;
}
However, if you are interfacing with legacy code and those functions expect null inputs, which force you to write something like
if(someOptional.isPresent()){
return somevalue;
} else{
return null;
}
In the above case, Optional does not bring you more than using null only. In this case I would use null over Optional.
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 6 years ago.
Improve this question
do you prefer writing method with immediate return of result to assigning it firstly to variable? To be clear we only consider situation presented below when no other operations are done in method body.
First option:
private List<Integer> getIdsOfUsersLoggedWithinLastHour() {
return userDAO.getUsersLoggedWithinLastHour().stream().map(User::Id).collect(Collectors.toList());
}
Second option:
private List<Integer> getIdsOfUsersLoggedWithinLastHour() {
List<Integer> ids = userDAO.getUsersLoggedWithinLastHour().stream().map(User::Id).collect(Collectors.toList());
return ids;
}
IMHO there is no need to assign result of method operations to variable when you do nothing with it and just return. The return type is declared in method signature so you can easily check it. The code cleanliness is about the same. You use some additional memory and cpu operations (maybe not so important today but it is always something additional). Friend of mine claims that initializing variable is better for easier debugging and further code development but I think it is redundant and can be done when you really need this, not 'for future'. What is your opinion?
In many cases I plump for the second option and, in the cited case, I almost certainly would.
This allows you to place a breakpoint on return ids; which can be helpful when debugging. (Inspecting the contents of a CPU register is an option in low level languages like C, but I don't think that is available for JVM-based languages).
A series of functions that return an anonymous temporary up the stack can be difficult to debug.
I wouldn't worry about any overhead that the second choice introduces: that ought to be optimised out and declaring an extra reference variable is unlikely to cause a performance bottleneck even if it was not optimised out. (Note that in C++ it will be optimised out via a process called Named Return Value Optimisation and I imagine that Java would follow suit.) Remember that being able to debug and maintain code is as important as elegance; whatever that means in this particular instance.
I assign result to the variable only when need to do some logic with it before returning value from the method. Otherwise I use coding style from the first example - makes code concise.
Second code style can help during debug process sometimes, but you shouldn't commit this IMHO
Also, if you inspect second example with any popular static analysis tool it would give a result like "local variable is redundant" which is one more reason to eliminate those vars in real projects.
Good article about this design issue: http://www.yegor256.com/2015/09/01/redundant-variables-are-evil.html
But you must understand that it's only a common practice, nobody can make you do not use redundant variables - code works with them correctly, it's only a question of taste like many other design principles
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
Is it considered bad style to use long, but descriptive method names such as "adjacentLocationsByState()" and if so, would it be better to shorten it to something like "adjLocByState" which is definitely shorter, but also less readable in my opinion
Don't make me think.
When I read your code, if I have to stop and think about what the method name might mean, it usually means that the method name is wrong. Longer method names are preferable when it adds useful context to the method.
There are two rules I basically follow when writing code:
Must be readable as a normal text to which a human eye got used from books and mass media (so adjLocByState is not the case)
Maximize brevity, utilize programming techniques - code conventions and default states. These could be applied when some of the terms start appear to repeat too often.
So, adjacentLocationsByState() reads perfectly fine, but it could be shortened to just:
adjacentLocations()
which by default would return locations by their state and adjacentLocations(STATE) or chaining with fluent interface technique which allows more options for having the criteria: adjacentLocations().by(STATE). STATE here is a member of an enum LocationCriteria.
So in the end of the day it could look like:
adjacentLocations()
adjacentLocations().by(STATE)
adjacentLocations(STATE)
Of course, there is a time sacrifice which is spent on coding the 2nd and the 3rd forms.
Longer version is more readable and the the code is self documenting. So a good method name = method responsibility. Adj can be understand as adjust or adjacent, etc.
Keep in mind: Code is read 10 times more than it is written.!
You really write code that will often be read again and again. The more meaningful your names are, the more understandable is the code.
You are declaring classes, fields, methods, variables, and many more. You are thinking about them, you are developping a well-defined structure. All the time, you make hard decisions. The names that you give to your entities (classes, fields, ...) reflect all your thoughts on that. They reflect the intention of your code.
Conclusion: Names are the most important properties of your code. So, you always should think deeply about the names you give to your variables, methods, and so on. And you always should not abbreviate them in what way ever.
Its part of Documentation.
Usually everybody like to write Code in two phases before commit:
Implementation
Documentation
By example (phase 1):
ObjectOutputStream oos = ...
List a : ob.getSOE();
for(Object a: b){
oos.writeObject(a);
}
Then phase 2:
ObjectOutputStream stackOverflowElementOuputStream = ...
List stackOverflowElements : ob.getStackOverflowElement();
for(Object currentStackOverflowElement: stackOverflowElements){
stackOverflowElementOuputStream.writeObject(currentStackOverflowElement);
}
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'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway. But if my theory is true then I'm not sure why they included the private access modifier...?
I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.
The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.
I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case...
I agree about using the default (package private) modifier for stuff that is to be accessed by tests, but I don't agree about private being unnecessary. Even for tests there is a lot of stuff that is not needed to be visible.
For a good test, implementation details are unnecessary and should not be visible outside the class. The more "whitebox" a test is, the more fragile it is. I usually limit the default modifier to fields I expect to be set via dependency injection and set manually in a test. (I could also use constructor injection and get rid of this, but this is more convenient.)
I propose little thought-experiment. Consider this code:
public void promoteUser(User user)
{
int newRank = computeNew(user);
user.setRank(newRank);
}
private int computeNewRank(User user)
{
return user.getRank() + 1;
}
One might feel computeNewRank should be tested (real implementation might do lot more stuff). But let's forget that for a moment and through the magic of inlining do this:
public void promoteUser(User user)
{
int newRank = user.getRank() + 1;
user.setRank(newRank);
}
The beauty of this experiment is that it applies to private methods of any size. You can always imagine yourself inlining private member and asking yourself "What do I really want to test here?". Is it the private method itself or perhaps new class/component with brand new functionality that's disguised as private method? The point is, you should rarely (if ever!) need to test private (or even package/internal) members. To outside world, to your contract consumers those are all irrelevant details.
Now, of course we could replace everything with system tests. But then how your regular work flow would look like? What if in order to test the rank promotion code you'd have to log user, register for session, wait 3 minutes, enter promotional code, receive sms, confirm... You see my point.
It's good to remember that unit tests are for you, not the other way around. You can bend them, adjust them, make them fit so that you can deliver software of better quality. Thier purpose is not to help you achieve some magical goal of 100% coverage, but rather to give you immediate feedback on what you're doing so that you can react more quickly to bugs and failures you will encounter. Or in other words, to improve your productivity.
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 9 years ago.
Improve this question
Yesterday I have attended interview in one Leading IT Service company. Technical interview was good, no issues, then I have moved to another set of round about Management, Design and Process. I have answered everything except the below question.
Question asked by interviewer:
Let say you are developing a class, which I am going to consume in my
class by extending that, what are the key points you keep in
mind? Ex, Class A, which has a method called "method A" returns a Collection,
let say "list". What are the precautions you will take?
My Answer: The following points I will consider, such as:
Class and method need to be public
Method 1 returns a list, then this needs to be generics. So we can avoid class cast exception
If this class will be accessed in a multi-threaded environment, the method needs to be synchronized.
But the interviewer wasn't convinced by my points. He was expecting a different answer from me but I am not able to get his thought process, what he was excepting.
So please provide your suggestions.
I would want you holding to design principles of Single Reaponsibility, Open/Close, and Dependency Injection. Keep it stateless, simple, and testable. Make sure it can be extended without needing to change.
But then, I wasn't interviewing you.
A few more points which haven't been mentioned yet would be:
Decent documentation for your class so that one doesn't have to dig too deep into your code to understand what functionality you offer and what are the gotchas.
Try extending your own class before handing it out to someone else. This way, you personally can feel the pain if you class is not well designed and thereby can improve it.
If you are returning a list or any collection, one important question you need to ask is, "can the caller modify the returned collection"? Or "is this returned list a direct representation of the internal state of your class?". In that case, you might want to return a copy to avoid callers messing up your internal state i.e. maintain proper encapsulation.
Plan about the visibility of methods. Draw an explicit line between public, protected, package private and private methods. Ensure that you don't expose any more than you actually want to. Removing features is hard. If something is missing from your well designed API, you can add it later. But you expose a slew of useless public methods, you really can't upgrade your API without deprecating methods since you never know who else is using it.
If you are returning a collection, the first thing you should think about is should I protect myself from the caller changing my internal state e.g.
List list = myObject.getList();
list.retainAll(list2);
Now I have all the elements in common between list1 and list2 The problem is that myObject may not expect you to destroy the contents of the list it returned.
Two common ways to fix this are to take a defensive copy or to wrap the collection with a Collections.unmodifiableXxxx() For extra paranoia, you might do both.
The way I prefer to get around this is to avoid returning the collection at all. You can return a count and a method to get the n-th value or for a Map return the keys and provide a getter, or you can allow a visitor to each element. This way you don't expose your collection or need a copy.
Question is very generic but i want to add few points:
Except the method which you want to expose make other methods and variable private. Whole point is keep visibility to minimum.
Where ever possible make it immutable, this will reduce overhead in mutithreaded environment.
You might want to evaluate if serializability is to be supported or not. If not then dont provide default constructor. And if serializable then do evaluate serialized proxy pattern.