Recently I wrote a small piece of code for my project need and the code works fine...
if (Utils.nullOrEmpty(string1))
{
Config config = getConfig();
if (config != null)
{
doX();
}
}
else
{
doY();
}
if (Utils.nullOrEmpty(string2))
{
Config config = getConfig();
if (config != null)
{
doA();
}
}
else
{
doB();
}
I am not convinced the way it is written and I feel there is a scope for improvement to make it better........
Please give me some suggestions to make it better... Is there a scope to use lambdas ??.........
-
1\$\begingroup\$ Welcome to StackExchange Code Review! Please review How do I ask a good Question? Specifically, it is best to explain what the code does. This is especially true in the title. \$\endgroup\$Stephen Rauch– Stephen Rauch2017年06月23日 04:43:06 +00:00Commented Jun 23, 2017 at 4:43
-
\$\begingroup\$ Is this your actual code, or a generalized version? \$\endgroup\$Daniel– Daniel2017年06月23日 06:02:53 +00:00Commented Jun 23, 2017 at 6:02
-
\$\begingroup\$ Generalized version.... do..() methods work fine..... I need some suggestions on re-organizing my code so that it is more readable.... \$\endgroup\$mani kandan– mani kandan2017年06月23日 06:21:22 +00:00Commented Jun 23, 2017 at 6:21
-
\$\begingroup\$ @manikandan we usually don't review pseudo-code. You should put your real code here ;) preferably add the whole class code. You should also consider making your title clearer \$\endgroup\$Ronan Dhellemmes– Ronan Dhellemmes2017年06月23日 08:30:13 +00:00Commented Jun 23, 2017 at 8:30
2 Answers 2
You could make an interface like :
interface Do {
void doSometing();
}
Implement it :
class DoA implements Do {
void doSometing() {/* do A */}
}
class DoB implements Do {
void doSometing() {/* do B */}
}
(DoC
.......DoD
......etc)
And use it by :
if (someConditionX) {
process(string1, new DoA(), new DoB());
process(string2, new DoC(), new DoD());
}
where process is defined by:
void process(String string, Do doA, Do doB) {
if(nullOrEmpty(string)){
if (getConfig() != null) {doA.doSometing(); }
}else {
doB.doSometing();
}
}
As for using Lambda expression, you could implement the interface using Lambda:
process (string1, ()->{/* implement doSomething */;}, new DoB());
When you extract the common parts of the code, you get this:
void doSomething(String s, Runnable action, Runnable actionIfEmpty) {
if (Utils.nullOrEmpty(s)) {
Config config = getConfig();
if (config != null) {
actionIfEmpty.run();
}
} else {
action.run();
}
}
You would then use the above code like this:
doSomething(string1, this::doX, this::doY);
doSomething(string2, this::doA, this::doB);
Explore related questions
See similar questions with these tags.