Taking a more functional approach

functional approach examples
functional approach definition
functional approach psychology
functional programming
functional approach theory
functional approach in management
functional approach in marketing
functional approach in linguistics

I currently have this method (this is basically the real one, I just renamed variables and objects)

private void myMethod(
      final InputMessage inputMessage,
      final String id) {
    try {
        final Map<String, String> result =
              jdbcTemplate.query(
                  QUERY /* sql */, 
                  ROW_EXTRACTOR /* ResultSetExtractor */, 
                  id /* args */
              );

        if (result != null) {
            inputMessage.setParam1(result.get("param1"));
            inputMessage.setId(result.get("description")); // Insert description
            return;
        }
    } catch (final Exception e) {
        logger.error(...);
    }

    final String param1 = ...

    inputMessage.setParam1(param1);
    inputMessage.setId(id); // Insert the ID
}

I'd like to take a more functional approach for this. Just to try it out. I tought about different solutions but none of them is able to maintain the same logic.

How would you do that? Is it possible at all? I'm on Java 8, but you can throw in Java 11 classes and methods if necessary.

It isn't necessary to "convert" the entire method, I'm more interested in the part after the result extraction. However it is tightly coupled to the try - catch block.

I would prefer return a new InputMessage from method rather than pass it as a parameter. Assuming you have constructor for InputMessage with 2 params it will looks like:

return Optional.ofNullable(result)
    .map(map -> new InputMessage(map.get("param1"), map.get("description")))
    .orElse(new InputMessage("id", "param1"));

Make your code easier to read with Functional Programming, It seems that the functional approach is 60% slower. For more on applying functional programming techniques in React take a look at� Functional Medicine focuses on identifying and addressing the root cause of disease, not just symptom treatment. Functional medicine examines every factor involved including symptoms, genes, environment, and lifestyle factors to treat the causes of disease, not just the symptoms. A functional practitioner will: Focus on the root cause of symptoms to guide treatment; Take a holistic view of the entire body rather than a collection of separate systems

When querying database results you should use the Optional class in Java in order to avoid NullPointerExceptions. (https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html here is some further documentation).

For example, the following piece of code:

final Map<String, String> result =
          jdbcTemplate.query(
              QUERY /* sql */, 
              ROW_EXTRACTOR /* ResultSetExtractor */, 
              id /* args */
          );

Should not return null but much rather an Optional<Map<String,String>>, then you would be able to write the code in a functional manner like this:

result.ifPresent(res -> {
            inputMessage.setParam1(res.get("param1"));
            inputMessage.setId(res.get("description")); // Insert description
        });

This would also help you to take out the try-catch statement which is unnecessary here.

Also it is a good practice to seperate the data fetching functionality to the DAO layer and do operations on the fetched objects in the Service layer. Please find more documentation with regards to that here: https://www.baeldung.com/java-dao-pattern

Don't 'Object'-ify Me: An Introduction to Functional Programming in , A more functional way of doing the same thing is to define a function Taking a functional programming approach by using map(), instead of� The functional approach is one of the methods used in classification of activities that occur in the marketing processes by breaking down the processes into functions. A marketing function is defined as a major specialized activity performed in accomplishing the marketing process.

What about:

private void myMethod(final InputMessage inputMessage, final String id) { 
    final Map<String, String> result = null;
    try {
        result = jdbcTemplate.query(
             QUERY /* sql */, 
             ROW_EXTRACTOR /* ResultSetExtractor */, 
             id /* args */
        );
    } catch (final Exception e) {
        logger.error(...);
    }

    if (result != null)
        setParams(inputMessage, result.get("param1"), result.get("description")) 
    else
        setParams(inputMessage, param1, id);
}

public void setParams(final InputMessage inputMessage, String param1, String param2) {
    inputMessage.setParam1(param1);
    inputMessage.setId(param2);
}

Functional Approach, Among functional approaches, trustworthiness analysis, modeling, assessment, As in later periods, in Antiquity too, Jewish 'otherness' had been more or less tolerated in a Jews are known to have often taken the blame upon themselves. Functional medicine is a science-based approach Research supports the fact that every single component of the body is very connected and that it all works together as a whole. This is why functional medicine doctors, like Dr. Mark Hyman, support the idea that you need to focus on the organism as a whole, instead of the organs in the body. 4.

Mapping “future” values in JavaScript, a more functional approach , As you can see, this function will take a “mapping” function and will return a new Promise that will resolve the value resulted from applying the� And more importantly, the child was totally normal. Not every child has such a dramatic recovery but many improve, and some improve dramatically using the approach of functional or systems medicine. This is just the beginning. Read the full article on Autism and Functional Medicine.

Functional vs Object-Oriented Programming, How to determine where and when to use each approach code is more optimal : object-oriented or functional programming. Instead of starting from scratch, you can take your blueprint for making and work from there. Instead, we can take a more functional approach and create a new array instead of modifying the values in the original array, preventing subtle bugs and promoting reuse. const numbers = [1.4, 2.6,

Functional programming, In computer science, functional programming is a programming paradigm where programs are Higher-order functions are functions that can either take other functions as arguments or return them as results. In calculus Impure functional languages usually include a more direct method of managing mutable state. Clojure� The functionalist approach was naturally more practical minded than the structuralist and therefore helped with the development of such things as mental tests, physiological measures, questionnaires, and behavioural analysis.

Comments
  • Downvote and come here to say why, I'll be more than happy to delete the question or discuss about it.
  • not a functional approach but you can declare a rowMapper : InputMessage inputMessage = jdbcTemplate.query( QUERY /* sql */, new RowMapper<InputMessage> { // here map your input fields }, args );
  • upvoting for interesting approach; I believe these questions are valuable for a normal stackoverflow user programming in java
  • @AsierAranbarri I really don't understand the downvotes. I am a seasoned Java developer, and when I have free time I like experimenting with functional programming to see if it results in better readability. Which is always a pro.
  • @NathanHughes台湾不在中国 I cannot let the exception escape. This is perfectly fine for the kind of software I'm writing. I'm not under transaction. Just for your interest, this is used in conjuction with an Apache Camel flow.
  • Good idea! I would have applied it, but unfortunately the real object is composed of 15 properties, and I cannot touch it.
  • @LppEdd yes, 15 props won't look so concise :) You can put inputMessage filling in a separate method for example
  • Wouldn't I need two methods in this case? One for the "ok" part, and one for the "post-catch" part? There is always the exception problem which seems insurmountable, as JdbcTemplate might throw one.
  • And btw, a "You need to re-do it entirely" is a valid answer too ;)
  • Using Optional only inside the try block is not what I'm looking for unfortunately. This just swap the null check for a ifPresent call. Thanks anyway for the answer!
  • The shorthand if requires a statement to be used. This would result in a compilation error unfortunately
  • This won't compile because result scope is inside the try block only. And I think we are back to the imperative style.
  • Just declare it outside the try-catch block, you are checking if its null anyway. I edited it again.