Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic in constructor?

Tags:

java

The code below is working fine but I'm wondering if there are any issues coming in object creation time.

import java.util.Scanner;

public class FactorialExample {
    public FactorialExample(int n) {
        int fact=1;
        for(int i=1;i<=n;i++) {
              fact=fact*i;  
        }
        System.out.println("the factorial of a given number is::"+fact);        
    }
            public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any Integer Value:");
        int value=sc.nextInt();
        FactorialExample fe=new FactorialExample(value);

    }
}
like image 289
madhu Avatar asked Jun 04 '14 13:06

madhu


1 Answers

Yes, you're onto the right assumption - don't use business logic in the constructor.

At most, initialize the object state.

Otherwise, things like exception handling, testing and mocking can becoming difficult.

In your code, you can completely avoid having a constructor, in fact:

import java.util.Scanner;

public class FactorialExample {
    int solve(int n){
        int fact=1;
        for(int i=1;i<=n;i++){
            fact=fact*i;
        }
        return fact;
    }

    public static void main(String[] args) {
        FactorialExample fe=new FactorialExample();
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any Integer Value:");
        int value=sc.nextInt();
        int solution = fe.solve(value);
        System.out.println("tha factorail of a given number is::"+solution);
    }
}
like image 157
vikingsteve Avatar answered Oct 10 '22 19:10

vikingsteve