can i let the constructor return which value has not been initialized due to validation reasons?

validation in constructor c#
constructor java
c# parameter validation
javascript constructor function
@value.immutable example
javascript class constructor
using setter in constructor
javascript constructor prototype

I have a constructor receives 3 parameters String name, int id, int height.

I am using the setters to check the validation : for example the height should be between 100cm to 250cm, thus I avoid the redundant instead of checking inside the constructor, but i need to use a while loop in the driver class to keep asking for the height again and again till the user enter a valid data ..

the problem is: How can I specify that the problem was in the height not in the name ..

setHeight(int height){
    if(height>=100 && height<=250){
         this.height=height;
     }
  }

the constructor will call this method to set the height and check the validation, but if it is not valid I need the constructor to return something to the user to specify that the app accepted the name but there is a problem in the height .

should I use a static boolean variable for each parameter to see which is not valid or there exist an easier way for it ?


You can define specific Exception for each of them and throw them accordingly.

public class Test {

    int id;
    int height;
    String name;

    public Test(int id, int height, String name) throws HeightException, NameException, IdException {
        setHeight(height);
        setId(id);
        setName(name);
    }

    public static void main(String[] args) {
        try {
            Test tes = new Test(1, 2, "Hello")
        } catch (HeightException e) {
            //height is wrong
            e.printStackTrace();
        } catch (NameException e) {
            //name is wrong
            e.printStackTrace();
        } catch (IdException e) {
            //id is wrong
            e.printStackTrace();
        }
    }

    public void setId(int id) throws IdException {
        if (id >= 200)
            throw new IdException("Id is wrong it must be lower than 200");
        this.id = id;

    }

    public void setHeight(int height) throws HeightException {
        if (height >= 100 && height <= 250) {
            this.height = height;
        } else
            throw new HeightException("Height is wrong it must be between 100 and 250");
    }

    public void setName(String name) throws NameException {
        if (name.length() >= 20)
            throw new NameException("Name is wrong it must be less than 20 characters");
        this.name = name;
    }

    class NameException extends Exception {
        NameException(String message) {
            super(message);
        }
    }

    class HeightException extends Exception {
        HeightException(String message) {
            super(message);
        }
    }

    class IdException extends Exception {
        IdException(String message) {
            super(message);
        }
    }
}

Constructor parameter validation in C# - Best practices, Honestly, I can't think of a reason why not. NET framework will throw exceptions in their constructors. Throw an exception IFF the class cannot be put into a consistent state with regard to an empty constructor + initialize() before your object is actually completely built). 2 - Call an Initialize method with a return result. Sometimes you need to write code that can't use exceptions. If that's the case there isn't an obvious way to handle errors in constructors, as they don't have a return value. This post shows how you can report errors without using exceptions and without sacrificing the benefits of constructors.


Create a factory method instead that throws an specific exception for each field if validation fails

public static MyClass create(String name, int id, int height) {
    if (name == null || name.isEmpty()) {
         throw new IncorrectNameException("Name must be given");
    }

    //validate id 

    //validate height

    return new MyClass(name, id, height);
}

You can create an exception class for each field (or even for each type of error)

class IncorrectNameException extends RuntimeException {

}

class IncorrectHeightException extends RuntimeException {

}

class IncorrectIdException extends RuntimeException {

}

Programming with Microsoft Visual Basic 2015, The class should contain an auto-implemented property that will store the side contain a default constructor and a method that calculates and returns the square's perimeter. An employee object can initialize its attributes using values provided by the class. May not be copied, scanned, or duplicated, in whole or in part. A constructor can not explicitly return a value. A constructor already returns reference ID of a created object and constructor itself is a method. A method can not return more than one value. So, we can say that a constructor can not explicitly return a value.


Since the variable height is an int and you are setting its value only if its valid which is >=100 and <=250 , you can simply check if height == 0 which is the default int value and return the error message to the user if the value of height is 0.

Why did it not become a common pattern to use setters in the , this doesn't check the return value from setAge . wasted default initialization (​which for some member variables at least is worth avoiding) if there is a validation of a constraint in a setter, should it not also be in the constructor of A constructor, when it does not throw an exception, should leave the object in a valid state,  I think others have explained why they don't have a return type, but just to be clear: a constructor is not a method. Here are some relevant quotes from the Java Language Specification . The body of a class declares members (fields and methods and nested classes and interfaces), instance and static initializers, and constructors


Why Immutables Are the Better Objects and How to Implement Them, It's good to know what an immutable object is, but why should we use them? compilers can tell us when such a field has not been initialized. Instead of writing the constructor by hand, we can use Lombok to object may have fields that are optional so that their value is null. Thanks for reading! The value of a bool is always false or true. If you see it as something else you did a cast. If you see it as a big number, then you might have done an invalid cast. Due to spees reasons, there is no real bool type because a computer cannot easily handle single bits. So a bool is also a byte by default.


constructor, The ValidationError class doesn't need an explicit constructor, because it doesn't need to do any custom initialization. The default constructor  Initialization means the object was provided with an initial value at the point of definition. Uninitialized means the object has not been given a known value (through any means, including assignment). Therefore, an object that is not initialized but is then assigned a value is no longer uninitialized (because it has been given a known value).


Object.prototype.constructor, The following example shows how to modify the constructor value of generic objects. Only true , 1 , and "test" will not be affected (as they have  Constructors have no return type (not even void) Default constructors. A constructor that takes no parameters (or has parameters that all have default values) is called a default constructor. The default constructor is called if no user-provided initialization values are provided. Here is an example of a class that has a default constructor:


@NoArgsConstructor, @RequiredArgsConstructor , @NoArgsConstructor will generate a constructor with no parameters. constraints will generally not be fulfilled until those fields are properly initialized later. the staticName value for the annotation, like so: @​RequiredArgsConstructor(staticName="of") . To put annotations on the generated constructor, you can use  Structures follow all the rules of classes. Therefore, you can have a primary constructor, and you can provide additional constructors by using new. However, there is one important difference between structures and classes: structures can have a parameterless constructor (that is, one with no arguments) even if no primary constructor is defined.