Where to put reusable pure functions in java? - spring

I can't decide where to store reusable pure functions in Java. Example :
class ServiceA(){
private C pureFunction1(A a, B b) {
//code to produce C c;
return c;
}
}
class ServiceB(){
private C pureFunction1(A a, B b) {
//code to produce C c;
return c;
}
}
According to DRY i should extract this pure function somewhere.
I've considered to put it into following places :
Static helper class (smell + against SOLID's dependency inversion principle)
Spring bean (isn't it an overkill for just a pure function)
Super class (does not feel like a right thing for two independent services)
Interface with default method (Interfaces have different purpose)
Where would you recommend to put code for pureFunction1?

My preference would be for static helper class if there is no business logic involved in the method. For example, computing dates which don't have any business logic would be a right candidate for static helper class.
Spring bean can be an option if there is some proper business logic involved in the method
Having superclass may not be the right idea. Reasons here

I prefer static helper class. With java 8 you can declare static method in interface (and implement it in your services).
No difference between spring bean and static helper class for your case
Super class - not good idea without multiple inheritance feature.

Related

Reference to an instance method of a particular object breaks the type-safety in Java?

Does the notion of a reference to an instance method of a particular object break the type-safety in Java?
According to
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
you can have a custom class ComparisonProvider that DOES not implement the Comparator interface, and still use an instance of this class as the second argument of the method
Arrays.sort(T[] a, Comparator c)
Sure, the implementation of your ComparisonProvider MUST have a method whose signature exactly matches the Comparator.compare() method, but that is still not an instance of Comparator, isn't it?
In essence, Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not.
This means, that we are loosing Type-safety in Java, do we?
lambda expressions and method reference don't have a predefined type, they are poly expressions, as seen here. That means that their type is derived from the context in which they are used.
In your example these both would be legal for example:
BiFunction<Person, Person, Integer> biFun = myComparisonProvider::compareByName;
Comparator<Person> comp = myComparisonProvider::compareByName;
But at the same time you can't do:
Arrays.sort(pers, biFun);
When you actually try to sort the array like this:
Arrays.sort(pers, myComparisonProvider::compareByName);
At the bytecode level that is a Comparator:
// InvokeDynamic #0:compare:(LTest$ComparisonProvider;)Ljava/util/Comparator;
Also notice that this would print true:
Comparator<Person> comp = myComparisonProvider::compareByName;
System.out.println(comp instanceof Comparator); // true
You can enable a flag : -Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here
and look at what that method reference is transformed into:
final class Test$$Lambda$1 implements java.util.Comparator
and inside it there's the compare method implementation(I've simplified it and removed some of it's code to make it a little more obvious):
public int compare(java.lang.Object, java.lang.Object);
Code:
4: aload_1
5: checkcast // class Test3$Person
8: aload_2
9: checkcast // class Test$Person
12: invokevirtual Test$ComparisonProvider.compareByName:(Test$Person;Test$Person;)I
Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not
Not exactly, it allows you to use a single method of some instance of a class as if it were implementing some functional interface.
And it doesn't add any functionality that didn't exist in Java 7 - it just gives you a short cut to writing that functionality.
For example, instead of:
Arrays.sort(someArray, someInstance::someMethod);
In Java 7 you could use anonymous class instance to write:
Arrays.sort(someArray, new Comparator<SomeType> () {
public int compare (SomeType one, SomeTypeTwo) {
return someInstance.someMethod(one,two);
}
});
As long as the instance method is accessible (i.e. public), you can use it as you see fit.
Comparator is a functional interface, which means that when requested you can pass an instance of a class implementing it, use a lambda expression that conforms to the type of single abstract method declared in it or use a method reference that also conforms to.
Java 8 Functional interface makes the difference. This tries to catch the concept of function. Afterall what is important in Comparator is not the type itself but the method (and its type) that should be provided at runtime. In pre Java 8 you need to provide a function object, while in Java 8 you can simply provide the function (just what is needed).
So for the type system everything is correct, provided that the lambdas or references you use are of the type of the method of the functional interface.

Enums support for inheritance

I frequently come across a situation where we create a class that acts on some enumeration, but later we derive and we want to add more values to the enumeration without changing the base class.
I see this question from 2009:
Base enum class inheritance
However, I know there were a number of changes to enum in C++11, 14, 17.
Do any of those changes allow for extension of enums from base class to derived?
class Base
{
enum State {STATE_1, STATE_2, STATE_3};
};
class Derived : public Base
{
enum State {STATE_4};
};
...where we want derived to have an enumeration describing the states it can be in, which are: STATE_1, STATE_2, STATE_3, and STATE_4. We don't really want to change the enumeration in the base class, because other derived classes might not have the ability to be in STATE_4. We don't really want to create a new enumeration either, because we already have one for State in the Base.
Do we still use static const values instead in order to accomplish this 8 years later?
class Base
{
static int STATE_1= 0;
static int STATE_2= 1;
static int STATE_3= 2;
};
class Derived : public Base
{
static int STATE_4= 3;
};
No, C++ does not allow this sort of thing. Base::Color is a completely separate type from Derived::Color, with zero connection to them. This is no different from any other nested types; nested types defined in a base class are not connected to nested types defined in a derived class.
Nor can enumerations be inherited from one another.
This sort of things tends to go against good OOP practices anyway. After all, if a derived class introduces a new enumerator, how would the base class handle it? How would different derived class instances handle it?
If Base defines an operation over an enumeration, then Base defines the totality of the enumeration it operates on, and every class derived from it ought to be able to handle all of those options. Otherwise, something is very wrong with your virtual interface.
Why not just using namespaces to group enums?
namespace my_codes {
enum class color { red, green, blue } ;
enum class origin { server, client } ;
} // my_codes
Usage might be
struct my_signal {
my_codes::color flag ;
my_codes::origin source ;
} ;
But beware: "overkill is my biggest fear..." :) I would not enjoy some deep hierarchy of namespaces with enums in them and a such ...

Testing for sameness

BOOST_AUTO_TEST_CASE(testing_sameness) {
Dependency dep;
T foo(dep);
BOOST_CHECK_EQUAL(dep, foo.dep());
}
In a test like this, how to write the last line in order to test that the dep() method really returns the same object as injected over the constructor?
The underlying class should not implement additional methods like overloading the == operator.
Ideally, I would like to simply compare the addresses of both objects. The method is declared as:
Dependency dep() : const;
Writing this test is more for educational purposes, I wouldn't test getters like that in practice.

Why should functions used for creating a Predicate be defined as static?

While reading up on the new features introduced in Java 8, I came across the concept of Predicates. I noticed that most of the examples provided on the internet and in books use static functions to create predicates.
Consider the following Apple class for example :
public class Apple {
private String color;
private int weight;
private static final int SMALL_APPLE_MAX_WEIGHT = 150;
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public static boolean isGreenApple(Apple apple) {
return null!=apple && null!=apple.getColor() && "green".equals(apple.getColor());
}
public boolean isBigApple() {
return this.getWeight() > SMALL_APPLE_MAX_WEIGHT;
}
}
I can now create a new predicate as follows :
Predicate<Apple> isGreenApple = Apple::isGreenApple;
Predicate<Apple> isBigApple = Apple::isBigApple;
As shown above, I can create a predicate using both a static as well as an instance method. Which approach is the preferred approach then and why?
For a method reference, there is no difference between an instance method A.foo() and a static method foo(A), in fact, the compiler will reject a method reference as ambiguous if both exist.
So the decision whether to use an instance method or a static method does not depend on the question whether you want to create a function via method reference for it.
Rather, you have to apply the same considerations us usual. Should the method be overridable, it has to be an instance method, otherwise, if it represents a fixed algorithm, you may consider a static method, but of course, a final method would do as well.
static methods are obviously unavoidable when you are not the maintainer of the class whose instance you want to process, in other words, when the containing class has to be different than the class of the instance. But even if the class is the same but you feel that it could be placed in another (utility) class as well, declaring it as static might be the better choice.
This holds especially when there are more than one parameter and the first one isn’t special to the operation, e.g. max(Foo,Foo) should be a static method rather than an instance method max(Foo) on Foo.
But in the end there are different programming styles out there and the answer is that method references do not mandate a particular programming style.
Regarding why there are so many examples using static methods; well I don’t know enough examples to decide whether your observation is right or just a subjective view. But maybe some tutorial writers are themselves not aware about the possibility to refer to an instance method as a function taking the method receiver as first argument.
I think, there are examples, like
Predicate<String> empty=String::isEmpty;
Predicate<CharSequence> isHello="hello"::contentEquals;
which are worth to be shown in tutorials to emphasize that you are not required to create methods specially intended to be used as method references, but that in fact there are a lot of already existing methods, static and non-static, to be directly usable with method references.
What I am more interested in knowing is why are all examples on predicates shown using static methods?
The reference appears on the Class as no additional argument is required.
Any specific reason for not using instance methods?
For non-static methods that would make sense. In the case of
Predicate<Apple> isBigApple = Apple::isBigApple;
Predicate needs a argument so it takes this. An example of a non-method call would be something like
List<Apple> bigApples = new ArrayList<>();
apples.stream().filter(Apple::isBigApple).forEach(bigApple::add);

Cheat sheet for all design patterns implemented in Ruby?

I wonder if there are cheat cheets for all design patterns implemented in Ruby so that you don't have to reinvent the wheel.
Design patterns are useful for organizing massive amounts of code. since you don't need to write as much code to do things in ruby as you do in #{verbose_algol_derivitive_language}, they don't have the same degree of importance.
What you will see used all the time is strategy and builder implemented with blocks (an example of builder would be form_for blocks in rails views, an example of strategy would be File.open) I can't really think of the last time I saw any others (gof patterns anyways)
EDIT: responding to
You mean with ruby we don't have to
think about design patterns in most
cases? Another question, if I'm using
Rails, do I actually have to think
about design patterns? Cause I don't
know where to use them. They don't
seem to fit in any component of the
MVC. Are design patterns only for
people that are building massive
libraries/frameworks eg. Rails,
DataMapper, MongoID etc and not for
others that only using these
frameworks/libraries?
For the most part, rails makes a lot of your decisions for you, and will until your app hits a fairly high level of complexity. Even if you are using something like sinatra though (which doesn't decide anything for you), you still won't really need to reach for those GoF patterns the same way as you would in a language like (for example) java.
This is because the whole point of design patterns is bottled ways to keep things flexible and maintainable. If that is built into the language, often they aren't even needed.
For example, a strategy pattern implemented in java looks sort of like this
//StrategyExample test application
class StrategyExample {
public static void main(String[] args) {
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3,4);
}
}
// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {
int execute(int a, int b);
}
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyAdd's execute()");
return a + b; // Do an addition with a and b
}
}
class ConcreteStrategySubtract implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategySubtract's execute()");
return a - b; // Do a subtraction with a and b
}
}
class ConcreteStrategyMultiply implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyMultiply's execute()");
return a * b; // Do a multiplication with a and b
}
}
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
private Strategy strategy;
// Constructor
public Context(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
}
It is a lot of work, but what you end up with is worth it a lot of the time, and can be the difference between a big ball of mud, and something that has a chance in hell of being maintained. Now lets do it in ruby
class Context
def initialize(&strategy)
#strategy = strategy
end
def execute
#strategy.call
end
end
a = Context.new { puts 'Doing the task the normal way' }
a.execute #=> Doing the task the normal way
b = Context.new { puts 'Doing the task alternatively' }
b.execute #=> Doing the task alternatively
c = Context.new { puts 'Doing the task even more alternatively' }
c.execute #=> Doing the task even more alternatively
its hard to even call that a pattern, you are just using blocks! When the language covers the needs that the pattern addresses, effectively using the language will mean you don't really need the pattern in most circumstances. It also means you can elegantly address that kind of problem when it would be horrible overkill to do a java style strategy.
This document has nice examples of actual implementation of some of the design patterns from the GoF.
It may be a "cheatsheet", but I don't think is a silver-bullet reference for design patterns because they emerge once you have analyzed a problem, and the pattern fits the solution you're giving. Is not a recipe, but rather a good reference.
And, of course, is the great book Design patterns in Ruby

Resources