Implementing Java Interface with extra method in implementing Class - list

First post so be gentle. :) I'm not sure what I am doing wrong here, hopefully someone can help me out.
I have an Class that implements the List interface. This class also has it's own method that will only add an item to the list if it is not already in the list. The trouble is that when I try to use my conditionalAdd method, I get a error stating that it can't find my method because it is looking for it in the WorkflowSubType class. Please see below:
When I instantiate the Class I am using:
List<WorkflowSubType> currentViolations = new Violations();
This is the definition of my class that implements the List interface:
import java.util.*;
public class Violations<E> implements List<E>{
public Violations() {}
public void conditionalAdd(E violation){
if(violation != null)
if(!this.contains(violation))
add(violation);
}
#Override
public <T> T[] toArray(T[] a) {
return null;
}
#Override
public boolean add(E e) {
return false;
}
#Override....
So how come I can't access the conditionalAdd method. The currentViolations object I created is a List, but it's also a Violations type. Am I correct in saying this?
Thanks in advance.
RW

You will need to cast your instance to Violations. If you don't do so, the compiler interprets it as a List, and a List does not have the conditionalAdd method. Do it like this: ((Violations<WorkflowSubType>)currentViolations).conditionalAdd(whatever);

Related

Which pattern to use in order to execute new code by just adding new subclasses of a base class?

I am trying to figure out a pattern to avoid code duplication in a situation similar to the one bellow:
std::list<int> error_list;
void validate()
{
if( validate_0001() == false )
{ error_list.push_back(1); }
if( validate_0002() == false )
{ error_list.push_back(2); }
...
}
The method 'validate' is public in a class responsible for performing different actions, in the example validations, each one with an unique id. I want to be able to add a new action by just extending a base class, without the need to create a new method and add its call and its error handling inside the validate method.
I'm suggesting you use validating decorators (Here is a Java example)
abstract class Validation {
final List<Integer> list;
Validation(List<Integer> list) {
this.list = list;
}
public abstract int error();
}
class FirstValidation extends Validation {
public FirstValidation(List<Integer> list) {
super(list);
}
#Override
public int error() {
return 0;
}
}
You can't really extend a single function from a base class without extending the whole class.
One thing you can do is make the validation methods in a separate class and extend it by the two other classes. Another thing you can do is make the validations as an abstract class and implement it as you please in the child classes,the disadvantage of this approach is that you would have to provide the implementation in each of the child classes.

Writing List of Items using JdbcBatchItemWriter

Currently i am using JpaItemWriter to write the list of objects as below which is working fine.
Now i want to change the JpaItemWriter to JdbcBatchItemWriter due to performance issue.
public class MyItemWriter implements ItemWriter<List<MyDomainObject>> {
#Override
public void write(List<? extends Lists<MyDomainObject>> items) {
JpaItemWriter<MyDomainObject> writer = new JpaItemWriter<>();
for(List<MyDomainObject> o : items)
{
writer.write(o);
}
}
}
Suggest a sample snippets which uses the JdbcBatchItemWriter to write the List of objects will helps. Tried using the ItemSqlParameterSourceProvider it did't help ending up in org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter exception
You example is not correct. You are creating a JpaItemWriter in the write method, so a new instance is created on each call to write. This is probably the cause of your performance issue.
More importantly, lifecycle methods of the delegate writer (open/update/close) will not be honored (it is not the case for JpaItemWriter which does not implement ItemStream but this would be a problem if the delegate is an item stream). Your MyItemWriter implementation should be something like:
public class MyItemWriter implements ItemWriter<List<MyDomainObject>> {
private JpaItemWriter jpaItemWriter;
public MyItemWriter(JpaItemWriter jpaItemWriter) {
this. jpaItemWriter = jpaItemWriter;
}
#Override
public void write(List<? extends Lists<MyDomainObject>> items) {
for(List<MyDomainObject> o : items) {
this. jpaItemWriter.write(o);
}
}
}
Now if you want to use the JdbcBatchItemWriter to write a list of lists, see Spring Batch - Using an ItemWriter with List of Lists.
Edit: Added a sample code of how to set the delegate as requested in comments:
#Bean
public ListUnpackingItemWriter<T> itemWriter() {
JdbcBatchItemWriter<T> jdbcBatchItemWriter = null; // configure your jdbcBatchItemWriter
ListUnpackingItemWriter<T> listUnpackingItemWriter = new ListUnpackingItemWriter<>();
listUnpackingItemWriter.setDelegate(jdbcBatchItemWriter);
return listUnpackingItemWriter;
}

A C++ issue with multiple inheritance, templates and static variables

I have a code similar to the following:
template<class ObjType>
class jsonable
{
private:
static map<string, jsonElem> config;
protected:
virtual void setConfig() = 0;
//other fields and methods in public/private
}
class user : public jsonable<user>
{
protected:
virtual void setConfig();
//other fields and methods in public/private
}
class client : user
{
protected:
virtual void setConfig() {user::setConfig(); /* more config */}
//other fields and methods in public/private
}
The main idea of this code is to save in static variables data related to the class referenced in the template. The problem comes when I want to inherit from the user class: the static variable is shared between user and client classes, instead of one static variable for each class.
I've tried to do something like:
class client : user, jsonable<client>
But a bunch of problems appeared (many methods with same name, and some other related to inherit 2 times the same class). I don't know if there is an elegant way of do this, or even if there is a way at all. (I'm a bit newbie in c++)
Any idea would be welcome! :). And of course, I can "copy" all the contents of user into client but... I would like to do not do that until there are no more options.
Edit:
In order to add context and details to the question, I'm going to explain a bit what I'm doing (or want to do).
Jsonable is a class that provides the ability to serialize into Json another class (helped by https://github.com/nlohmann/json).
To achive this, it uses a static map to store each jsonable-field name and its info (type and position relative to the start of the class in memory, so it can be serialized and deserialized).
The problem comes if a class inherits from another class that inherits from jsonable. Both shares that map, so only the baseclass data is consider when serializing/deserializing. Hope this explanation helps to understand...
Edit2: Giving a full code in a question seems very overkilling to me. If someone wants something to compile, I've uploaded a git repo: https://github.com/HandBe/jsontests
Really thanks to all the people who have put interest on this question!.
A possible solution can be derive client from both user (because it is a user) and jsonable<client> as (private/public apart)
class user : public jsonable<user>
{
protected:
virtual void setConfig();
//other fields and methods in public/private
};
class client: public user, public jsonable<client>
{
virtual void setConfig()
{
user::setConfig();
// more config, referred to jsonable<client>::map
}
}
because it has to implement jsonable for itself (regardless of user).
This is the so-called "stacked parallelogram" inhertiance pattern very common in multiple interface implementations as modular behavior.
Now user and client have each their own configuration
If I understand your problem correctly: you want client to be a user, but also have all the per-class statics defined in jsonable?
Have you considered composition over inheritance? This could work either way:
1) make user a component of client
class client : public jsonable<client>
{
user parent; // could also be a pointer
void setConfig() {parent.setConfig(); /* more config */}
/* ... */
}
2) make jsonable a component:
class user
{
jsonable<user> userjson; // public, private, whatever is appropriate for your design
/* ... */
}
class client : public user
{
jsonable<client> clientjson;
/* ... */
}

Mock/Test Super class call in subclass..is it possible?

I am looking for a solution to mock the super call in subclass ButtonClicker.
Class Click {
public void buttonClick() throws java.lang.Exception { /* compiled code */ } }
Class ButtonClicker extends Click {
#Override
public void buttonClick() throws Exception {
super.buttonClick();
} }
Using inheritance reduces testability of your code. Consider replacing inheritance with the delegation and mock the delegate.
Extract the interface IClicker
interface IClicker {
void buttonClick();
}
Implement IClicker in Clicker class. In case that you are working with third-party code consider using Adapter Pattern
Rewrite your ButtonClicker as following:
class ButtonClicker implements IClicker {
Clicker delegate;
ButtonClicker(Clicker delegate) {
this.delegate = delegate;
}
#Override
public void buttonClick() throws Exception {
delegate.buttonClick();
}
}
Now just pass the mock as a constructor parameter:
Clicker mock = Mockito.mock(Clicker.class);
// stubbing here
ButtonClicker buttonClicker = new ButtonClicker(mock);
The answer is no. A mock is only a trivial interface implementation. (I mean interface in the API sense, not the specific Java keyword sense.) So it doesn't know about any implementation details like which class actually implements the functionality (there is no functionality, essentially).
You can create a 'spy' on a real object that will let you mock only some methods and not others, but that also will not let you mock just the super method of a class because the method(s) you choose to mock are typically chosen by the signature, which is the same for both the sub class and the super class.

Make Object available to all methods c++

Can anyone help me with this? basically I have a test class, wihtin this test class I have a number of methods which all use the same type of setup. Let me show you by example:
class Test:public CxxTest::TestSuite
{
public:
void Test1(){/*...*/}
void Test2(){/*...*/}
};
Each test method requires the same type of setup:
Class c_objectName = AnotherClass::method("c_name","c_name","c_name");
class c_newObjectName = AnotherCLass::create(c_objectName);
I am currently setting this in every single method, because each of the above i started with "c_..." needs to be different.
I tried to make a "global method" that would take in a string to rename these each time, but then I cant seems to access them from the method calls. I tried the following:
class Test:public CxxTest::TestSuite
{
public:
void method()
{ Class c_objectName = AnotherClass::method("c_name","c_name","c_name"); <--- cant access these
Class c_newObjectName = AnotherClass::create(c_objectName);
}
void Test1(){/*...*/}
void Test2(){/*...*/}
};
Is there a way to put this in a "global method" of some sort so that I can access these from the methods?
Im really bad at explaining things so sorry and thanks in advance
I can't make heads and tails of the question, but it looks like something like this would help:
struct TestFixture
{
Class c_objectName;
Class c_newObjectName;
};
TestFixture makeFixture()
{
TestFixture fixture;
fixture.c_objectName = new Class("c_name","c_name","c_name");
fixture.c_newObjectName = create(c_objectName);
return fixture;
}
(assuming your Class (classes?) are copyable. If not, return a pointer to a new instance of TestFixture or something like scoped_ptr
Then you could use it in your test methods:
void Test1()
{
TestFixture fixture = makeFixture();
// use fixture.c_objectName etc.
If you don't mind sharing the data, you could just make them fields of class Test.
Edit Oh, I just realized you are using CxxTest, which probably has a better way of creating fixtures/setup/teardown for unit tests. However, the above approach should work in any framework.