Functional programming in OOP language Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Functional programming in OOP language without wasting too much if your time.

The question is published on by Tutorial Guruji team.

immutable objects are OK, but, are OK non-final local references?

In other words, next code snippet can be represented as written in functional style?

Employee e = new Employee("Lex", 24, 250);
e = Employee.setName(e, "Vasili");
e = Employee.setAge(e, 12);
e = Employee.setSalary(e, 2500);
Employee.log(e);

P.S. here all Employee methods are static, setters are factory methods that returns new instances.

Answer

Don’t know anything about Haskell, but I believe you are trying to achieve something like this:

Employee e = new Employee("Lex")
    .setAge(25)
    .setSalary(2500)
    .setGender(Gender.Male);

This is just a result of chaining functions in the following way

public Employee setParam(param){
   this.param = param;
   return this;
}

but the methods are not static, they belong to the instance.

Also there would be no need to pass the instance as parameter.


Also:

  • this isn’t a required keyword; in my example above, the two parameters have the same name, so without this the code would basically re-assign param’s value to itself. If the parameters had a different name this is not required. Yet returning this is necessary as it represent a reference to the current instance.

E.g:

public Employee setParam(String param) {
    parameter = param; // parameter is a field in class Employee
    return this; // this "this", is still necessary
}
  • final variables

May limit you on what you are trying to achieve with your style

final Employee e = Employee.setName(e, "Name"); // invalid, e is unkown

// ----------------

final Employee e;
e = Employee.setName(e, "Name"); // invalid, e may not be initialized

// ----------------

final Employee e;
e = Employee.setName("Name"); // valid

// ----------------

final Employee e = null;
e = Employee.setName(e, "Name"); // invalid. e was already initalized to null

// ----------------

final Employee e = Employee.setName("Name"); // valid
e = Employee.setName("Name2"); // invalid, final variable already initialized
We are here to answer your question about Functional programming in OOP language - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji