I have a class that performs some sort of (potentially redundant) validation logic on some number of arguments in the functions it contains. To demonstrate, I have the following Controller and ValidationHelper classes:
class ValidationHelper {
void validateA(int a, String b) { /*...*/ }
void validateB(int c, double d, String e) { /*...*/ }
void validateC(int f) { /*...*/ }
}
class Controller {
private ValidationHelper helper;
void foo(int a, String b, int f) {
this.helper.validateA(a, b);
this.helper.validateC(f);
// .. Rest of foo
}
void bar(int a, String b, int c, double d, String e) {
this.helper.validateA(a, b);
this.helper.validateB(c, d, e);
// .. Rest of bar
}
}
I'm wondering if there is a way to improve this validation architecture so any addition in validation logic wouldn't be as intrusive as the current implementation, and have validation become much cleaner? If this isn't achievable, would you have any suggestions if all the functions had the exact same validation statements? (e.g. both foo() and bar() containing ONLY this.helper.validateA(a,b)):
class Controller {
void foo(int a, String b, int f) {
this.helper.validateA(a, b);
// .. Rest of foo
}
void bar(int a, String b, int c, double d, String e) {
this.helper.validateA(a, b);
// .. Rest of bar
}
}
ValidationHelper is a code smell. You should be skeptical of any class ending in -ER.
I would implement this using validating decorators. Your example is a bit vague with all of the random meaningless variables, so let me invent my own.
interface CoffeeMachine
{
Coffee brew(Volume water, Volume milk);
}
class DarkRoastCoffeeMachine implements CoffeeMachine
{
public Coffee brew(Volume water, Volume milk) {
return new Coffee(Roast.DARK, water, milk);
}
}
But what if we want to enforce some constraints? Let's say there must be at least some quantity of water - we can't make coffee without water.
class WaterEnforcingCoffeeMachine implements CoffeeMachine
{
private CoffeeMachine delegate;
public WaterEnforcingCoffeeMachine(CoffeeMachine delegate) {
this.delegate = delegate;
}
public Coffee brew(Volume water, Volume milk) {
if (water.millilitres() < 50) {
throw new IllegalArgumentException("Must use more than 50ml of water");
}
return delegate.brew(water, milk);
}
}
You can then compose these like so:
CoffeeMachine coffeeMachine = new WaterEnforcingCoffeeMachine(
new DarkRoastCoffeeMachine()
);
Need additional validation? Add another decorator.
Related
public class A extends Q implements T {
public class B extends Z {
public void D(int A, int B) {
}
}
private Z z;
public A() {
// other stuff
z = new B(/** params **/);
// more stuff
}
void C () {
((B)z).D(2,3);
}
}
The code is structured like that (can't give the full snippet due to legal reasons) When I try to call D, I get symbol not found error from java compiler. Z, Q, and T are defined in different files and they do compile without error.
Okay, if you have a class vehicle(Z) and a class truck(B) which is also a vehicle but can attachCargo(D). Then if we know we have any vehicle(z) and we just assume its a truck ( (B z) ), we cannot know for sure if it actually can attachCargo since we just assumed it were a truck(B). What you could do is create a constructor that takes in a vehicle(Z) and constructs a truck(B) from the information given. This new truck can be treated like a vehicle since it is one, but as we know it is a truck, we can also treat it like a truck:
class AClass extends Q implements T
{
class B extends Z
{
boolean CargoAttached;
public B()
{
}
public B(Z z)
{
CargoAttached = false;
}
public void D(int A, int B)
{
}
}
private Z z = new Z();
void C()
{
z = (new B(z));
((B) z).D(1, 2);
}
}
Which works perfectly fine
I am trying to re-build an OOP approach to mobile verification at the developers discretion. The concept I come up with is to allow for interfaces to manipulate the class. If the class implements the interface, then the verify method will be executed.
The problem I am facing, because I am only used to programming in less strongly-typed languages (PHP) is how to get a protected variable from a class extending the current class.
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
This line of code is now giving me an error
_mobileNumber cannot be resolved or is not a field
Here is my full code and here is an example I wrote of the same concept in PHP which I am trying to implement in Java.
import java.util.ArrayList;
interface Verification
{
public void initVerification();
}
class AreaCode
{
private int _code;
private String _country;
public AreaCode(int code, String country)
{
this._code = code;
this._country = country;
}
public int getAreaCode() { return this._code; }
public String getAreaCountry() { return this._country; }
}
class VerificationHandler
{
private ArrayList<AreaCode> _areaCodes = new ArrayList<AreaCode>() {{
this.add(new AreaCode(44, "UNITED KINGDOM"));
this.add(new AreaCode(91, "INDIA"));
}};
public void initVerification()
{
if(this instanceof Verification) {
this.verify();
}
}
protected void verify()
{
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
}
}
class Main extends VerificationHandler implements Verification {
protected String _mobileNumber = "+447435217761";
}
public class Hack1337 { public static void main(String[] args) { new Main(); } }
How can I retrieve a variable in a class extending another, ie:
class A { public String getB() { return this.b; } }
class B extends A { protected String b = 'A should get this'; }
B b = new B().getB();
Only instances of class B, or sub-classes of B can access the b instance variable directly (unless you cast A to B within the body of the A class, which is bad practice).
You can give class A read-only access to that value by overriding getB():
class B extends A
{
protected String b = 'A should get this';
#Override
public String getB() {
return this.b;
}
}
and you may also want to make the getB() method abstract in class A (which means making class A abstract):
abstract class A
{
public abstract String getB();
}
This would only make sense if different sub-classes of A are expected to return different things in getB(). Otherwise, you may as well move the b variable to the base class A.
I have the sama java object TestData in to packages (A & B). I have made a function that processes the object for a standard business functionality.
CommonFunc.java:
import A.TestData ;
class CommonFunc
{
/// .....
public static TestData processTestData(Date d1, String s1){
TestData testData = new TestData ();
/// set some testData porperties based on d1 and s1
/// e.g : testData.setInitialDate(d1);
return testData ;
}
}
The problem here is that the compiler has to load the object from one of the packages lets say package (A), so when I expect the data to be returned to a local variable from package (B) I get incompatible type error :
File using B TestData and needs to call the function processTestData:
import B.TestData;
// ...
TestData obj = CommonFunc.processTestData(new Date(), "test");
// ...
Is there a way to overcome this problem keeping a common function for both?
Is there a way to overcome this problem keeping a common function for both?
No and yes. On the general case, you cannot.
But you can, IFF you can make the two classes adopt the same interface, with the common methods declared in the same interface. See below, with apologies for the change in the class names:
interface C {
public Date getA();
public void setA(Date a);
}
interface C_Factory <X extends C> {
X createInstance();
}
class C1 implements C {
Date a;
int b;
public C1() {
super();
}
public Date getA() { return a; }
public void setA(Date a) { this.a = a; }
public int getB() { return b; }
public void setB(int b) { this.b = b; }
}
class C2 implements C {
Date a;
float b;
public C2() {
super();
}
public Date getA() { return a; }
public void setA(Date a) { this.a = a; }
public float getB() { return b; }
public void setB(float b) { this.b = b; }
}
public class CommonFunc {
// You need this extra param to create instances----
// V
static <X extends C> X doSomething(Date d, Class<X> clazz)
throws InstantiationException, IllegalAccessException
// You'll have to accept those exceptions as well
{
// the next statement uses clazz as a factory for new X instances
// As such, you can abstract the method further and use
// a custom Factory class instead.
X toret=clazz.newInstance();
toret.setA(d);
// something else
return toret;
}
// A custom factory variant of the above
static <X extends C> X doSomething(Date d, C_Factory<X> factory)
{
X toret=factory.createInstance();
toret.setA(d);
// something else
return toret;
}
static public void main(String[] args) {
try {
C1 c1=doSomething(new Date(), C1.class);
C2 c2=doSomething(new Date(), C2.class);
} catch (InstantiationException | IllegalAccessException e) {
// Should not happen
e.printStackTrace();
}
}
}
I do not see how it is possible in the above example you have posted, The best way out is to make the TestData an interface and have implementations in 2 packages. Then, to decide whether to return A TestDataImpl or B TestDataImpl, take another parameter in the processData, for simplicity, let us say a boolean. Based on true or false instantiate A TestDataImpl or B TestDataImpl and return the same. Where the return type of processData is the interface type
This is probably would be the most straightforward way of reusing the processData method.
Problem Description:
I want to be able to pass around a list of methods to other classes where the methods have been defined in only one class. If the methods, some of which have input parameters and non-void return types, are defined in one class, I want to be able to pass a list of some of them, with possible duplicates, as a parameter to some other class's constructor.
Code Description:
The code below is a crude example and can be ignored if it detracts from the main goal. Another example, in addition to the one below, would be a case where the methods are int Add(int n1, int n2), int Subtract(int n1, int n2), Multiply, etc.. and the interface has a method called int MathOperation(int n1, int n2).
Attempt to solve the problem:
The adapter pattern seems to have the functionality I'm looking for but I have only seen examples where the methods in the interface have no input or output parameters. An example implementation I wrote just for this question is posted below.
Problem Analogy:
You have a random picture generator web service. There are 30 mutations that can be applied to an image. The client connects and clicks a "generate" button and a random list of some of those functions are passed to some other class within the web service which then proceeds to run those functions with it's own data while also collecting and possibly re-using the return values to generate some mutated cat image. It can't just explicitly call the methods in the other class because that process needs to be done randomly at run-time. That is why I lean towards the idea of generating a random list of methods which are executed in-order when the 'generate' button is clicked.
I hope I have been clear.
public class SomeClass {
...
public double UseWrench(double torque, boolean clockwise) { ... }
public double UsePliers(double torque, boolean clockwise) { ... }
public double UseScrewDriver(double torque, boolean clockwise) { ... }
public boolean UseWireCutters(double torque) { ... }
interface IToolActions {
double TurnFastener(double torque, boolean clockwise);
boolean CutWire(double torque);
}
private IToolActions[] toolActions = new IToolActions[] {
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseWrench(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UsePliers(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseScrewDriver(double torque, boolean clockwise); } },
new IToolActions() { public boolean CutWire(double torque) { boolean UseWireCutters(double torque); } },
};
}
public class Worker<T> {
public List<? extends IToolActions> toolActions;
public Worker(List<? extends IToolActions> initialToolSet){
toolActions = initialToolActions;
}
}
While #alainlompo has the general idea, Java 8 simplifies this greatly by using something such as BiConsumer (for doubles) or even just a Consumer for the class object. In fact, you can go really crazy, and have a method accept varargs lambdas:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
}
public class Worker {
#SafeVarargs
public Worker(SomeClass example, Consumer<? extends SomeClass>... operations) {
for (Consumer bc : operations) {
bc.accept(example);
}
}
}
Then, this is easily simplified:
SomeClass c = new SomeClass();
new Worker(c, SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
While it seems a little awkward applying it like that (due to it being an Adapter pattern), you can easily see how this could apply to a class body:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
#SafeVarargs
public void operate(Consumer<? extends SomeClass>... operations) {
for (Consumer<? extends SomeClass> bc : operations) {
bc.accept(example);
}
}
}
//Elsewheres
SomeClass c = new SomeClass();
c.operate(SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
Of course, you don't need varargs, it will work just as well simply passing a Collection
But wait there's more!!!
If you wanted a result, you can even use a self-returning method via a Function, e.g.:
public class SomeClass {
public double chanceOfSuccess(Function<? super SomeClass, ? extends Double> modifier) {
double back = /* some pre-determined result */;
return modifier.apply(back); //apply our external modifier
}
}
//With our old 'c'
double odds = c.chanceOfSuccess(d -> d * 2); //twice as likely!
There's so much more flexibility provided from the Function API in java 8, making complex problems like this incredibly simplified to write.
#John here is how I have approached a solution to your problem.
I used the case of MathOperations to make it simpler. I think first that I would be better to have the interface outside of SomeClass like:
public interface MathOperable {
public int mathOperation(int n1, int n2);
}
I created two examples of classes implementing this interface and one anonymous implementation inside SomeClass (I did an Add, Multiply and an anonymous "Substract")
public class Add implements MathOperable {
public int mathOperation(int n1, int n2) {
return n1 + n2;
}
public String toString() {
return "<addition>";
}
}
The overriding of toString() is simply for the purpose of giving more readability to the examples that I will show at the end of my post.
public class Multiply implements MathOperable {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1 * n2;
}
public String toString() {
return "<multiplication>";
}
}
Here is my SomeClass class, it contans a getRandomListOfOperations, where I simulate what happens when the click on the button is done
public class SomeClass {
private static MathOperable addition = new Add();
private static MathOperable multiplication = new Multiply();
// Anonymous substraction
private static MathOperable substraction = new MathOperable() {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1-n2;
}
public String toString() {
return "<substraction>";
}
};
public List<MathOperable> getRandomListOfOperations() {
// We put the methods in an array so that we can pick them up later randomly
MathOperable[] methods = new MathOperable[] {addition, multiplication, substraction};
Random r = new Random();
// Since duplication is possible whe randomly generate the number of methods to send
// among three so if numberOfMethods > 3 we are sure there will be duplicates
int numberOfMethods = r.nextInt(10);
List<MathOperable> methodsList = new ArrayList<MathOperable>();
// We pick randomly the methods with duplicates
for (int i = 0; i < numberOfMethods; i++) {
methodsList.add(methods[r.nextInt(3)]);
}
return methodsList;
}
public void contactSomeOtherClass() {
new SomeOtherClass(getRandomListOfOperations());
}
}
Now here is my SomeOtherClass (which may correspond to your Worker class)
public class SomeOtherClass<T extends MathOperable> {
Random r = new Random();
List<T> operations;
public SomeOtherClass(List<T> operations) {
this.operations = operations;
runIt();
}
public void runIt() {
if (null == operations) {
return;
}
// Let's imagine for example that the new result is taken as operand1 for the next operation
int result = 0;
// Here are examples of the web service own datas
int n10 = r.nextInt(100);
int n20 = r.nextInt(100);
for (int i = 0; i < operations.size(); i++) {
if (i == 0) {
result = operations.get(i).mathOperation(n10, n20);
System.out.println("Result for operation N " + i + " = " + result);
} else {
// Now let's imagine another data from the web service operated with the previous result
int n2 = r.nextInt(100);
result = operations.get(i).mathOperation(result, n2);
System.out.println("Current result for operation N " + i + " which is " + operations.get(i) +" = " + result);
}
}
}
}
I have a simple test class that contains a main to connect the two classes
public class SomeTestClass {
public static void main(String[] args) {
SomeClass classe = new SomeClass();
classe.contactSomeOtherClass();
}
}
Now a few examples of executions:
And another illustration!
I hope this could be helpful!
Okay, I'm going to be "that guy"... the one who understands the question but asks anyway to restate the problem because I think you are on the wrong path. So, bear with me: if you like what you see, great; if not, I understand.
Basically, you have a different intent/motivation/purpose than what "adapter" is suited for. The command pattern is a better fit.
But first, more generally, one of the goals of designing "elements of reusable software" (from the title of the original GOF design patterns book) is that you don't want to modify code when you add functionality; rather, you want to add code without touching existing functionality. So, when you have:
public class Toolbox {
public void hammer() { ... }
}
and you want to add a screwdriver to your toolbox, this is bad:
public class Toolbox {
public void hammer() { ... }
public void screwdriver() { ... }
}
Rather, ideally, all existing code would remain unchanged and you would just add a new Screwdriver compilation unit (i.e., add a new file), and a unit test, and then test the existing code for regression (which should be unlikely, since none of the existing code changed). For example:
public class Toolbox {
public void useTool(Tool t) { t.execute(); ...etc... }
}
public interface Tool { // this is the Command interface
public void execute() // no args (see ctors)
}
public Hammer implements Tool {
public Hammer(Nail nail, Thing t) // args!
public void execute() { nail.into(t); ... }
}
public Screwdriver implements Tool {
public Screwdriver(Screw s, Thing t)
public void execute() { screw.into(t); ... }
}
Hopefully it should become clear how to extend this to your example. The Worker becomes straight-foward list of Tools (or, for clarity, instead of "Tool" , just call it a "Command").
public class Worker {
public List<Command> actionList;
....
public void work() {
for(...) {
action.execute();
}
}
}
This pattern also allows for easy "undo" functionality and "retry", as well as memoization (caching results so they don't have to be re-run).
In my project I need to create objects for each kind of Java Math Operator like "Add", "Substraction", "Multiplication", etc. And these operators should be singletons.
So here is what I am going to do. I define the Math Operator as an interface and I put those implementations inside it as I don't want to define singleton classes for each operator.
public interface MathOperator {
double operate(double a, double b);
MathOperator ADD = new MathOperator(){
#Override
public double operate(double a, double b) {
return a + b;
}
};
MathOperator SUBSTRACT = new MathOperator(){
#Override
public double operate(double a, double b) {
return a - b;
}
};
}
I don't see much of such usage when I Google this. So I wonder if this is a good practice and if there are better and more graceful approaches?
I would do smt like
1) Define interface
interface MathOperator {
double operate(double a, double b);
}
2) Than have some common implementation in enum (less code)
enum MathOperators implements MathOperator {
ADD {
#Override
public double operate(double a, double b) {
return a + b;
}
},
SUBTRACT {
#Override
public double operate(double a, double b) {
return a - b;
}
}
}
3) Or public static members (more clean solution).
class MathOperators {
public static MathOperator ADD = new MathOperator() {
#Override
public double operate(double a, double b) {
return a + b;
}
};
public static MathOperator SUBTRACT = new MathOperator() {
#Override
public double operate(double a, double b) {
return a - b;
}
};
}
can create new MathOperator without changing MathOperators
have nice API for common operations
shouldn't write singletons
have nice clean interface
One idiom that I've seen used in precisely these circumstances is the use of enum:
public enum MathOperator {
ADD {
#Override
public double operate(double a, double b) {
return a + b;
}
},
SUBTRACT {
#Override
public double operate(double a, double b) {
return a - b;
}
};
public abstract double operate(double a, double b);
}
I use this pattern often, especially for specific implementations of generic interfaces. I find it works really well for me.
I like the way it puts the implementations where you can find them. I do it slightly differently - I make them static (it's a style thing, so the interface impls look more like class impls):
public interface MathOperator {
double operate(double a, double b);
public static MathOperator ADD = new MathOperator() {
#Override
public double operate(double a, double b) {
return a + b;
}
};
public static MathOperator SUBSTRACT = new MathOperator() {
#Override
public double operate(double a, double b) {
return a - b;
}
};
}
I don't see any problem with it. Take java.lang.String.CASE_INSENSITIVE_ORDER for instance. It is almost the same, except that
String is not an interface but a final class
The Comparator is not declared using an anonymous class, but using a static inner class, which is essentially the same
Personally, I don't like putting implementations within interfaces. I would either:
make MathOperator an enum
keep the interface but have a factory or a static class (say MathOperators) with the implementations
Why don't you define each implementation in its own class/file? This would make it clearer and would leave the interface clean.