That rule's Summary is that "Methods should not have too many parameters" and its description is: "This audit rule finds methods that have more than the specified number of parameters.
You can now choose to sort by Trending, which boosts votes that have happened recently, helping to surface more up-to-date answers. Once identified, these constructors and methods can be manually changed/refactored to reduce the number of parameters with approaches such as the ones I've outlined in earlier posts in this series of too many parameters. These include Java Coding Standard Checker and Sonar. These situations usually denote the need for new objects to wrap the numerous parameters.". Cannot Get Optimal Solution with 16 nodes of VRP with Time Windows. Dodgy - Unsigned right shift cast to short/byte, Dodgy - Vacuous bit mask operation on integer value, Dodgy - Vacuous comparison of integer value, Dodgy - Write to static field from instance method, Dodgy - instanceof will always return true, Dodgy - int division result cast to double or float, Dodgy - private readResolve method not inherited by subclasses, Experimental - Potential lost logger changes due to weak reference in OpenJDK, Field isn't final but should be refactored to be so, Field names should start with a lower case letter, Format string should use %n rather than \n, Internationalization - Consider using Locale parameterized version of invoked method, Malicious code vulnerability - Field is a mutable Hashtable, Malicious code vulnerability - Field is a mutable array, Malicious code vulnerability - Field isn't final and can't be protected from malicious code, Malicious code vulnerability - Field should be both final and package protected, Malicious code vulnerability - Field should be moved out of an interface and made package protected, Malicious code vulnerability - Field should be package protected, Malicious code vulnerability - Finalizer should be protected, not public, Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object, Malicious code vulnerability - May expose internal representation by returning reference to mutable object, Malicious code vulnerability - May expose internal static state by storing a mutable object into a static field, Malicious code vulnerability - Public static method may expose internal representation by returning array, Method may fail to clean up stream or resource on checked exception, Multithreaded correctness - A thread was created using the default empty run method, Multithreaded correctness - A volatile reference to an array doesn't treat the array elements as volatile, Multithreaded correctness - Call to static Calendar, Multithreaded correctness - Call to static DateFormat, Multithreaded correctness - Class's readObject() method is synchronized, Multithreaded correctness - Class's writeObject() method is synchronized but nothing else is, Multithreaded correctness - Condition.await() not in loop, Multithreaded correctness - Constructor invokes Thread.start(), Multithreaded correctness - Empty synchronized block, Multithreaded correctness - Field not guarded against concurrent access, Multithreaded correctness - Inconsistent synchronization, Multithreaded correctness - Incorrect lazy initialization and update of static field, Multithreaded correctness - Incorrect lazy initialization of static field, Multithreaded correctness - Method calls Thread.sleep() with a lock held, Multithreaded correctness - Method does not release lock on all exception paths, Multithreaded correctness - Method does not release lock on all paths, Multithreaded correctness - Method spins on field, Multithreaded correctness - Method synchronizes on an updated field, Multithreaded correctness - Mismatched notify(), Multithreaded correctness - Mismatched wait(), Multithreaded correctness - Monitor wait() called on Condition, Multithreaded correctness - Mutable servlet field, Multithreaded correctness - Possible double check of field, Multithreaded correctness - Static Calendar, Multithreaded correctness - Static DateFormat, Multithreaded correctness - Sychronization on getClass rather than class literal, Multithreaded correctness - Synchronization on Boolean could lead to deadlock, Multithreaded correctness - Synchronization on boxed primitive could lead to deadlock, Multithreaded correctness - Synchronization on boxed primitive values, Multithreaded correctness - Synchronization on field in futile attempt to guard that field, Multithreaded correctness - Synchronization on interned String could lead to deadlock, Multithreaded correctness - Synchronization performed on java.util.concurrent Lock. Code checks for specific values returned by compareTo, Comparing values with incompatible type qualifiers, Correctness - Value required to not have type qualifier, but marked as unknown, Correctness - "." The PMD-provided action when this rule is triggered is to "try to group the parameters together" with a "a new object [that] should be created to wrap the numerous parameters" (see my post on parameters objects). Class defines tostring(); should it be toString()? Alternatively, the method could be refactored into several methods, each doing part of the task and requiring less parameters at input." Consider moving some of the values and behavior associated with them into a separate class.". By Dustin Marx, Newer PMD documentation puts it this way, "Methods with numerous parameters are a challenge to maintain, especially if most of them share the same datatype. My understanding of that expression is that it means that despite whatever positive statistics might be associated with that player or team, watching the player or team play leads one to believe that they are not as good as the statistics might indicate. What would the ancient Romans have called Hercules' Club? Modern Java IDEs are particularly helpful in the refactoring and code generation efforts. As the last series of screen snapshots demonstrate, NetBeans 7.4 allows us to specifically inspect code for methods and constructors that have "too many parameters." Correctness - The readResolve method must not be declared as a static method. In my case a Spring service needed a lot of other services in order to do its work. Is the fact that ZFC implies that 1+1=2 an absolute truth? I covered the application of the builder pattern and even discussed using NetBeans to refactor a builder in a previous post in this series. So rule squid:S00107 fired and gave me an error in the SonarCube. Selecting "Default" allows me to now click on the "Manage" button and clicking on that button presents the "Configuration" window. Connect and share knowledge within a single location that is structured and easy to search. One of the my favorite approaches for dealing with too many parameters to a constructor is application of a builder. "Was the x, y or the z first argument?". Why is the US residential model untouchable and unquestionable? It is also worth noting that CodePro Analytix also supports a "Average Number of Parameters" metric for metrics reporting. To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Once the methods and constructors with potentially too many parameters have been identified, the developer can apply the "eye test" to them to determine if corrective action should be taken. IntelliJ IDEA has a similar refactoring tool called Replace Constructor with Builder. In other words, in a way that is difficult to describe, the viewer feels the team or player is not as skilled as their statistics imply. Large number of parameters indicate a bad design. If a creature's best food source was 4,000 feet above it, and only rarely fell from that height, how would it evolve to eat that food? Robert Martin, in Clean Code, writes (page 40): Steve McConnell, in Code Complete, writes that developers should "limit the number of a routine's parameters to about seven" because "seven is a magic number for people's comprehension." The next screen snapshot demonstrates use of Java Code Metrics in NetBeans 7.4. Find centralized, trusted content and collaborate around the technologies you use most. For my demonstration purposes, I select "All Analyzes" and then click on the "Inspect" button. Fortunately, NetBeans provides the ability to automatically refactor code relying on numerous parameter constructor to use a builder implementation. In the twin paradox or twins paradox what do the clocks of the twin and the distant star he visits show when he's at the star? Why does KLM offer this specific combination of flights (GRU -> AMS -> POZ) just on one day when there's a time change? Multithreaded correctness - Unconditional wait, Multithreaded correctness - Unsynchronized get method, synchronized set method, Multithreaded correctness - Using notify() rather than notifyAll(), Multithreaded correctness - Wait not in loop, Multithreaded correctness - Wait with two locks held, Negating the result of compareTo()/compare(), Non-transient non-serializable instance field in serializable class, Performance - Could be refactored into a named static inner class, Performance - Could be refactored into a static inner class, Performance - Huge string constants is duplicated across multiple class files, Performance - Inefficient use of keySet iterator instead of entrySet iterator, Performance - Maps and sets of URLs can be performance hogs, Performance - Method allocates a boxed primitive just to call toString, Performance - Method allocates an object, only to get the class object, Performance - Method calls static Math class method on a constant value, Performance - Method invokes inefficient Boolean constructor; use Boolean.valueOf() instead, Performance - Method invokes inefficient Number constructor; use static valueOf instead, Performance - Method invokes inefficient floating-point Number constructor; use static valueOf instead, Performance - Method invokes inefficient new String() constructor, Performance - Method invokes inefficient new String(String) constructor, Performance - Method invokes toString() method on a String, Performance - Method uses toArray() with zero-length array argument, Performance - Primitive value is boxed and then immediately unboxed, Performance - Primitive value is boxed then unboxed to perform primitive coercion, Performance - Should be a static inner class, Performance - The equals and hashCode methods of URL are blocking. This inspection allows the number of method parameters that is too many to be configured. The next two screen snapshots demonstrate that these values are set for constructors and methods respectively in the same window where we checked the options we wanted inspected. Announcing the Stacks Editor Beta release! Dependency injection through constructors or property setters? Like @sp00m, having too many dependency probably means that your service has too many responsibility and that your service should be break into smaller service. Constructors typically take more parameters than a regular method, especially when initializing a large object. This hint is described as, "Reports constructor that take too many parameters. All of the hints in the "Java Code Metrics" category of NetBeans 7.4 are disabled by default. In many ways, it's a matter of taste and depends somewhat on what those parameters are, if they use custom types rather than primitives and repeated types, and whether there are optional parameters that might require null to be passed. Another newly added hint, "Method declares too many parameters," is described as, "Reports method that take too many parameters. Methods whose signatures are inherited from library classes are ignored by this inspection." Tannakian-type reconstruction of etale fundamental group. The next screen snapshot indicates that I can select "Constructor declares too many parameters" as a checkbox and "Method declares too many parameters" as another checkbox. How would electric weapons used by mermaids function, if feasible? It is nice to be able to easily change the number of parameters deemed unacceptable (or at least worth pointing out so that the "eye test" can be applied) because there is such widely differing opinions on what number is unacceptable. Is a neuron's information processing more complex than a perceptron? US to Canada by car with an enhanced driver's license, no passport? The first seven posts of my series of dealing with too many parameters expected in Java methods focused on alternative approaches to reduce the number of parameters a method or constructor expects. This recommended approach is essentially the same as the parameters object approach I blogged about earlier in this series of posts. I've already mentioned NetBeans plug-ins for Checkstyle and PMD, but one of my favorite features in NetBeans is the numerous and highly customizable built-in NetBeans hints and inspections. In Checkstyle's case, the default "maximum allowable number of parameters" for a constructor or method is 7 (same number as Steve McConnell's recommendation). Too many dependencies probably means that your design doesn't respect. Fortunately, there are some tools that can aid in these refactoring and new code generation efforts. For example, in software, we might say that "fewer parameters is generally better than more parameters." used for regular expression, Correctness - A collection is added to itself, Correctness - A known null value is checked to see if it is an instance of a type, Correctness - A parameter is dead upon entry to a method but overwritten, Correctness - An apparent infinite recursive loop, Correctness - Apparent method/constructor confusion, Correctness - Array formatted in useless way using format string, Correctness - Bad attempt to compute absolute value of signed 32-bit hashcode, Correctness - Bad attempt to compute absolute value of signed 32-bit random integer, Correctness - Bad comparison of nonnegative value with negative constant, Correctness - Bad comparison of signed byte, Correctness - Bad constant value for month, Correctness - Bitwise OR of signed byte value, Correctness - Bitwise add of signed byte value, Correctness - Call to equals() comparing different interface types, Correctness - Call to equals() comparing different types, Correctness - Call to equals() comparing unrelated class and interface, Correctness - Call to equals() with null argument, Correctness - Can't use reflection to check for presence of annotation without runtime retention, Correctness - Check for sign of bitwise operation, Correctness - Check to see if (() & 0) == 0, Correctness - Class defines field that masks a superclass field, Correctness - Class overrides a method implemented in super class Adapter wrongly, Correctness - Collections should not contain themselves, Correctness - Creation of ScheduledThreadPoolExecutor with zero core threads, Correctness - Dead store of class literal, Correctness - Deadly embrace of non-static inner class and thread local, Correctness - Don't use removeAll to clear a collection, Correctness - Doomed attempt to append to an object output stream, Correctness - Doomed test for equality to NaN, Correctness - Double.longBitsToDouble invoked on an int, Correctness - Exception created and dropped rather than thrown, Correctness - Field not initialized in constructor, Correctness - Field only ever set to null, Correctness - File.separator used for regular expression, Correctness - Format string placeholder incompatible with passed argument, Correctness - Format string references missing argument, Correctness - Futile attempt to change max pool size of ScheduledThreadPoolExecutor, Correctness - Impossible downcast of toArray() result, Correctness - Incompatible bit masks (BIT_AND), Correctness - Incompatible bit masks (BIT_IOR), Correctness - Integer multiply of result of integer remainder, Correctness - Integer shift by an amount not in the range 0..31, Correctness - Invalid syntax for regular expression, Correctness - Invocation of hashCode on an array, Correctness - Invocation of toString on an anonymous array, Correctness - Invocation of toString on an array, Correctness - JUnit assertion in run method will not be noticed by JUnit, Correctness - MessageFormat supplied where printf style format expected, Correctness - Method assigns boolean literal in boolean expression, Correctness - Method attempts to access a prepared statement parameter with index 0, Correctness - Method attempts to access a result set field with index 0, Correctness - Method call passes null for nonnull parameter, Correctness - Method call passes null for nonnull parameter (ALL_TARGETS_DANGEROUS), Correctness - Method call passes null to a nonnull parameter, Correctness - Method defines a variable that obscures a field, Correctness - Method does not check for null argument, Correctness - Method doesn't override method in superclass due to wrong package for parameter, Correctness - Method ignores return value, Correctness - Method may return null, but is declared @NonNull, Correctness - Method must be private in order for serialization to work, Correctness - Method performs math using floating point precision, Correctness - More arguments are passed that are actually used in the format string, Correctness - No previous argument for format string, Correctness - No relationship between generic parameter and method argument, Correctness - Non-virtual method call passes null for nonnull parameter, Correctness - Nonsensical self computation involving a field (e.g., x & x), Correctness - Nonsensical self computation involving a variable (e.g., x & x), Correctness - Null pointer dereference in method on exception path, Correctness - Null value is guaranteed to be dereferenced, Correctness - Nullcheck of value previously dereferenced, Correctness - Number of format-string arguments does not correspond to number of placeholders, Correctness - Possible null pointer dereference, Correctness - Possible null pointer dereference in method on exception path, Correctness - Primitive array passed to function expecting a variable number of object arguments, Correctness - Primitive value is unboxed and coerced for ternary operator, Correctness - Random value from 0 to 1 is coerced to the integer 0, Correctness - Return value of putIfAbsent ignored, value passed to putIfAbsent reused, Correctness - Self comparison of field with itself, Correctness - Self comparison of value with itself, Correctness - Signature declares use of unhashable class in hashed construct, Correctness - Static Thread.interrupted() method invoked on thread instance, Correctness - Store of null value into field annotated NonNull, Correctness - Suspicious reference comparison of Boolean values, Correctness - Suspicious reference comparison to constant, Correctness - TestCase declares a bad suite method, Correctness - TestCase defines setUp that doesn't call super.setUp(), Correctness - TestCase defines tearDown that doesn't call super.tearDown(), Correctness - TestCase implements a non-static suite method.