Recently, i got a task where licensing was required to be added. I have done such tasks using ant in the past but this time I was supposed to use maven. Some quick search made it clear that maven provides a plugin to do such activities but the documentation was not upto the mark (or i can say it was a bit confusing or too generic). To save other people from such situation I am going to demonstrate it using a simple example.

Lets suppose you want to have licensing information given below in all java files of your project:

/**
 * Copyright (C) 2014 My Coaching Company. All rights reserved This software is the confidential
 *  and proprietary information of My Coaching Company. You shall not disclose such confidential
 * information and shall use it only in accordance with the terms of the license agreement you 
 * entered into with My Coaching Company.
 *  
 */

Here are steps to do so:

1. Create a txt file named License.txt and place it in parallel with pom.xml and make sure that your license file should not contain comments like /** ... */. It should look like,


 Copyright (C) 2014 My Coaching Company. All rights reserved This software is the confidential      and proprietary information of My Coaching Company. You shall not disclose such confidential        information and shall use it only in accordance with the terms of the license agreement you entered    into with My Coaching Company.
 
2. Add following snippet to pom.xml

  <properties>
        <license.dir>${basedir}</license.dir>
  </properties>

3. Now add plugin configuration for adding license to java files in maven project,

<!-- License information -->
<plugin>
<groupId>com.mycila.maven-license-plugin</groupId>
<artifactId>maven-license-plugin</artifactId>
<version>1.10.b1</version>
<configuration>
<header>${license.dir}/license.txt</header>
<properties>
<project>
${project.name}
</project>
<founder>${project.organization.name}</founder>
<year>${project.inceptionYear}</year>
<website>${founder-website}</website>
</properties>
<includes>
<include>src/main/java/**</include>
<include>src/test/java/**</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>format</goal>
</goals>
<phase>process-sources</phase>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.mycila</groupId>
<artifactId>licenses</artifactId>
<version>1</version>
</dependency>
</dependencies>
</plugin>

4. Now you are all set to fire the command 
     mvn license:format
 This will add license information on top of java code.


Note: If you have projects under subproject something like
   
 project ---|
                 | --> sub-project
                 | --> sub-project2

then you are required to add following snippet into the pom.xml of sub-projects:

<properties>
    <license.dir>${project.parent.basedir}</license.dir>
</properties>

I hope this should help lots of developers around. This is one of the most simple usage of this plugin for more please refer to the official site.



0

Add a comment


  1. Its a common requirement that we have to keep backup and restore data/indexes of solr. Although latest versions of solr makes life a lot easier. I will explain how to do it in solr 4.x, taking simplest use case. Follow the below steps:

    For Backup

    Open browser and type this command in address bar

    http://localhost:8983/solr/my_core/replication?command=backup&location=/tmp/backup_1&numberToKeep=1

    here "my_core" is name of solr core and location is absolute path to directory where you want to create backup. in this case backup files will be created under /tmp/backup_1

    For Restoration

    Open Admin UI and unload my_core core from "core admin" tab.
    Now manually copy the files backup files created under /tmp/backup_1 to /path-to-solr-data/my_core/data/index.
    Remove 'tlog' directory under /path-to-solr-data/my_core/data.
    make sure to set proper permissions like user is "solruser" and group is "solr". Following commands can be used:

    [root@svc-2-solr index]# chgrp solr *
    [root@svc-2-solr index]# chown solruser *

    Now, go back to "core admin" tab from admin UI and click "add core". Now fill in following details:
    name : my_core
    instanceDir : /path-to-solr-config-install/my_core/
    dataDir : /path-to-solr-data/my_core/data/index

    submit the form. All set, indexes should be right back at desired place.
    0

    Add a comment



  2. Multithreading has always been an area of interest for most of the developers. They have been trying hard to find out the most optimal strategy to solve this problem. In the past various attempts have been made to standardize such solutions. Especially with the rise of new problem domains like Big Data, real time analytics etc. new challenges have been introduced. One of the steps taken in this direction was work (great work) by “Doug Lea”, available to us in form of concurrency framework (JSR 166).

    As, now we have started distinguishing between concurrency and parallelism. These are different strategies and a number of frameworks are available in market, which enable us to achieve the same. While making such choice, we can benefit a lot if we also know about their internal implementation details. In this article we will explore some of the well-established options available for thread pooling/sharing in jvm. Also, with the availability of multicore processors new issues have crept up. Developers have started to think and exploit “mechanical sympathy” to gain performance from superior hardware.

    In my opinion, following are the main mechanisms that are currently wide spread when we start discussing about thread pooling:

          1. Thread pools available in Executor framework
     2. Ring Buffer concept by LMAX
     3. Actor (event) based  implementations

    Pool options under Concurrency framework:

    First of all, I would personally disagree with the widespread term threadpool and instead would term it as a worker queue. In a nutshell, all different kinds of pooling options available in executor framework are based on some kind of sequential data structure like array or queue (blocking or non-blocking) for example ConcurrentLinkedQueue, ArrayBlockingQueue, LinkedBlockingQueue etc. Their Documentation reveals that they are meant to be used under different circumstances but their underlying fact/data structure has same property i.e., sequential insertion and traversal. 



    Benefits:
    a.       Delay introduced in thread creation is reduced.
    b.      By proper tuning of thread count, we can address resource thrashing.

    These can be used in rendering applications and server applications to improve response time.  Using thread pool might seem as acceptable solution but these suffer from fundamental flaw i.e., sequential contention. Here is a good discussion on some pooling options available under concurrency framework in java.

    Disruptor (Ring Buffer):

    Developers at LMAX tried to address this issue of sequential contention with disruptor framework based upon data structure called “ring buffer”. It is a way of sending messages between threads in the most efficient manner possible. It can be used as an alternative to a queue, but it also shares a number of features with SEDA and Actors. Putting messages into the Disruptor is a 2-phase process, first a slot is claimed in the ring buffer, which provides the user with the Entry that can be filled with the appropriate data. Then the entry must be committed, this 2-phase approach is necessary to allow for the flexible use of memory mentioned above. It is the commit that makes the message visible to the consumer threads. Figure below depicts the data structure ring buffer (core of disruptor). 


    Disruptor achieves very low latency and high throughput on multicore platforms even if threads are sharing data and passing across messages.

    What makes it so unique is its lock and contention free architecture. It doesn’t even employ CAS or memory barriers. For more details about this, here is a good article and official website. One of the shortcomings (not actually a drawback) of using disruptor is, you need to upfront tell disruptor about the approximate number of threads application will need to complete the task.

    Event based:

    One of the powerful alternatives of traditional thread pooling mechanisms is based on event model.  Event based thread polling/pooling/scheduling mechanism is very common in functional programming space. One of the very popular implementation of this concept is actor based systems, where “Akka” has become the de-facto standard.

    Actors are very lightweight concurrent entities. They process messages asynchronously using an event-driven receive loop. Pattern matching against messages is a convenient way to express an actor's behavior. They raise the abstraction level and make it much easier to write, test, understand and maintain concurrent and/or distributed systems. You focus on workflow—how the messages flow in the system—instead of low level primitives like threads, locks and socket IO. One thread can be assigned multiple or single actor only, both models can be exploited as per choice.

    Some of the benefits of using actor based system like akka are:
    • ·      Encapsulation
    • ·         Supervision
    • ·         Configurable execution
    • ·         Location transparency
    • ·         Re-try mechanism

    Note: Debugging an actor based system could be challenging.

    The Disruptor uses a 1 thread - 1 consumer model, where Actors use an N:M model i.e. you can have as many actors as you like and they will be distributed across a fixed numbers of threads (generally 1 per core), otherwise actor model is very close to disruptor; specially when used for batch processing.
    Also, my initial search on internet revealed that there are contributions in open source space towards benchmarking such options on jvm. One such option is ExecutorBenchmark.It is an open-source test framework for parallelizable tasks. It is written in Scala, and can be used with Java and Scala loads.

    In nutshell, evolving software and hardware industry has presented us new challenges but also has given us a wide range of solutions to make our applications more responsive and fault resistant. For unpredictable and small number of threads we recommend use of pooling mechanisms available in concurrency framework (part of jdk). For large number of similar sized tasks, we recommend use of disruptor. Disruptor has slight learning curve but benefits gained in terms of performance and scalability over run the cost of time invested. In case our application requires some sort of re-try mechanism or supervision and distributed nature of tasks, I recommend use of “Actor” model (Akka). Although decisions might also get influenced by other factors like, for a distributed application you might choose something like map reduce or fork/join model or some custom implementation. 

    0

    Add a comment



  3. Recently, i got a task where licensing was required to be added. I have done such tasks using ant in the past but this time I was supposed to use maven. Some quick search made it clear that maven provides a plugin to do such activities but the documentation was not upto the mark (or i can say it was a bit confusing or too generic). To save other people from such situation I am going to demonstrate it using a simple example.

    Lets suppose you want to have licensing information given below in all java files of your project:

    /**
     * Copyright (C) 2014 My Coaching Company. All rights reserved This software is the confidential
     *  and proprietary information of My Coaching Company. You shall not disclose such confidential
     * information and shall use it only in accordance with the terms of the license agreement you 
     * entered into with My Coaching Company.
     *  
     */

    Here are steps to do so:

    1. Create a txt file named License.txt and place it in parallel with pom.xml and make sure that your license file should not contain comments like /** ... */. It should look like,


     Copyright (C) 2014 My Coaching Company. All rights reserved This software is the confidential      and proprietary information of My Coaching Company. You shall not disclose such confidential        information and shall use it only in accordance with the terms of the license agreement you entered    into with My Coaching Company.
     
    2. Add following snippet to pom.xml

      <properties>
            <license.dir>${basedir}</license.dir>
      </properties>

    3. Now add plugin configuration for adding license to java files in maven project,

    <!-- License information -->
    <plugin>
    <groupId>com.mycila.maven-license-plugin</groupId>
    <artifactId>maven-license-plugin</artifactId>
    <version>1.10.b1</version>
    <configuration>
    <header>${license.dir}/license.txt</header>
    <properties>
    <project>
    ${project.name}
    </project>
    <founder>${project.organization.name}</founder>
    <year>${project.inceptionYear}</year>
    <website>${founder-website}</website>
    </properties>
    <includes>
    <include>src/main/java/**</include>
    <include>src/test/java/**</include>
    </includes>
    </configuration>
    <executions>
    <execution>
    <goals>
    <goal>format</goal>
    </goals>
    <phase>process-sources</phase>
    </execution>
    </executions>
    <dependencies>
    <dependency>
    <groupId>com.mycila</groupId>
    <artifactId>licenses</artifactId>
    <version>1</version>
    </dependency>
    </dependencies>
    </plugin>

    4. Now you are all set to fire the command 
         mvn license:format
     This will add license information on top of java code.


    Note: If you have projects under subproject something like
       
     project ---|
                     | --> sub-project
                     | --> sub-project2

    then you are required to add following snippet into the pom.xml of sub-projects:

    <properties>
        <license.dir>${project.parent.basedir}</license.dir>
    </properties>

    I hope this should help lots of developers around. This is one of the most simple usage of this plugin for more please refer to the official site.



    0

    Add a comment


  4. Concurrency sparked widespread interest in functional programming. Multithreaded programming, requiring synchronized access to shared, mutable state, is the assembly language of concurrency.

    • Immutable values make synchronization unnecessary.
    Mutating state is never completely avoidable. We will examine two higher-level abstractions that provide “principled” ways to manage mutable state in thread-safe ways:

    1. i. Actors
    2. ii. Software Transactional Memory.


    The Actor Model
    In the Actor model of concurrency, work is coordinated by message passing between “actors.” Each actor has a queue, sometimes called a mailbox, for incoming messages. The actor processes each message, one at a time. Perhaps the best known implementation of actors is found in Erlang, where actors are the core of everything you do in the language.

    This metaphor of passing messages between objects is not only intuitive, it helps clarify boundaries between objects. Have you seen code where one object makes lots of little calls to other objects to get bits of information? How would you change that code if you thought in terms of message passing, instead?

    In an actor system, state mutation is handled one of several ways. For some state, it can be the responsibility of one actor to mutate that state. No other code is permitted to do so. When a mutation is required, a message is sent to the actor, which performs all such changes sequentially, thereby avoiding synchronization problems. A similar model is to allow multiple actors to modify the same state, but only one at a time. A special “semaphore” message is exchanged that tells the receiver that it is safe to modify the state. When finished, the semaphore is sent to another actor.

    Both cases run the risk of creating a bottleneck if the scope of responsibility is too large. It might be necessary to break it down into smaller, “isolated” sections. Good actor libraries are available for most languages. Perhaps the best option for Java is the Akka Java API. Following is an example from akka website:


    1. case class Greeting(who: String)
    2.  
    3. class GreetingActor extends Actor with ActorLogging {
    4. def receive = {
    5. case Greeting(who) log.info("Hello " + who)
    6. }
    7. }
    8.  
    9. val system = ActorSystem("MySystem")
    10. val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
    11. greeter ! Greeting("Charlie Parker")


    Software Transactional Memory

    Most of us have worked on “RDBMS”. They support ACID transactions. The goal of ACID transactions is to avoid logical inconsistencies in a given set of related records.  Software Transactional Memory (STM) brings transactions to locations in memory that are referenced by variables). STM can’t provide durability, because memory isn’t durable (e.g., if the power is lost), but STM can provide
    the ACI, atomicity, consistency, and isolation in ACID.

    The model in STM is to separate references to values from the values themselves. In STM, a program has a reference to a value of interest. The STM framework provides a protocol for changing the value to which the reference “points”. However, values themselves are not changed. They remain immutable. Only the references change to point to new values. Persistent Data Structures are exactly what STM needs.


      Figure below shows the state at time “0.” There are two references pointing the same value1 of a persistent data structure.




    Now let’s change ref2 to point to a new, updated value, as shown below:




    By time “1,” an STM transaction in the context of ref2 has been used to move its reference to value2, which was created from value1, as indicated by the dotted line. Creating value2 does not necessary have to occur within the transaction, just the reassignment of ref2.  This behavior allows different clients to acquire references to the same value at a particular time, but each can work with the value without fear that it will change unexpectedly, due to the actions of one of the other clients. A version with no references will be garbage collected.


    There are several STM libraries for Java, many of which are inspired by Clojure’s implementation. Akka integrates with the Multiverse STM. 

    The main intent of these concepts is to provide new and higher level of abstraction to developers. This will enable them to write better concurrent programs.




    0

    Add a comment


  5. Functional languages provide a core set of common data structures with combinatory operations that are very powerful for working with data. Functional algorithms emphasize declarative structure, immutable values, and side-effect-free functions. We already think of lists, maps, etc. as “collections,” all with a set of common methods. In functional programming, there are three core operations that are the basis of almost all work you do with collections:

    1. Filter -- Create a new collection, keeping only the elements for which a filter method returns true.

        2. Map –  Create a new collection where each element from the original collection is  transformed into a new value.
       
        3. Fold -- Starting with a “seed” value, traverse through the collection and use each element to build up a new final value where each element from the original collection “contributes” to the final value.

    Together they are the basis for implementing concise and composable behaviors.


                                    Persistent Data Structures

    It seems that if we want immutable values, we have to make a copy whenever we change
    a value. While this may be fine for small objects, it will be too expensive for large objects,
    like long lists and large maps.
    Fortunately, we can have both immutability and acceptable performance if we only allocate memory for what is actually changing and we share the unchanged parts with the original object. This approach is called structure sharing. Tree data structures provide the balance of performance and space efficiency required to do this. The public abstraction might still be a List, a Map, or another data structure.

    Unbalanced binary trees provide average O(log2(N)) search times (unless the tree is really unbalanced). Real persistent data structures often use one of several 16- or 32-way balanced tree variants to further reduce search times and to optimize other performance goals.

    Example: Tree at time “0”, referenced as an object named Value1




    Now imagine a user wants to create a new tree that prunes off nodes a1 and its left branch, node a2, but keep node a3 and its right branch, node a4. All we have to do is create a new root node that points to a3 as its left branch and b1 as its right branch.


    Note that a history of the evolving values is being maintained. We still have value1 and as long as some code has a reference to it, it won’t be garbage collected. This is why these data structures are called persistent.

    Interest in Domain-Specific Languages is another recent, popular trend. DSLs try to capture the idiomatic language used by domain experts directly in the code. You can implement DSLs in both object oriented
    and functional languages. it can be useful to represent a domain with a DSL at the upper levels of abstraction, but questionable to create explicit object representations under this surface. We can have a DSL that says, for example groupUsersByDomain in emailAddresses, but implement it with List<EmailAddresses>.foldLeft(new HashMap<…>(), groupingFunction);

    As I said in my earlier blog post, objects operate at the wrong level of abstraction and they lack a standard set of protocols that are essential for the kind of reuse we want. The core data structures of functional programming and the combinators like filter, map, and fold bring us closer to that ideal.




    0

    Add a comment

  6. 1.       Do not repeat yourself (DRY) – check if you have added something to CPD reports. CPD can be easily taken from tools like PMD.
    2.       Take care about methods:
    ·         Do not create methods for “side effects”. They can drive you crazy in case of bugs.
    ·         Methods shouldn’t be doing multiple things.
    ·         Try to switch over to “switch” statement rather than nested “if”.
    ·         Make sure methods use abstractions rather than concretions.
    ·         Use fewer arguments.
    ·         Catch as specific exceptions as possible (use exceptions instead of returning null).
    ·         Prefer “early return” over “single return” policy.

    3.       Take care about classes:
    ·   Follow “single responsibility”, “open closed” principles.
    ·   Classes should be small unless you have strong reason for them to be large (Smaller classes are easier to grasp. Classes should be smaller than about 100 lines of code. Otherwise, it is hard to spot how the class does its job and it probably does more than a single job).
    ·   Avoid multiple languages in one file/class (C#, java, html, javascript, xml, English, French…).
    ·    Use explanatory variables.
    ·   Try and use, small and immutable objects.
    ·   Prefer composition over inheritance.
    4.       You should reconsider design in case method crosses 10 or class crosses 100 line limit.
    5.       Avoid manual memory management.
    6.       In case you are using any DI framework like spring, guice etc. don’t spread your dependencies across code and configuration files (java, c#, xml). Try keeping them either in code or in xml files. Mixing them will give you nightmares.

    Some of the tools that will be helpful for developing quality code are checkstyle, pmd, javaNCSS, coverlipse, eclipse metrics plugin, sonarqube etc. These are just some recommendations not hard lines. These have proved beneficial for most of the projects/scenarios. There could be anti-patterns to them too, on case-by-case basis. Practicing methodologies like agile, TDD etc. and standard frameworks like guava, spring etc. can also help in producing quality code.
    0

    Add a comment


  7. Around two years back I was introduced to some concepts like Big Data, Distributed Computing, NoSQL and Guava api. This lead to my introduction to the term “Functional Programming”. At that time I just parked this term and continued with my interest in NoSQL space but as my work and interest grew in these areas, more I heard about benefits for using this style. A couple of weeks back I got chance to spend time on it. I started up this as learning some DSL (domain specific language [for Big Data products]) but soon realized that this is much more than what I expected. I found that it brought new clarity to my thinking about the design of types and functions. It also allowed me to write more concise code. I also concluded that functional programming is a better fit for many of the unique challenges of our time, like working with massive data sets and remaining agile as requirements change ever more rapidly and schedules grow ever shorter.

    It’s hard to believe that objects, which have worked so well in the past, could be any less valuable today, isn’t it? For me, my growing interest in functional programming isn’t a repudiation of objects, which have proven benefits. Rather, it’s a recognition that the drawbacks of objects are harder to ignore when faced with the programming challenges of today. Both FP and OOP are tools, not silver bullets. Each has advantages and disadvantages. For me, functional programming offers the best approach to meet the following challenges, which I face every day like,
      
    • We need to write better concurrent programs.
    • Most of our programs do just, “Data Manipulation”. I personally worked a lot in Big-Data space and can tell you that Objects are big overhead.
    • We need to be agile (ORM is a classic example about our love for Objects. Working directly with more fundamental collections of data minimizes the overhead of working with object models).

    Most of the successful examples of reusable libraries are platforms that defined their own standards that everyone had to follow like spring, Eclipse plugin api, apache commons etc. They have their own custom APIs that we must conform to. For the rest of the code we need, we still rewrite a lot of it project after project. Hence, object-oriented software development isn’t the “component assembly” as we hoped. There are no standards in “Object-based” programming like digital electronics which enable innovative, better and cheaper designs.

    Agility

    Day by day our release cycles are getting shorter. All of us are feeling the pressure to get work done more quickly, without sacrificing quality, of course. Today, for most projects, understanding the domain precisely is less important than delivering some value quickly. If we misunderstand some aspect of the domain, we can fix those mistakes quickly when we do frequent deployments. If careful modeling seems less important, faithfully implementing the object model is even more suspect today than before.

    Note: I’m not trying to convince you to abandon objects altogether or to become an FP advocate. I’m trying to present here a bigger toolbox and a broadened perspective.
    0

    Add a comment


  8. Functional programming, in its “purest” sense, is rooted in how functions, variables, and values actually work in mathematics, which is different from how they typically work in most programming languages.  In functional programming, programs are executed by evaluating expressions, in contrast with imperative programming where programs are composed of statements which change global state when executed. Functional programming typically avoids using mutable state.

    Haskell Curry (for whom the Haskell language is named) helped develop Combinatory Logic, which provides an alternative theoretical basis for computation. Combinatory Logic examines how combinators, which are essentially functions, combine to represent a computation. They are useful for representing the steps in a planned/building blocks of computation, which can be analyzed for possible bugs and optimization opportunities.

    History
    The first language to incorporate functional programming ideas was Lisp, which was developed in the late 1950s and is the second-oldest high-level programming language, after Fortran. The ML family of programming languages started in the 1970s, including Caml, OCaml (a hybrid object-functional language), and Microsoft’s F#. Perhaps the best known functional language that comes closest to functional “purity” is Haskell, which was started in the early 1990s. Other recent functional languages include Clojure and Scala, both of which run on the JVM but are being ported to the .NET environment.





    Basic Principles of FP

    Avoiding Mutable state
    X2 + Y2 = Z2
    If I give you values for the variables x and y, say X=3 and Y=4, you can compute the value for Z (5 in this case). The key idea here is that values are never modified. It would be crazy to say 3++ (X++), but you could start over by assigning new values to the same variables.

    Why should we avoid mutating values?
    i. Allowing mutable values is what makes multithreaded programming so difficult. If multiple threads can modify the same shared value, you have to synchronize access to that value. If you make a value immutable, the synchronization problem disappears. Concurrent reading is harmless, so multithreaded programming becomes far easier.

    ii.   Immutable values relates to program correctness in other ways. It is harder to understand and exhaustively test code with mutable values, particularly if mutations aren’t localized to one place. Some of the most difficult bugs to find in large systems occur when state is modified non-locally, by client code that is located elsewhere in the program.

    Defensively copying objects could be an option to mimic Immutability but this could prove to be an expensive operation as and when objects become large for example, large list of Orders.  What happens when the list of orders is supposed to change, but it has become huge? Should we relent and make it mutable to avoid the overhead of making big copies? Fortunately, we have an efficient way to copy large data structures; we’ll reuse the parts that aren’t changing.

    Functional programming encourages us to think strategically about when and where mutability is necessary. If we encapsulate mutations in well-defined areas and keep the rest of the code free of mutation, we improve the robustness and modularity of our code. We still need to handle mutations in a thread-safe way. Software Transactional Memory and the Actor Model give us this safety.

       Functions as First Class values
    In OOPs, we are accustomed to passing objects and primitive values to methods, returning them from methods, and assigning them to variables. This means that objects and primitives are first-class values in OOPs.  A function is more general to method. It is not attached to any particular class or object. Therefore, all instance methods are functions where one of the arguments is the object. For example, in java you can’t pass a method as an argument to another method, return a method from a method, or assign a method as a value to a variable.

       Lambdas and Closures
    The term lambda is another term for anonymous function. It comes from the use of the Greek lambda symbol λ to represent functions in lambda calculus.  JDK8 will introduce a syntax for defining anonymous functions. Here is what the planned syntax looks like:

    public FunctionalHelloButtonApp() {
         button.addActionListener(
    #{ ActionEvent e -> System.out.println("Hello There: event received: "+e) }
    );
    }
    A closure is formed when the body of a function refers to one or more free variables, variables that aren’t passed in as arguments or defined locally, but are defined in the enclosing scope where the function is defined. The runtime has to “close over” those variables so they are available when the function is actually executed, which could happen long after the original variables have gone out of scope! Java has limited support for closures in inner classes; they can only refer to final variables in the enclosing scope. For example,
    scala> var more = 1
      more: Int = 1
      scala> val addMore = (x: Int) => x + more //
      addMore: (Int) => Int = <function>

     High Order Functions
    Functions that take other functions as arguments or return them as results. They are powerful tools for building abstractions and composing behavior. Higher-order functions allow nearly limitless customization of standard library types, like Lists and Maps, and also promote reusability. Here is a function apply which takes another function f and a value v and applies function f to v:

    def apply(f: Int => String, v: Int) = f(v)
    For example,
    class Decorator(left: String, right: String) {
      def layout[A](x: A) = left + x.toString() + right
    }

    object FunTest extends Application {
      def apply(f: Int => String, v: Int) = f(v)
      val decorator = new Decorator("[", "]")
      println(apply(decorator.layout, 7))
    }

       
    Side effect free Functions
    Another source of complexity, which leads to bugs, are functions that mutate state, e.g., setting values of an object’s field or global variables. In mathematics, functions never have side effects, meaning they are side-effect-free. For example, no matter how much work sin(x) has to do, its entire result is returned to the caller. No external state is changed. Being able to replace a function call for a particular set of parameters with the value it returns is called referential transparency.

    Side-effect-free functions make excellent building blocks for reuse, since they don’t depend on the context in which they run. Compared to functions with side effects, they are also easier to design, comprehend, optimize, and test. Hence, they are less likely to have bugs.

       Recursion
    Functional programming in its purest form doesn’t allow mutable values. That means we can’t use mutable loop counters to iterate through a collection! For example,

      for(int i=0; i < size; i++)

    The classic functional alternative to an iterative loop is to use recursion, where each pass through the function operates on the next item in the collection until a termination point is reached. Recursion is also a natural fit for certain algorithms, such as traversing a tree where each branch is itself a tree.

    However, each recursion adds a new frame to the stack, which can exceed the stack size for deep recursions. Tail-call recursions can be converted to loops, eliminating the extra function call overhead. Unfortunately, the JVM and the Java compiler do not currently perform this optimization (for details click here).



       Declarative v/s Imperative Programming
    Finally, functional programming is declarative, like mathematics, where properties and relationships are defined. The runtime figures out how to compute final values. The definition of the factorial function provides an example:

      Factorial(n) = 1        if  n=1
                            n *  factorial(n-1)   if n > 1

    Object-oriented programming is primarily imperative, where we tell the computer what specific steps to do. For example,

    public static long declarativeFactorial(int n) {
    assert n > 0 : "Argument must be greater than 0";
    if (n == 1) return 1;
    else return n * declarativeFactorial(n-1);
    }

    public static long imperativeFactorial(int n) {
    assert n > 0 : "Argument must be greater than 0";
    long result = 1;
    for (int i = 2; i<= n; i++) {
    result *= i;
    }
    return result;
    }


    Declarative programming is made easier by lazy evaluation, because laziness gives the runtime the opportunity to “understand” all the properties and relations, then determine the optimal way to compute values on demand.
    0

    Add a comment

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.