У меня была эта та же проблема пару раз. В прошлом я решил это при помощи веб-приложения как запуск, но похоже, что Вы уже сделали это.
Мое сообщение на предмете: http://www.donnfelker.com/silverlight-cross-domain-issue/
DD and DU anomalies (if I remember correctly—I use FindBugs and the messages are a little different) refer to assigning a value to a local variable that is never read, usually because it is reassigned another value before ever being read. A typical case would be initializing some variable with null
when it is declared. Don't declare the variable until it's needed.
Assigning null
to a local variable in order to "assist" the garbage collector is a myth. PMD is letting you know this is just counter-productive clutter.
Specifying final on a local variable should be very useful to an optimizer, but I don't have any concrete examples of current JITs taking advantage of this hint. I have found it useful in reasoning about the correctness of my own code.
Specifying interfaces in terms of… well, interfaces is a great design practice. You can easily change implementations of the collection without impacting the caller at all. That's what interfaces are all about.
I can't think of many cases where a caller would require a LinkedList
, since it doesn't expose any API that isn't declared by some interface. If the client relies on that API, it's available through the correct interface.
Block level synchronization allows the critical section to be smaller, which allows as much work to be done concurrently as possible. Perhaps more importantly, it allows the use of a lock object that is privately controlled by the enclosing object. This way, you can guarantee that no deadlock can occur. Using the instance itself as a lock, anyone can synchronize on it incorrectly, causing deadlock.
Operands of type short
are promoted to int
in any operations. This rule is letting you know that this promotion is occurring, and you might as well use an int
. However, using the short
type can save memory, so if it is an instance member, I'd probably ignore that rule.
Не может установить для объекта значение null помочь в сборке мусора, если объект - это локальный объект (не используется вне метода)? Или это миф?
Единственное, что он делает, это позволяет объекту быть GCd до завершения метода, что редко когда-либо необходимо.
Есть ли какие-либо преимущества в использовании конечных параметров и переменных?
Это дает код более ясен, так как вам не нужно беспокоиться о том, что значение где-то изменится, когда вы анализируете код. Чаще всего вам не нужно или вы не хотите изменять значение переменной после ее установки.
Если я знаю, что мне конкретно нужен LinkedList, почему бы мне не использовать его для ясно дать понять мои намерения будущие разработчики?
Можете ли вы назвать причину, по которой вам может понадобиться LinkedList?
Одно дело вернуть класс, который находится выше путь к классам имеет смысл, но почему я бы не объявил свои переменные в самом строгом смысле?
Меня не особо интересуют локальные переменные или поля, но если вы объявите параметр метода типа LinkedList
, я выслежу вас и причиню вам боль, потому что это заставляет Мне невозможно использовать такие вещи, как Arrays.asList ()
и Collections.emptyList ()
.
Какие преимущества дает синхронизация на уровне блоков перед синхронизацией на уровне методов?
] Самая большая из них заключается в том, что он позволяет вам использовать выделенный объект монитора, так что только те критические секции являются взаимоисключающими, а не все, использующие один и тот же монитор.
В мире Java, почему бы мне не используйте тип, который лучше всего описывает мой data?
Потому что типы, меньшие, чем int, автоматически повышаются до int для всех вычислений, и вам нужно привести вниз, чтобы присвоить им что-нибудь. Это приводит к загромождению кода и довольно большой путанице (особенно, когда задействован автобокс).
AvoidUsingShortType: не используйте короткий тип
Элемент списка
short - это 16 бит, дополнение 2 в java
DataflowAnomalyAnalysis: Found 'DD'-anomaly for variable 'variable' (lines 'n1'-'n2').
DataflowAnomalyAnalysis: Found 'DU'-anomaly for variable 'variable' (lines 'n1'-'n2').
No idea.
NullAssignment: Assigning an Object to null is a code smell. Consider refactoring.
Wouldn't setting an object to
null
assist in garbage collection, if the object is a local object (not used outside of the method)? Or is that a myth?
Objects in local methods are marked to be garbage collected once the method returns. Setting them to null won't do any difference.
Since it would make less experience developers what is that null assignment all about it may be considered a code smell.
MethodArgumentCouldBeFinal: Parameter 'param' is not assigned and could be declared final
LocalVariableCouldBeFinal: Local variable 'variable' could be declared final
Are there any advantages to using
final
parameters and variables?
It make clearer that the value won't change during the lifecycle of the object.
Also, if by any chance someone try to assign a value, the compiler will prevent this coding error at compile type.
consider this:
public void businessRule( SomeImportantArgument important ) {
if( important.xyz() ){
doXyz();
}
// some fuzzy logic here
important = new NotSoImportant();
// add for/if's/while etc
if( important.abc() ){ // <-- bug
burnTheHouse();
}
}
Suppose that you're assigned to solve some mysterious bug that from time to time burns the house.
You know what wast the parameter used, what you don't understand is WHY the burnTHeHouse
method is invoked if the conditions are not met ( according to your findings )
It make take you a while to findout that at some point in the middle, somone change the reference, and that you are using other object.
Using final
help to prevent this kind of things.
LooseCoupling: Avoid using implementation types like 'LinkedList'; use the interface вместо этого
Если я знаю, что мне конкретно нужен
LinkedList
, почему бы мне не использовать его, чтобы четко разъяснить свои намерения будущим разработчикам? Одно дело - вернуть класс, который находится наверху по пути к классам, что имеет смысл, но почему бы мне не объявить свои переменные самыми строгими?
В этом случае нет никакой разницы. Я думаю, что, поскольку вы не используете специфические функции LinkedList
, предложение является справедливым.
Сегодня LinkedList может иметь смысл, но с помощью интерфейса вы помогаете себе (или другим) легко изменить его, когда это не так.
Для небольших личных проектов это может вообще не иметь смысла, но, поскольку вы уже используете анализатор, я думаю, вы уже заботитесь о качестве кода.
Кроме того, помогает менее опытному разработчику сформировать хорошие привычки. уровень блока, а не уровень метода синхронизация
Какие преимущества имеет синхронизация на уровне блоков по сравнению с синхронизацией на уровне методов?
Чем меньше синхронизированная секция, тем лучше. Вот и все.
Кроме того, если вы синхронизируете на уровне метода, вы заблокируете весь объект. Когда вы синхронизируете на уровне блоков, вы просто синхронизируете этот конкретный раздел, в некоторых ситуациях это то, что вам нужно.
AvoidUsingShortType: не используйте short type
My first languages were C and C++, but in the Java world, why should I not use the type that best describes my data?
I've never heard of this, and I agree with you :) I've never use short though.
My guess is that by not using it, you'll been helping your self to upgrade to int
seamlessly.
Code smells are more oriented to code quality than performance optimizations. So the advice are given for less experienced programmers and to avoid pitfalls, than to improve program speed.
This way, you could save a lot of time and frustrations when trying to change the code to fit a better design.
If it the advise doesn't make sense, just ignore them, remember, you are the developer at charge, and the tool is just that a tool. If something goes wrong, you can't blame the tool, right?
Какие преимущества имеет синхронизация на уровне блоков перед синхронизацией на уровне методов? Синхронизация метода похожа на
синхронизацию (getClass ())
блокирует и блокирует весь класс.
Возможно, вы не хотите, чтобы