Code base is in Java. I need to read data from two different stores conditionally.
interface Reader<T> {
T read();
}
T foo(Reader<T> reader1, Reader<T> reader2) {
// read using reader1 or reader2 based on some
// conditions
}
ConcreType1 readFromDB1(some parameters) {
}
ConcreType2 readFromDB2(some other parameters) {
}
void someMethod() {
// some logic
foo(
() -> readFromDB1(params1), // 1
() -> readFromDB2(params2), // 2
);
}
If developer switch order above parameters 2, 1. code will compile and it will just do read from incorrect DB. it may fail at runtime if data is missing or format is different. I want it to fail at compile time.
I tried bunch of things - like creating two interfaces, but does not help. passing dummy parameter on one interface etc, either it did not work or code looked overly complex and hard to read. How do I prevent developer accidentally switch order of parameters? Seeking recommendations.
Code base is in Java. I need to read data from two different stores conditionally.
interface Reader<T> {
T read();
}
T foo(Reader<T> reader1, Reader<T> reader2) {
// read using reader1 or reader2 based on some
// conditions
}
ConcreType1 readFromDB1(some parameters) {
}
ConcreType2 readFromDB2(some other parameters) {
}
void someMethod() {
// some logic
foo(
() -> readFromDB1(params1), // 1
() -> readFromDB2(params2), // 2
);
}
If developer switch order above parameters 2, 1. code will compile and it will just do read from incorrect DB. it may fail at runtime if data is missing or format is different. I want it to fail at compile time.
I tried bunch of things - like creating two interfaces, but does not help. passing dummy parameter on one interface etc, either it did not work or code looked overly complex and hard to read. How do I prevent developer accidentally switch order of parameters? Seeking recommendations.
Share Improve this question asked Nov 19, 2024 at 16:42 AdamsAdams 91 bronze badge 6 | Show 1 more comment2 Answers
Reset to default 0I would probably wrap either set of parameters into a parameter object. You can commonly define them in an ancestor, but have readfromDB1 and readfromDB2 only accept either of two empty subclasses.
Something like this might work for you?...
T foo(Reader<T> reader1, Reader<T> reader2) {
Reader<T> readerA, Reader<T> readerB;
if( reader1.getKnownParameter() == knownParameterValue ) {
readerA = reader1;
readerB = reader2;
}
else {
readerA = reader2;
readerB = reader1;
}
....
}
foo
to be callable only with named parameters: see stackoverflow/a/37394267/13963086 – k314159 Commented Nov 19, 2024 at 17:01reader1
orreader2
already based on some conditions, why would the order of the parameters matter? Is it a matter of choosing one over the other (e.g. assigning some kind of "priority" to them)? – Rogue Commented Nov 19, 2024 at 17:03