Consider the following. (in pseudocode).
Class
{
hello
world
public
constructor(hello, world)
{
if (hello is not String)
{
throw Exception()
}
if (world is not Array)
{
throw Exception()
}
this.setHello(hello)
this.setWorld(world)
}
protected
setHello(hello)
{
if (hello is not String)
{
throw Exception()
}
this.hello = hello
}
private
setWorld(world)
{
if (world is not Array)
{
throw Exception()
}
if (not this:isASafe(world))
{
throw Exception()
}
this.world = world
}
public
static
isASafe(world)
{
if (world is not Array)
{
return false
}
if (world.length < 1)
{
return false
}
if (world['sky'] is not 'blue')
{
return false
}
return true
}
}
Is it best practice to perform parametric type/validity checking at the constructor and then again at the function, or at only one of the two methods. (ie. constructor xor method).
Further, does the scope (public/protected/private/etc.) of said method change the above answer (1). For instance isASafe(world) is a public static method, and is only in the class to encapsulate logic.
Should constructors even be doing any checks?
I have my own personal opinions on the matter, but would like to see what others think, and what they find most effective/efficient.