How to optimize code below by getting rid of redundant? - java

My code below is to calculate ProductFunction based on some values of Object Product. Method getProductFunctions in InternalProductMapper and ExternalProductMapper call functions in ProductFunctionCalculator to calcuate the value of ProductFunction. According to me its not possible to have a single function in ProductFunctionCalculator, because two different mappers call it. How can I optimize the code below? Also, If I have two functions, i am not sure what to name the other as both calculate function for two different mappers.
public class InternalProductMapper{
public EnumSet<ProductFunction> getProductFunctions(Product p){
return productFunctionCalculator.get(p);
}
}
public class ExternalProductMapper{
public EnumSet<ProductFunction> getProductFunctions(Product p){
return p!=null ? productFunctionCalculator.calculate(p):
return EnumSet.of(Function.BUSINESS,Function.MARKET);
}
}
public class ProductFunctionCalculator{
public EnumSet<ProductFunction> calculate(Product p){
if(p.brand() == "ABC" && p.id.equals("1") && p.value > 100){
return EnumSet.of(Function.BUSINESS, Function.LOCAL);
}
}
public EnumSet<ProductFunction> get(Product p){
if(p != null && p.location.equals("NY")){
return EnumSet.of(Function.BUSINESS);
}
return EnumSet.of(Function.BUSINESS, Function.MARKET);
}
}

"Also, If I have two functions, i am not sure what to name the other as both calculate function for two different mappers."
You can name one calculateInternal and the other calculateExternal or similar, unless I misunderstand what you mean to say.
You can also add an Identifier on your Product object, to ascertain if it is internal or external(Could be a new field, boolean/enum or otherwise). You would need to set the value of this field on initialization of the Product object, when you most probably know what kind of Product it is. This could allow for a new single method of calculating, because now your method would know how to handle the different scenarios(As you have this new 'type' field), possibly via an if-else statement such as:
//This should not be allowed if you can help it and you should try and get
//rid of the scenario this comes in as null - just check it before calling this method
if(product != null) {
if(product.isInternal()) {
//Internal product logic
} else {
//External product logic
}
}

Related

a method validating objects from different roots repeats most of checks

please is there a way how to make the code more concise -
to avoid repeating similar/same actions -
I have a method doing object validations, but most parameters
are similar/same, like using some sort of lambda expression for that,
but objects are not from the same tree.
My use-case is like this:
validate.( car );
and somewhere else I do:
validate.( person );
Right now I am doing the validation like this:
public boolean validate( Object obj ) {
if ( obj instanceof Car ) {
Car car = (Car) obj;
if ( car.getAge() <= 0 ) return false;
// many other checks which are repeated below
} else if ( obj instanceof Person ) {
Person person = (Person) obj;
if ( person.getAge() <= 0 ) return false;
// many other check which are repeating those above
}
// here I would like to do checks for both objects, but objects are from different roots
return true;
}
You can use method overloading :
public boolean validate(Car car) {
if ( car.getAge() <= 0 ) return false;
return validate((Master)car);
}
public boolean validate(Person p) {
if ( p.getAge() <= 0 ) return false;
return validate((Master)p);
}
public boolean validate(Master m) {
// common validations
return true;
}
Master is the common parent of Person and Car (I assume there is a common parent interface/class).
"Do not"s:
First of all, I would strictly suggest you to try your best to avoid designing your method as you are doing it now;
Person and Car have nothing in common from the logical, modelling, or conceptual perspective. Nor they do share any similar characteristics in the real life;
Do not accept Object as an argument in your method. You will have hard times of managing your bugs and/or maintaining unpredictable behaviour.
"Do"s:
Define your method by following Single Responsibility Principle;
Consider from your model object perspective - what your method should be as a behaviour? what ONE problem it should solve?
Try to separate concerns in their respective classes/files/block-units and try not to overlap them.
If you want to your method to behave based on what is the actual instance of the argument, best way is to use instanceof checks.
What you can do instead, however, is to design some proper inheritance and accept a supertype, as a method argument. Then polymorphism would kick in and you will only have one logic in your method.

Better way of returning from condition

Which way of returning from condition is better , Like the process1 and process 2 both does the same. But I want to know better way returning.
In both cases I don't want to enter inside of loop, I just want to return. I would like to know that, Is there any performance difference If I put return before control passes to end. I don't want Java Virtual Machine to check end of loop and returning from there. I thought If I put return Immediately when the condition not satisfied, then I could see minor performance difference and also code readability. Please suggest me the best way.
Let us consider the below scenarios.
Process1:
public Method()
{ //Method
Company company = new Company(); //Object
if (null != Address && null = Address.location()) //Condition
{
return company; //I want to return
}
for (Location location: Address.location())
{
//forloop
}
return company; //return
}
Process2:
public Method()
{
Company company = new Company();
if (null != Address && null != Address.location())
{
//enters loop
}
return company; // return
}
There will be some performance impact. Iterating complete objects from the for loop to verify the condition.
For example:
We can write like this.
if(condition is false){
return ;
else{
for(DataType ref: collection){
if(true){
return;// return from here, so that it will not iterate remaining elements.
}
}
}
ex 2:
if there is a logic after the if and that should not be executed, if the object is null.
if(object is null){
return ;
}
//Remaining logic here will not be executed, if the object is null. it's a good way of writing.
ex 3:
if there is no logic after the if and else, then directly return from the end of method.
if(object is null){
return
}else{
//process logic and return.
}
you can write something like this.
if(object is not null){
// return either from here.
}
return here is also fine...

Check if returned value is not null and if so assign it, in one line, with one method call

Java is littered with statements like:
if(cage.getChicken() != null) {
dinner = cage.getChicken();
} else {
dinner = getFreeRangeChicken();
}
Which takes two calls to getChicken() before the returned object can be assigned to dinner.
This could also be written in one line like so:
dinner = cage.getChicken() != null? cage.getChicken() : getFreeRangeChicken();
But alas there are still two calls to getChicken().
Of course we could assign a local variable then use the ternary operator again to assign it if it is not null, but this is two lines and not so pretty:
FutureMeal chicken = cage.getChicken();
dinner = chicken != null? chicken : getFreeRangeChicken();
So is there any way to say:
Variable var = some value if some value is not null OR some other
value;
And I guess I'm just talking syntax here, after the code is compiled it probably doesn't make much difference how the code was written in a performance sense.
As this is such common code it'd be great to have a one-liner to write it.
Do any other languages have this feature?
Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.
dinner = Optional.ofNullable(cage.getChicken())
.orElse(getFreerangeChicken());
Note: This usage of Optional is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
You can use the result variable as your temporary, like this:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
Since Java 9 you have Objects#requireNonNullElse which does:
public static <T> T requireNonNullElse(T obj, T defaultObj) {
return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}
Your code would be
dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());
Which is 1 line and calls getChicken() only once, so both requirements are satisfied.
Note that the second argument cannot be null as well; this method forces non-nullness of the returned value.
Consider also the alternative Objects#requireNonNullElseGet:
public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
which does not even evaluate the second argument if the first is not null, but does have the overhead of creating a Supplier.
If you don't mind to use commons-lang you can use org.apache.commons.lang3.ObjectUtils#defaultIfNull
Your code would be:
dinner = ObjectUtils.defaultIfNull(cage.getChicken(),getFreeRangeChicken())
Using Java 1.8 you can use Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken to return either Optional.empty() instead of null, or Optional.of(myReturnObject), where myReturnObject is your chicken.
Then you can call getChicken() and if it would return Optional.empty() the orElse(fallback) would give you whatever the fallback would be, in your case the second method.
Use your own
public static <T> T defaultWhenNull(#Nullable T object, #NonNull T def) {
return (object == null) ? def : object;
}
Example:
defaultWhenNull(getNullableString(), "");
Advantages
Works if you don't develop in Java8
Works for android development with support for pre API 24 devices
Doesn't need an external library
Disadvantages
Always evaluates the default value (as oposed to cond ? nonNull() : notEvaluated())
This could be circumvented by passing a Callable instead of a default value, but making it somewhat more complicated and less dynamic (e.g. if performance is an issue).
By the way, you encounter the same disadvantage when using Optional.orElse() ;-)
You could use
Objects.requireNonNullElse(cage.getChicken(), getFreerangeChicken())
even nicer with static import:
import static java.util.Objects.requireNonNullElse;
requireNonNullElse(cage.getChicken(), getFreerangeChicken())
dinner = cage.getChicken();
if(dinner == null) dinner = getFreeRangeChicken();
or
if( (dinner = cage.getChicken() ) == null) dinner = getFreeRangeChicken();
Alternatively in Java8 you can use Nullable or NotNull Annotations according to your need.
public class TestingNullable {
#Nullable
public Color nullableMethod(){
//some code here
return color;
}
public void usingNullableMethod(){
// some code
Color color = nullableMethod();
// Introducing assurance of not-null resolves the problem
if (color != null) {
color.toString();
}
}
}
public class TestingNullable {
public void foo(#NotNull Object param){
//some code here
}
...
public void callingNotNullMethod() {
//some code here
// the parameter value according to the explicit contract
// cannot be null
foo(null);
}
}
http://mindprod.com/jgloss/atnullable.html

Why have a return keyword if you're not returning a value?

As I was reading my AP java book I stumbled upon this section that made no sense to me:
...The getBalance method simply returns the current balance. A return statement obtains the value of a variable and exits the method immediately. The return value becomes the value of the method call expression. The syntax of a return statement is:
return expression;
or
return; // Exits the method without sending back a value
Why would you want to have a return statement and "exit the method without sending back a value" if you could just make it void?
***Note: Sorry if this may be too subjective. I just couldn't understand the point and the book doesn't explain it.
The return keyword doesn't need to be at the end. For example:
public static void print42(int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if (numbers[i] == 42) {
System.out.println("has 42");
return;
}
}
System.out.println("no 42");
}
It can't just use a break, as that would print both strings.
This is kind of subjective. I'm old school, I believe in one entry and exit point for all methods/functions, but...
If you have a method with a void return type and if you had reached a point in your logic which would dictate that no further processing should take place, you could call return; to force the execution to return to the calling method at this point, foregoing any further execution of the method.
It would be the same as using something like return x; in the middle of a method body that had an expected return type (of whatever x is)
It's a little like using break to break out of a loop prematurely, except you're breaking out of the method before the execution gets to the end.
There are some situations where once you've verified something inside a void function, it makes sense to exit it immediately. For example:
public static void checkIfStringInList(List<String> searchList, String findString) {
for( String thisSearchString : searchList ) {
if( findString.equals(thisSearchString) )
return;
}
throw new Exception("String " + findString + " not found in list");
}
A method declared as void can exit with a return; this is just a shortcut for early termination. A method with a non-void return type must return a value of the right type, you can not have a method return "nothing" if it has a non-void return type.
If your method has a void return type, then the return statement is optional. You might want to use it anyway if, for instance, you wanted to stop execution in certain cases.
If the return type is not void, then using return; without an argument will give you a compile error.
In java if a method has a return type in its signature, you must return an object of that type or null before exiting the method.
for example
public A foo(boolean val){
A obj=null;
if (val){
obj=new A();
obj.setSomeAttribute();
}
return obj;
}
You can not compile source code if you just code "return;"

calling function should return default value, if object (or any function result) is null

Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}

Categories