Functional Programming in Java 8 - interface

As for as I have understood that functional Programming means to give a different behavor implementations interface. Would that be better than I had to create a new Class and implemented that interface in it?
I am not clear on this
interface worldGreeting {
String processName(String str);
}
public class ReadJson {
public static void main(String[] argv) throws Exception {
worldGreeting morningGreeting = (str) -> "Good Morning " + str + "!";
worldGreeting eveningGreeting = (str) -> "Good Evening " + str + "!";
System.out.println(morningGreeting.processName("Waseem"));
System.out.println(eveningGreeting.processName("Saeed"));
}
}
Second approach would be like this
class Moring implements worldGreeting{
#Override
public String processName(String str) {
return "Good Morning " + str + "!";
}
}
class Evening implements worldGreeting{
#Override
public String processName(String str) {
return "Good Evening " + str + "!";
}
}

The difference between single-abstract-method notation and anonymous interface implementations is immaterial, so in my code examples, I will prefer anonymous interface implementations.
Consider these two different ways to provide similar functionality:
Version 1: Type-level Inheritance
interface Greeter {
abstract String greet(String name);
}
class MorningGreeter implements Greeter {
#Override public String greet(String name) {
return "Good morning, " + name + "!";
}
}
class EveningGreeter implements Greeter {
#Override public String greet(String name) {
return "Good evening, " + name + "!";
}
}
Version 2: Anonymous Implementations
interface Greeter {
abstract String greet(String name);
static Greeter morningGreeter = new Greeter() {
#Override public String greet(String name) {
return "Good morning, " + name + "!";
}
};
static Greeter eveningGreeter = new Greeter() {
#Override public String greet(String name) {
return "Good evening, " + name + "!";
}
};
}
What are some of the differences? Version 1 adds three type-level abstractions, while Version 2 adds only one. Furthermore, Version 1 allows any number of MorningGreeters and EveningGreeters to be instantiated, whereas Version 2 is written so that there is exactly one morningGreeter and exactly one eveningGreeter.
I prefer Version 2 for a few reasons.
For one, there's no reason to ever make more than one instance of MorningGreeter, since any two instances will function indistinguishably from one another: the only difference will be their memory address. I try to only ever make classes for things that I will instantiate many times and with different properties.
Second, I personally don't think that MorningGreeter and EveningGreeter should be their own type-level abstractions, since they do not add any methods or fields to Greeter. I try to limit my type-level abstractions by the methods and fields they support, since the purpose of the type system is to prevent you from calling the wrong methods on objects that might not support it, and Greeter is the type-level abstraction for objects that have a single method with signature String greet(String name). I don't feel there is much value in creating two new type-level abstractions with the exact same methods.
Third, Version 2 presents a clear entry point for users of this (very simple) library. In Version 1, users either need to grep all the project files for "implements Greeter" or use IDE magic to jump to the implementing classes. In Version 2, users simply create a greeter with either of the two static convenience methods.
I hope this answers your question. I think it's a good question, more than just a matter of personal taste.

Related

Expected default behavior for Grails RESTful mapping to Nested Resources

I have my Grails Domain classes annotated with #Resource with the uri specifications in UrlMappings where I declare the resource nesting. But even though according to https://docs.grails.org/latest/guide/theWebLayer.html#restfulMappings it seems that just declaring this the right way, I should have the correct behavior that I wanted, which is that a URL pattern such as /nesting/1/nested will list the nested domain that belonged to the nesting domain with ID 1, the observed behavior is that it just lists out all nested domain objects.
So for that, my workaround is to have a controller implemented that overrides the listResources to filter the nested domain by the nesting domain. But what's weird to me is why I even have to do that at all. The documentation said it defaults to the index action but said index action seems to just behave as if it's the index() of nested (without taking nesting into account).
My domain entities are WeightSensor:
#Resource(formats = ['json', 'xml'])
class WeightSensor extends Sensor<WeightData>
{
Set<WeightData> data
static constraints = {
}
}
its superclass Sensor
#Resource(formats = ['json', 'xml'])
class Sensor<T extends SensorData>
{
Set<T> data
static hasMany = [data: SensorData]
String name
static constraints = {
name unique: true
}
}
and WeightData
class WeightData extends SensorData
{
Float weight
static constraints = {
weight nullable: false
}
}
and its superclass SensorData
class SensorData
{
#BindingFormat('yyyy-MM-dd HH:mm:ss.S') // 2019-07-11 22:00:28.909
Date timestamp
static belongsTo = [sensor: Sensor]
static constraints = {
timestamp nullable: false
}
}
In my UrlMappings I have the following:
"/sensor/weight"(resources: 'weightSensor') {
"/data"(resources: "weightData")
}
My WeightDataController extends from a SensorDataController:
class WeightDataController extends SensorDataController<WeightSensor, WeightData>
{
#SuppressWarnings("GroovyUnusedDeclaration")
static responseFormats = ['json', 'xml']
WeightDataController()
{
super(WeightData, WeightSensor, "weightSensorId")
}
}
And SensorDataController in turn extends RestfulController, and overrides the listAllResources method as below.
import grails.rest.RestfulController
class SensorDataController<S extends Sensor, T extends SensorData> extends RestfulController<T>
{
String idProperty
Class<S> sensorType
#SuppressWarnings("GroovyUnusedDeclaration")
static responseFormats = ['json', 'xml']
protected SensorDataController(Class<T> dataType, Class<S> sensorType, String idProperty)
{
super(dataType)
this.idProperty = idProperty
this.sensorType = sensorType
}
#Override
protected List<T> listAllResources(Map params)
{
Long sensorId = params.get(idProperty) as Long
if (sensorId)
{
resource.withCriteria() {
eq 'sensor.id', sensorId
maxResults params.max ?: 10
firstResult params.offset ?: 0
} as List<T>
}
else
{
super.listAllResources(params)
}
}
}
Note because in order for me to have my WeightDataController class be used, I needed to remove the #Resource on top of WeightData domain entity above, another nice little gem of wisdom I had to discover with trial and error.
I can probably blame this on the fact that the documentation for nested resources seems a bit open to interpretation. But when we see in the documentation a URL like GET books/${bookId}/authors, doesn't that look like it should return the list of Author objects that belongs to the Book instance IDed by bookId?
I know that I'm not alone as I did find this online of someone asking the same question I have - https://gist.github.com/mnellemann/7cfff1c721ef32f0be6c63574795f795 but no one answered them either. I also came across another SO post nested RESTful resources that was abandoned 5 years ago as well.
But 3 people having the same question and no one responding to our questions (I asked mine on the Grails Slack community) usefully because there is a work-around is not acceptable. At the risk of having my question taken down for a slew of different reasons, I question the usefulness of even having the grails nested resource URL mapping in the first place because I could have done everything manually myself without having to "declare" such a nesting in UrlMappings.
In closing, what I'm trying to find out is whether or not there's more "configuration" I need to do to get Grails nested Resources to behave in the way that I expected, which is how the documentation painted, correctly. Because just doing what was described doesn't get me that.

TypeScript static members vs namespace with class name

In TypeScript, I have been separating non-instance variables out of my classes and into a namespace with the same name as the class. For example:
class Person
{
age: number;
constructor(age: number)
{
this.age = age;
}
}
namespace Person
{
export let numberOfFingers: number = 10;
}
export default Person;
as opposed to this:
class Person
{
static numberOfFingers: number = 10;
age: number;
constructor(age: number)
{
this.age = age;
}
}
export default Person;
Is there any benefit to either of these methods?
As far as typechecking and code generation is concerned, both methods produce exactly the same results. I can offer two not very strong arguments in favor of static members:
it's the most obvious thing to do, it does not require knowledge of advanced parts of the language (declaration merging) to understand the code
if you ever need to have a function that creates and returns class definition (as described for example here, to simulate static generic member or to add a mixin), then namespaces will not work - you can't have namespace inside a function.

Automatically wrapping/converting JavaBeans into case classes

We are using Kryo to communicate between a Scala application and a Java application. Since the class definitions have to be used from Java (and we don't want to include the Scala library as a dependency in the Java applicaton) we are using JavaBeans to define the transfer objects.
However, using JavaBeans directly in Scala is a bit of a hassle. No pattern matching, having to use new, etc. What we're doing right now is defining extractors and apply methods in separate objects on the Scala side to make it nicer to work with these classes.
Since most of what we need is boilerplate, we are wondering if there would be a way of doing this automatically. For example, we have this JavaBean (there are about 20+ different message types):
public class HandshakeRequest extends Request {
private String gatewayId;
private String requestId;
private Date timestamp = new Date();
public HandshakeRequest(String gatewayId, String requestId) {
this.gatewayId = gatewayId;
this.requestId = requestId;
}
public String getGatewayId() { return gatewayId; }
public String getRequestId() { return requestId; }
public Date getTimestamp() { return timestamp; }
private HandshakeRequest() { /* For Kryo */ }
}
This is an example of the object we use to bridge to Scala:
object Handshake {
def unapply(msg: HandshakeRequest): Option[ (DateTime, String, String) ] = {
(
new DateTime(msg.getTimestamp.getTime),
msg.getRequestId,
msg.getGatewayId
).some
}
def apply(gatewayId: String, requestId: String) = new HandshakeRequest(gatewayId, requestId)
}
Since all of our object have the Timestamp, it is also part of the boilerplate. We'd like some way (perhaps a macro?) to automatically generate the unapply and apply methods (and ideally, the whole object itself).
Does anyone know of an easy way to accomplish this?
Since there were no answers, I came up with this: https://github.com/yetu/scala-beanutils.
I've started a project https://github.com/limansky/beanpuree which allows convertions from beans to case classes. I'm going to add some more features, like automatic type convertion between Java number classes and Scala classes.

How do you refactor a God class?

Does anyone know the best way to refactor a God-object?
Its not as simple as breaking it into a number of smaller classes, because there is a high method coupling. If I pull out one method, i usually end up pulling every other method out.
It's like Jenga. You will need patience and a steady hand, otherwise you have to recreate everything from scratch. Which is not bad, per se - sometimes one needs to throw away code.
Other advice:
Think before pulling out methods: on what data does this method operate? What responsibility does it have?
Try to maintain the interface of the god class at first and delegate calls to the new extracted classes. In the end the god class should be a pure facade without own logic. Then you can keep it for convenience or throw it away and start to use the new classes only
Unit Tests help: write tests for each method before extracting it to assure you don't break functionality
I assume "God Object" means a huge class (measured in lines of code).
The basic idea is to extract parts of its functions into other classes.
In order to find those you can look for
fields/parameters that often get used together. They might move together into a new class
methods (or parts of methods) that use only a small subset of the fields in the class, the might move into a class containing just those field.
primitive types (int, String, boolean). They often are really value objects before their coming out. Once they are value object, they often attract methods.
look at the usage of the god object. Are there different methods used by different clients? Those might go in separate interfaces. Those intefaces might in turn have separate implementations.
For actually doing these changes you should have some infrastructure and tools at your command:
Tests: Have a (possibly generated) exhaustive set of tests ready that you can run often. Be extremely careful with changes you do without tests. I do those, but limit them to things like extract method, which I can do completely with a single IDE action.
Version Control: You want to have a version control that allows you to commit every 2 minutes, without really slowing you down. SVN doesn't really work. Git does.
Mikado Method: The idea of the Mikado Method is to try a change. If it works great. If not take note what is breaking, add them as dependency to the change you started with. Rollback you changes. In the resulting graph, repeat the process with a node that has no dependencies yet. http://mikadomethod.wordpress.com/book/
According to the book "Object Oriented Metrics in Practice" by Lanza and Marinescu, The God Class design flaw refers to classes that tend to centralize the intelligence of the system. A God Class performs too much work on its own, delegating only minor details to a set of trivial classes and using the data from other classes.
The detection of a God Class is based on three main characteristics:
They heavily access data of other simpler classes, either directly or using accessor methods.
They are large and complex
They have a lot of non-communicative behavior i.e., there is a low
cohesion between the methods belonging to that class.
Refactoring a God Class is a complex task, as this disharmony is often a cumulative effect of other disharmonies that occur at the method level. Therefore, performing such a refactoring requires additional and more fine-grained information about the methods of the class, and sometimes even about its inheritance context. A first approach is to identify clusters of methods and attributes that are tied together and to extract these islands into separate classes.
Split Up God Class method from the book "Object-Oriented Reengineering Patterns" proposes to incrementally redistribute the responsibilities of the God Class either to its collaborating classes or to new classes that are pulled out of the God Class.
The book "Working Effectively with Legacy Code" presents some techniques such as Sprout Method, Sprout Class, Wrap Method to be able to test the legacy systems that can be used to support the refactoring of God Classes.
What I would do, is to sub-group methods in the God Class which utilize the same class properties as inputs or outputs. After that, I would split the class into sub-classes, where each sub-class will hold the methods in a sub-group, and the properties which these methods utilize.
That way, each new class will be smaller and more coherent (meaning that all their methods will work on similar class properties). Moreover, there will be less dependency for each new class we generated. After that, we can further reduce those dependencies since we can now understand the code better.
In general, I would say that there are a couple of different methods according to the situation at hand. As an example, let's say that you have a god class named "LoginManager" that validates user information, updates "OnlineUserService" so the user is added to the online user list, and returns login-specific data (such as Welcome screen and one time offers)to the client.
So your class will look something like this:
import java.util.ArrayList;
import java.util.List;
public class LoginManager {
public void handleLogin(String hashedUserId, String hashedUserPassword){
String userId = decryptHashedString(hashedUserId);
String userPassword = decryptHashedString(hashedUserPassword);
if(!validateUser(userId, userPassword)){ return; }
updateOnlineUserService(userId);
sendCustomizedLoginMessage(userId);
sendOneTimeOffer(userId);
}
public String decryptHashedString(String hashedString){
String userId = "";
//TODO Decrypt hashed string for 150 lines of code...
return userId;
}
public boolean validateUser(String userId, String userPassword){
//validate for 100 lines of code...
List<String> userIdList = getUserIdList();
if(!isUserIdValid(userId,userIdList)){return false;}
if(!isPasswordCorrect(userId,userPassword)){return false;}
return true;
}
private List<String> getUserIdList() {
List<String> userIdList = new ArrayList<>();
//TODO: Add implementation details
return userIdList;
}
private boolean isPasswordCorrect(String userId, String userPassword) {
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
private boolean isUserIdValid(String userId, List<String> userIdList) {
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
public void updateOnlineUserService(String userId){
//TODO updateOnlineUserService for 100 lines of code...
}
public void sendCustomizedLoginMessage(String userId){
//TODO sendCustomizedLoginMessage for 50 lines of code...
}
public void sendOneTimeOffer(String userId){
//TODO sendOneTimeOffer for 100 lines of code...
}}
Now we can see that this class will be huge and complex. It is not a God class by book definition yet, since class fields are commonly used among methods now. But for the sake of argument, we can treat it as a God class and start refactoring.
One of the solutions is to create separate small classes which are used as members in the main class. Another thing you could add, could be separating different behaviors in different interfaces and their respective classes. Hide implementation details in classes by making those methods "private". And use those interfaces in the main class to do its bidding.
So at the end, RefactoredLoginManager will look like this:
public class RefactoredLoginManager {
IDecryptHandler decryptHandler;
IValidateHandler validateHandler;
IOnlineUserServiceNotifier onlineUserServiceNotifier;
IClientDataSender clientDataSender;
public void handleLogin(String hashedUserId, String hashedUserPassword){
String userId = decryptHandler.decryptHashedString(hashedUserId);
String userPassword = decryptHandler.decryptHashedString(hashedUserPassword);
if(!validateHandler.validateUser(userId, userPassword)){ return; }
onlineUserServiceNotifier.updateOnlineUserService(userId);
clientDataSender.sendCustomizedLoginMessage(userId);
clientDataSender.sendOneTimeOffer(userId);
}
}
DecryptHandler:
public class DecryptHandler implements IDecryptHandler {
public String decryptHashedString(String hashedString){
String userId = "";
//TODO Decrypt hashed string for 150 lines of code...
return userId;
}
}
public interface IDecryptHandler {
String decryptHashedString(String hashedString);
}
ValidateHandler:
public class ValidateHandler implements IValidateHandler {
public boolean validateUser(String userId, String userPassword){
//validate for 100 lines of code...
List<String> userIdList = getUserIdList();
if(!isUserIdValid(userId,userIdList)){return false;}
if(!isPasswordCorrect(userId,userPassword)){return false;}
return true;
}
private List<String> getUserIdList() {
List<String> userIdList = new ArrayList<>();
//TODO: Add implementation details
return userIdList;
}
private boolean isPasswordCorrect(String userId, String userPassword)
{
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
private boolean isUserIdValid(String userId, List<String> userIdList)
{
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
}
Important thing to note here is that the interfaces () only has to include the methods used by other classes. So IValidateHandler looks as simple as this:
public interface IValidateHandler {
boolean validateUser(String userId, String userPassword);
}
OnlineUserServiceNotifier:
public class OnlineUserServiceNotifier implements
IOnlineUserServiceNotifier {
public void updateOnlineUserService(String userId){
//TODO updateOnlineUserService for 100 lines of code...
}
}
public interface IOnlineUserServiceNotifier {
void updateOnlineUserService(String userId);
}
ClientDataSender:
public class ClientDataSender implements IClientDataSender {
public void sendCustomizedLoginMessage(String userId){
//TODO sendCustomizedLoginMessage for 50 lines of code...
}
public void sendOneTimeOffer(String userId){
//TODO sendOneTimeOffer for 100 lines of code...
}
}
Since both methods are accessed in LoginHandler, interface has to include both methods:
public interface IClientDataSender {
void sendCustomizedLoginMessage(String userId);
void sendOneTimeOffer(String userId);
}
There are really two topics here:
Given a God class, how its members be rationally partitioned into subsets? The fundamental idea is to group elements by conceptual coherency (often indicated by frequent co-usage in client modules) and by forced dependencies. Obviously the details of this are specific to the system being refactored. The outcome is a desired partition (set of groups) of God class elements.
Given a desired partition, actually making the change. This is difficult if the code base has any scale. Doing this manually, you are almost forced to retain the God class while you modify its accessors to instead call new classes formed from the partitions. And of course you need to test, test, test because it is easy to make a mistake when manually making these changes. When all accesses to the God class are gone, you can finally remove it. This sounds great in theory but it takes a long time in practice if you are facing thousands of compilation units, and you have to get the team members to stop adding accesses to the God interface while you do this. One can, however, apply automated refactoring tools to implement this; with such a tool you specify the partition to the tool and it then modifies the code base in a reliable way. Our DMS can implement this Refactoring C++ God Classes and has been used to make such changes across systems with 3,000 compilation units.

AspectJ - Is it possible to catch execution of an advice?

I have a CachingAspect which performs some simple caching on properly annotated methods using an around advice. Now, what I want to do is to trace the caching and the around advice in particular.
So far I'm able to intercept method calls within the around advice but not the advice itself. Ultimately, I would want to get the signature of the method the around advice is advising. Is it possible?
Thanks in advance!
What do you mean by
[adviceexecution pointcut] is not working for me
For me it works just fine, like so:
public aspect MetaAspect {
before() : within(DummyAspect) && adviceexecution() {
System.out.println("MetaAspect: " + thisJoinPointStaticPart.getSignature());
for (Object arg : thisJoinPoint.getArgs())
System.out.println(" " + arg);
}
}
From that point, looking at the signatures printed, you should be able to further refine which advice to pick from DummyAspect if there is more than one and they have different signatures.
Update:
Okay, you have edited your question and stated that what you need to determine is not just adviceexecution() but also the intercepted method's signature. There is no 100% solution for that, but if you make sure your intercepted advice somehow refers to methods of thisJoinPointStaticPart, an instance of JoinPoint.StaticPart will be added to the advice's own signature and can be accessed from your meta aspect. Here is a complete code sample:
Driver application:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
Application application = new Application();
application.writeProperty("fullName", "John Doe");
application.readProperty("firstName");
application.doSomething(11);
}
public void writeProperty(String name, String value) {}
public String readProperty(String name) { return "foo"; }
public void doSomething(int number) {}
}
Caching aspect:
package de.scrum_master.aspect;
public aspect CachingAspect {
pointcut readMethods(String propertyName) :
execution(* *.read*(String)) && args(propertyName);
before(String propertyName) : readMethods(propertyName) {
System.out.println(
"[CachingAspect] Read method called for property '" + propertyName + "'"
);
}
Object around(String propertyName) : readMethods(propertyName) {
System.out.println(
"[CachingAspect] Caching property '" + propertyName +
"' in method " + thisJoinPointStaticPart.getSignature()
);
return proceed(propertyName);
}
}
As you can see, there are two advice in this aspect. The first one does not access any join point members, the second one does. I.e. we will be able to find out the second one's target signature only in our meta aspect.
Meta aspect:
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint.StaticPart;
public aspect AdviceInterceptor {
before() : within(CachingAspect) && adviceexecution() {
System.out.println("[AdviceInterceptor] Intercepting " + thisJoinPointStaticPart);
boolean foundSignature = false;
for (Object arg : thisJoinPoint.getArgs()) {
if (arg instanceof StaticPart) {
foundSignature = true;
StaticPart jpStaticPart = (StaticPart) arg;
System.out.println("[AdviceInterceptor] Target method = " + jpStaticPart.getSignature());
break;
}
}
if (!foundSignature)
System.out.println("[AdviceInterceptor] Target method cannot be determined from advice signature");
}
}
The meta advice iterates over its parameters in order to find a JoinPoint.StaticPart type parameter. If it finds one, it prints its target signature, otherwise it prints a failure note after the loop.
Sample output:
[AdviceInterceptor] Intercepting adviceexecution(void de.scrum_master.aspect.CachingAspect.before(String))
[AdviceInterceptor] Target method cannot be determined from advice signature
[CachingAspect] Read method called for property 'firstName'
[AdviceInterceptor] Intercepting adviceexecution(Object de.scrum_master.aspect.CachingAspect.around(String, AroundClosure, JoinPoint.StaticPart))
[AdviceInterceptor] Target method = String de.scrum_master.app.Application.readProperty(String)
[CachingAspect] Caching property 'firstName' in method String de.scrum_master.app.Application.readProperty(String)
See adviceexecution() pointcut.
You can use the thisJoinPoint.getSignature() inside the advice to get the method signature like this:
pointcut tolog1() : execution(* Activity+.*(..)) ;
before() : tolog1() {
String method = thisJoinPoint.getSignature().toShortString();
Log.d(ATAG, "=========== entering " + method+", parms="+Arrays.toString(thisJoinPoint.getArgs()));
}