madhu
madhu

Reputation: 1103

Logic in constructor?

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);

    }
}

Upvotes: 12

Views: 21377

Answers (5)

vikingsteve
vikingsteve

Reputation: 40378

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 become 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);
    }
}

Upvotes: 15

TheLostMind
TheLostMind

Reputation: 36304

Constructor should be used only to initialize your object's state / fields. You should delegate the responsibility of other things to other methods. Note that a constructor is called only once i.e, whenever you create a new object. Here, in your design, you cannot calculate the factorial of a number without creating an object of FactorialExample. Instead, you should have a number n as a field in your FactorialExample and a separate method for calculating factorial.

Upvotes: 4

Abs
Abs

Reputation: 3962

Its a question of what you are trying to achieve together with real world problem domain in this case factorial.

If the constructor has everything then the constructor knows about many other objects. It becomes dependent on all those objects.

When features are added:

Example: What if i want the all positions where an Employee can sit around a table. The class above will not be able to as it is too tightly dependent for creation.

So you will have to expand you domain to include overloaded constructors and soon enough you will realise it becomes unmaintainable with increasing dependencies and population of Domain specific objects.

It is best programming practise to split it up.

Service concept proposed in Domain-Driven Design. Best to now read about different Design patterns particularly http://en.wikipedia.org/wiki/Design_Patterns#Creational

Factories and why we use them problem of creating objects without specifying the exact class of object http://en.wikipedia.org/wiki/Factory_method_pattern

Then i will suggest going forward reading about of Dependency injection and Inversion of control and why/how it decouples code.

http://martinfowler.com/articles/injection.html

Hope this helps!

Upvotes: 1

Tetsujin no Oni
Tetsujin no Oni

Reputation: 7367

Yes. With a sufficiently large input, you can cause an exception in your constructor.

This is one of several reasons why you should not use a constructor to contain "business logic".

In this case, the use of a constructor to both perform a computation and perform output is quite counter to good practice:

  • You have an object which contains no state and only does work in its constructor.
  • You are not interacting with the object created by the constructor, partly because it has no methods or fields to interact with.
  • Your constructor if considered as a method is violating the principal that a method should have a singular purpose (by both performing a computation and performing output).

Upvotes: 1

Ninad Pingale
Ninad Pingale

Reputation: 7069

In your case fact is a local variable inside the constructor. It is not even used outside the constructor. So in such cases constructor should not be used.

Upvotes: 0

Related Questions