dimanche 5 juin 2016

Java design pattern to check for integer sign

I come from C++ to Java, and, needless to say, certain things seem a bit unnatural (relative to my C++ background). For example, Java does not have unsigned numeric types. So I am curious whether there is a best, or conventional way, to check for sign in certain situations.

For example, suppose I'm designing a dynamic array class. I would like to keep track of the size of the array, which I can declare as

private int length

In case an array needs to be resized, it should be resized by a set block_size, so I should also have

private int block_size

Now, I should allow the user to set block_size, and I should certainly have something like

public void setValueAt(int pos) { ... }
public void setBlockSize(int bsize) { ... }

Now, because we do not have unsigned numeric types, and because -- in the best practices of OOD -- the objects should be consistent, I should guard against errors like setValueAt(-1).

The obvious way is a simple if conditional check. One could argue that I could simply let it slide, since at the point the array is referenced, Java will complain about the negative index and throw a compile-time error. This is fine if the indices are known at compile time, but not if they aren't.

An even worse situation is with block_size. A program can run for a long time before the time comes to resize, at which point either runtime exception or unpredictable behavior can occur.

So my question is:

What is the (or one of the) Java idiomatic ways/design patterns to handle this? Am I making it too complicated (i.e. should I just stick with the if checks and get on with life)?

This question, I think, becomes less trivial in a less trivial context (than the example above). For instance, I wouldn't want to pollute my code with if checks. It would be nice to just delegate the task to a designated error handler, that should somehow be intrinsic to the type. For instance:

Would it be more idiomatic to write a wrapper around the int type? Is there an elegant/idiomatic way to use Integer for this purpose?

EDIT

I seem to be getting lots of comments on this (which I do appreciate), but many are not focused on the actual question. The array class is an example. I am asking for a general, idiomatic way to handle a general situation which may arise in many different contexts.

Aucun commentaire:

Enregistrer un commentaire