Java8 splitting long interface method into separate methods - if-statement

I have the below default method in an interface and it seems to be pretty complex because of the many if-else conditions.
default void validate() {
Application application = application().get();
if (StringUtils.isEmpty(application.name()) || application.data() == null) {
throw new IllegalArgumentException());
} else {
for (Form form : application.data().forms) {
if (StringUtils.isEmpty(form.getId())) {
throw new IllegalArgumentException();
}
for (Question question : form.getQuestions()) {
if (StringUtils.isEmpty(question.getQuestion())
|| StringUtils.isEmpty(question.getValue())) {
throw new IllegalArgumentException();
}
}
}
}
}
I want to split this into different methods to reduce the complexity. However since the project is configured to use Java8, private methods cannot be used in the interface. How else can I break this down and reduce the complexity? Any advice would be much appreciated.

For refactoring to better readability and reduced complexity of your validate method I would apply the Extract Method refactoring. But depending on the available Java version you have different options for default interface methods.
There are different options at hand in Java 8 and Java 9. In both cases you could of course extract methods to abstract interface methods which would need to be implemented by the implementation classes. But I guess you want to keep the default implementation code of the extracted classes inside your interface as well. So I will not address this option here.
Java 8
If you are restricted to Java 8 you can - in addition to the already mentioned public abstract methods - extract methods as either other public default methods or public static methods of your interface.
Here is a simple refactoring approach for extracting methods into public default interface methods:
public interface ApplicationValidatorJava8WithDefaults {
default void validate() {
Application application = application().get();
validateApplication(application);
for (Form form : application.data().forms) {
validateForm(form);
}
}
default void validateApplication(Application application) {
if (StringUtils.isEmpty(application.name()) || application.data() == null) {
throw new IllegalArgumentException();
}
}
default void validateForm(Form form) {
if (StringUtils.isEmpty(form.getId())) {
throw new IllegalArgumentException();
}
for (Question question : form.getQuestions()) {
validateQuestion(question);
}
}
default void validateQuestion(Question question) {
if (StringUtils.isEmpty(question.getQuestion())
|| StringUtils.isEmpty(question.getValue())) {
throw new IllegalArgumentException();
}
}
Application application();
}
Now the same with extracting methods into public static interface methods:
public interface ApplicationValidatorJava8WithStatics {
default void validate() {
Application application = application().get();
validateApplication(application);
for (Form form : application.data().forms) {
validateForm(form);
}
}
static void validateApplication(Application application) {
if (StringUtils.isEmpty(application.name()) || application.data() == null) {
throw new IllegalArgumentException();
}
}
static void validateForm(Form form) {
if (StringUtils.isEmpty(form.getId())) {
throw new IllegalArgumentException();
}
for (Question question : form.getQuestions()) {
validateQuestion(question);
}
}
static void validateQuestion(Question question) {
if (StringUtils.isEmpty(question.getQuestion())
|| StringUtils.isEmpty(question.getValue())) {
throw new IllegalArgumentException();
}
}
Application application();
}
Java 9
If you can use Java 9 you can - in addition to all the already mentioned options methods - extract methods as either private instance methods or private static methods of your interface.
Here is a simple refactoring approach for extracting methods into private instance interface methods:
public interface ApplicationValidatorJava9WithPrivateInstanceMethods {
default void validate() {
Application application = application().get();
validateApplication(application);
for (Form form : application.data().forms) {
validateForm(form);
}
}
private void validateApplication(Application application) {
if (StringUtils.isEmpty(application.name()) || application.data() == null) {
throw new IllegalArgumentException();
}
}
private void validateForm(Form form) {
if (StringUtils.isEmpty(form.getId())) {
throw new IllegalArgumentException();
}
for (Question question : form.getQuestions()) {
validateQuestion(question);
}
}
private void validateQuestion(Question question) {
if (StringUtils.isEmpty(question.getQuestion())
|| StringUtils.isEmpty(question.getValue())) {
throw new IllegalArgumentException();
}
}
Application application();
}
Now the same with extracting methods into private static interface methods:
public interface ApplicationValidatorJava9WithPrivateStaticMethods {
default void validate() {
Application application = application().get();
validateApplication(application);
for (Form form : application.data().forms) {
validateForm(form);
}
}
private static void validateApplication(Application application) {
if (StringUtils.isEmpty(application.name()) || application.data() == null) {
throw new IllegalArgumentException();
}
}
private static void validateForm(Form form) {
if (StringUtils.isEmpty(form.getId())) {
throw new IllegalArgumentException();
}
for (Question question : form.getQuestions()) {
validateQuestion(question);
}
}
private static void validateQuestion(Question question) {
if (StringUtils.isEmpty(question.getQuestion())
|| StringUtils.isEmpty(question.getValue())) {
throw new IllegalArgumentException();
}
}
Application application();
}
Note: I also removed the first else branch as it is obsolete after throwing an exception in the first if clause. Good IDEs (such as IntelliJ) will already inform you about that and remove it for you with a single command. This already improves complexity as the overall nesting of the method is already reduced by one level.

Related

How to implement the State design pattern?

Let's say I am going to implement (in the C++) following finite state machine consisting of 5 states where the transitions between the states occur based on value of 6 boolean flags. In each of the states only a couple of the total number of the boolean flags is relevant e.g. in the State_A the transition into the State_B is conditional by following condition: flag_01 == true && flag_02 == true and the value of the rest of the flags is irrelevant.
I would like to exploit the State design pattern for implementation of the state machine
I have unfortunately stuck at the very beginning. Namely on definition of the interface of the common base class for all the state subclasses. It seems to me that my situation is little bit different from the examples mentioned in the literature where the state transitions occur based on single events with a guard condition. Can anybody give me an advice how to define the interface for the common base class in my situation where the transitions between states occur based on logic expressions with several operands?
You can create some reducer which will decide what state should be user. Let me show an example via C#.
This is an abstraction of state:
public interface IAtmMachineState
{
void Execute();
}
and its concrete states:
public class WithdrawState : IAtmMachineState
{
public void Execute()
{
Console.WriteLine("You are taking money");
}
}
public class DepositState : IAtmMachineState
{
public void Execute()
{
Console.WriteLine("You are putting money");
}
}
public class SleepState : IAtmMachineState
{
public void Execute()
{
Console.WriteLine("Insert your card");
}
}
and this is context of state:
public class AtmStateContext
{
private IAtmMachineState _currentState;
public AtmStateContext()
{
_currentState = new SleepState();
}
public void SetState(IAtmMachineState currentState)
{
_currentState = currentState;
}
public void Execute()
{
_currentState.Execute();
}
}
And this is a reducer which can take parameters:
public class StateReducer
{
public IAtmMachineState Get(int a, string b)
{
if (a == 0)
return new WithdrawState();
else if (!string.IsNullOrEmpty(b))
return new DepositState();
return new SleepState();
}
}
And it can be used like this:
AtmStateContext atmState = new AtmStateContext();
StateReducer stateReducer = new StateReducer();
atmState.SetState(stateReducer.Get(1, ""));
atmState.Execute(); // OUTPUT: insert your card

VS2015: TraceSource Output in Test Explorer?

I've got a library that I'm trying to unit test. I use TraceSource to write out warning details, and as I have the unit tests set to run as part of the build, I'd like them to show up when the tests are run - particularly on failure.
I've tried the following code to register a trace listener, but my WriteLine stuff never gets called, despite the constructor being called. See code at the bottom [1].
How do I get my traces to show up as part of the test runner?
[1] Code for my testcontexttracelistener:
[TestClass]
public class TestContextTraceListener : TraceListener
{
TestContext testContext;
public TestContextTraceListener(TestContext testContext)
{
this.testContext = testContext;
}
public override void Write(string message)
{
// EP TODO: This is likely going to create newlines where they shouldn't be, but testContext doesn't have a .Write, and I'm too lazy to buffer.
this.WriteLine(message);
}
public override void WriteLine(string message)
{
this.testContext.WriteLine(message);
}
}
[TestClass]
public class TestAssemblyInitializeAndCleanup
{
static TraceListener traceListener;
[AssemblyInitialize]
public static void OnInitialize(TestContext testContext)
{
if (traceListener == null)
{
// This code is reached, but the listener never gets triggered.
traceListener = new TestContextTraceListener(testContext);
Trace.Listeners.Add(traceListener);
}
}
[AssemblyCleanup]
public static void OnCleanup()
{
Cleanup();
}
static void Cleanup()
{
if (traceListener != null)
{
traceListener.Flush();
Trace.Listeners.Remove(traceListener);
traceListener.Dispose();
}
}
}

How to decouple process in business layer

I am facing a problem that, for some business processes the sequence of invoking business objects and methods may change frequently. So I came up with something similar to the below:(Sorry somehow I can't post image..., I tried to express them in the below text)
Business Objects:
Object1, Object2
Methods: M1, M2, M3, M4
Processes: P1 (M1 > M2 > M3), P2 (M2 > M3 > if M3 return true then M4 else end)
In this case I am using .NET 3.5. I create some classes to represent processes, which contains those sequences I mentioned. It works. But the problem is I need to compile every time when process changed. It would be much better if I could configure it by some sort of XML.
I have heard about jBPM for Java, Workflow Foundation for .NET but not sure if they fit my needs, or would they be overkill. I even don't what keyword to search in Google. Could anyone advice what technology I should use to solve this issue? Or just point me to some websites or books? Thanks in advance.
A common way to decouple software layers is by using interfaces as stated by Dependency Inversion Principle. In you case you could abstract the process concept using an interface and implement the logic in the implementation of that interface.
when you need change the logic of the process you can create a new implementation of that interface. You can use any IoC framework to inject what implementation you want to use
below is showed just a simple way to do that:
public interface IMethod
{
void M1();
string M2();
void M3();
void M4();
}
public interface IProcess
{
IMethod Method { get; set; }
void P1();
void P2();
}
public class Process : IProcess
{
public IMethod Method
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void P1()
{
Method.M1();
Method.M2();
}
public void P2()
{
if(Method.M2()==string.Empty)
{
Method.M3();
}
}
}
public class AnotherProcess : IProcess
{
public IMethod Method
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void P1()
{
Method.M4();
}
public void P2()
{
Method.M2();
Method.M4();
}
}
public class UseProcess
{
private IProcess _process;
//you can inject the process dependency if you need use a different implementation
public UseProcess(IProcess process)
{
_process = process;
}
public void DoSomething()
{
_process.P1();
}
}

Testable design with COM objects

What is a good way to design for testing and extensibility when a component used to complete a task could either be a COM component or a .NET component? Does it make sense to wrap the COM component completely and extract an interface? Here is a simple, completely contrived, RCW interface on a COM component, where "abc" is the acronym for the component maker:
public interface IComRobot
{
void abcInitialize(object o);
void abcSet(string s, object o);
void abcBuild();
void abcExit();
}
To me, the fact that the provider of the component chose to prefix all methods with something indicating their company is somewhat irritating. The problem is, I want to define other Robot components that perform the same actions, but the underlying implementation is different. It would be completely confusing to Robot builders to have to implement "abcAnything".
How should I go about building a RobotFactory with a simple implementation that works like this?
public class RobotFactory
{
public static IRobot Create(int i)
{
// // problem because ComRobot implements IComRobot not IRobot
if (i == 0) return new ComRobot();
if (i == 1) return new AdvancedRobot();
return new SimpleRobot();
}
}
Should I bite the bullet and accept the abc prefix in my interface, thus confusing robot implementers? Should I force a dependency on the Robot consumer to know when they are using the COM robot? None of these seem ideal. I'm thinking about an additional level of abstraction (that can solve everything, right?). Something like so:
public interface IRobot : IDisposable
{
void Initialize(object o);
void Set(string s, object o);
void Build();
void Exit();
}
public class ComRobotWrapper: IRobot
{
private readonly IComRobot m_comRobot;
public ComRobotWrapper()
{
m_comRobot = ComRobotFactory.Create();
}
public void Initialize(object o)
{
m_comRobot.abcInitialize(o);
}
public void Set(string s, object o)
{
m_comRobot.abcSet(s, o);
}
public void Build()
{
m_comRobot.abcBuild();
}
public void Exit()
{
m_comRobot.abcExit();
}
public void Dispose()
{
//...RELEASE COM COMPONENT
}
}
public class ComRobotFactory
{
public static IComRobot Create()
{
return new ComRobot();
}
}
I would then alter and use the RobotFactory like so:
public class RobotFactory
{
public static IRobot Create(int i)
{
if (i == 0) return new ComRobotWrapper();
if (i == 1) return new AdvancedRobot();
return new SimpleRobot();
}
}
public class Tester
{
// local vars loaded somehow
public void Test()
{
using (IRobot robot = RobotFactory.Create(0))
{
robot.Initialize(m_configuration);
robot.Set(m_model, m_spec);
robot.Build();
robot.Exit();
}
}
}
I'm interested in opinions on this approach. Do you recommend another approach? I really don't want to take on a DI framework, so that is out of scope. Are the pitfalls in testability? I appreciate you taking the time to consider this lengthy issue.
That looks spot on to me. You are creating an interface that is right for your domain / application, and implementing it in terms of a thrid party component.

NUnit Conditional Teardown?

Is there a way to do a conditional TearDown in NUnit?
I have a TestFixture which has a need to run cleanup code for just a few tests, and I don't really want to:
Run the TearDown method on every test
Create a private helper method and call it from the tests requiring cleanup if I can avoid it
There isn't unfortunately.
Can you not do the cleanup in the [TestFixtureTearDown] instead, so once all the tests have finished? I guess that depends on whether the cleanup has to be done before the next test runs.
Alternatively, put those tests that require a cleanup in another class/TextFixture together, away from the other tests. Then you can use a TearDown in there which doesn't need to be conditional.
Edit:
One thing I've just thought of, which could be done to achieve the aim though probably isn't actually worth it for this particular need, is that you can extend NUnit - create your own custom attributes which you could handle however you wanted. This is mentioned here. Like I say, I don't think really you should go down that route for this, but is useful to know none-the-less
You can have the main TearDown in a base class:
[TearDown]
public virtual void TearDown()
{
// Tear down things here
}
and then override it in the class where you have the tests that should not run the tear down code:
[TearDown]
public override void TearDown()
{
// By not calling base.TearDown() here you avoid tearing down
}
Extend all you classes with test from BaseTest
public class BaseTest
{
[SetUp]
public void BeforeTest()
{
GetService<NUnitHooksController>().ExecuteBeforeTestHooks(this);
}
[TearDown]
public void AfterTest()
{
GetService<NUnitHooksController>().ExecuteAfterTestHooks(this);
}
}
Use AfterTest and BeforeTest hooks. Works both with and without category.
public class ExampleTest : BaseTest
{
[Test, Category("asdasd")]
public void Test01()
{
...
}
[AfterTest("asdasd")]
public void ExampleHook()
{
...
}
}
public class NUnitHooksController
{
private readonly ILogger _log;
public NUnitHooksController(ILogger log)
{
_log = log;
}
public void ExecuteBeforeTestHooks(object testClass)
{
ExecuteHooks(testClass, typeof(BeforeTestAttribute));
}
public void ExecuteAfterTestHooks(object testClass)
{
ExecuteHooks(testClass, typeof(AfterTestAttribute));
}
private MethodInfo[] GetHookMethods(object currentTestClass, Type attributeType)
{
return currentTestClass
.GetType()
.GetMethods()
.Where(m => m.GetCustomAttributes(attributeType, false).Length > 0)
.ToArray();
}
private void ExecuteHooks(object testClass, Type requiredAttributeType)
{
var hooks = GetHookMethods(testClass, requiredAttributeType);
var testCategories = GetTestCategories();
foreach (var hook in hooks)
{
var allAttributes = hook.GetCustomAttributes(requiredAttributeType, true);
foreach (var attribute in allAttributes)
{
if (!attribute.GetType().IsEquivalentTo(requiredAttributeType))
{
continue;
}
var hookCategories = GetCategoriesFromAttribute(attribute);
// if we do not have specific category on hook
// or we have at least one same category on hook and test
if (!hookCategories.Any() || hookCategories.Intersect(testCategories).Any())
{
ExecuteHookMethod(testClass, hook);
}
}
}
}
private object[] GetTestCategories()
{
return TestContext.CurrentContext.Test.Properties["Category"].ToArray();
}
private void ExecuteHookMethod(object testClass, MethodInfo method)
{
var hookName = method.Name;
_log.Information($"Executing - '{hookName}' hook");
try
{
method.Invoke(testClass, Array.Empty<object>());
}
catch (Exception e)
{
_log.Error($"Executing of - '{hookName}' hook failed - {e}");
}
}
private string[] GetCategoriesFromAttribute(object attribute)
{
if (attribute is BeforeTestAttribute beforeTestAttribute)
{
return beforeTestAttribute.Categories;
}
if (attribute is AfterTestAttribute afterTestAttribute)
{
return afterTestAttribute.Categories;
}
throw new ArgumentException($"{attribute.GetType().FullName} - does not have categories");
}
}
I have solved this using the name of the test:
namespace TestProject
{
public class TestClass
{
// Test without TearDown
[Test]
public void Test1()
{
Assert.Pass("Test1 passed");
}
// Test with TearDown
[Test]
public void Test2()
{
Assert.Pass("Test2 passed");
}
[TearDown]
public void TearDown()
{
// Execute only after Test2
if (TestContext.CurrentContext.Test.Name.Equals(nameof(this.Test2)))
{
// Execute Test2 TearDown...
}
}
}
}
Or if you want to use the full name of Test2 (TestProject.TestClass.Test2) you can replace the line
if (TestContext.CurrentContext.Test.Name.Equals(nameof(this.Test2)))
by
if (TestContext.CurrentContext.Test.FullName.Equals(typeof(TestClass).FullName + "." nameof(this.Test2)))