java - When we override a method we should use all the parameters that are in the method signature? -


i found overrides methods not use parameters in signature of method.

ex:

@override protected void setsomething(object a, object b, object c) {     this.a =     this.b = b;     // parameter c not used (ignored) } 

normally parent class shouldn't care how children implements abstract methods.

but in mho, arguments of method use, it's rare when sub-class implementation doesn't need parameter, when happens there's problem design of interface or abstract class.

the base of 1 function is: inputs -> process of inputs -> output.

sometimes need calculate these inputs, if don't go use of these inputs in process of function, these inputs shouldn't place inputs of function.

you jump calculation of these inputs calling accurate function use inputs, accurate function.

the case situation acceptable, when don't want behavior of parent class, write:

@override protected void setsomething(object a, object b, object c) {       //nothing } 

or

@override  protected void setsomething(object a, object b, object c) {   throw new unsupportedoperationexception(...); } 

sonar says :

unused parameters misleading. whatever value passed such parameters is, behavior same.

my question is: when override method should use parameters in method signature?

when says 'use parameters', try parameters in method signature, use in body (implementation) of method.

when override method should use parameters in signature of method?

when override method, overriden method must define same parameters super-method.

you're not obligated use parameters in implementation - depends on want achieve implementation , not parameters may needed.

however, having unused method parameters within method implementation sign of poor design. when defining method (being abstract or implemented), should try answer questions of "why need parameter?" , "will parameter used?". if it's possible have cases parameters not used in implementation, define few overloaded methods.

take example, instance. let's have method

void somemethod(string first, string optionalparameter) { ... } 

the second parameter optional (i.e. may needed or may not be) - pass null or when parameter not needed. in case, overload 2 methods

void somemethod(string first) { ... }  void somemethod(string first, string second) { ... } 

and make sure parameters used in corresponding implementation.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -