#Best practice for optional parameters?

1 messages · Page 1 of 1 (latest)

teal pike
#

I've started doing a pattern to pass "parameter structs" instead of method optional params. Also using type? for the optional aspect. So I have:
void Hit(HitInfo info) and:

struct HitInfo {
public float hp;
Vector3 point;
Vector3? direction;
}

I figured using a Vector3? is more flexible than checking direction == Vector3.zero, and more readable, but I read that all the HasValue / Value accessing causes boxing and extra allocations, is worrying about this premature optimization?
Or would explicit bool hasDirection; in my struct be all around better?

rocky wraith
still cape
#

im not sure if nullables use boxing, it should be like a pointer to some heap data (is either 0 or some pointer)

icy portal
#

I'd probably do multiple constructors instead such that one has a direction and one excludes it

#

this way you can call the other constructor and send in a default direction*

#

or rather chunk the logic up and only call the methods that require direction in the constructor that has it passed in

pseudo swallow
teal pike
#

yeah, it's an option to have HitFlags and types of hits that imply what data is there, but the nullables are just more readable

#

I was curious about the impact. I did more reading and I now think there is NO boxing if I'm just using my struct directly, only if I'd cast it to an object, or run linq on it etc.
(edited a typo, there is NO boxing...)
@pseudo swallow is it just general preference to avoid them?

pseudo swallow
#

You could even do something like:
public Vector3 Direction {get {if(type != Type.DirectionnalHit)Debug.LogError(); return direction;}

still cape
#

Boxing is when we cast a value type to object. That requires it to be "boxed" in a heap object. Rust has a type called Box<> that does this for example

#

I presume nullable is different because ideally it would actually be a bool + the object to avoid boxing

unique pond
still cape
#

Tbh that is probably wrong (I was thinking about it like c/cpp)

#

I wish i could find it but there was a great article that showed how shit nullables are impemented in old mono in unity 🤔

tawny haven
#

AFAIK nullables are just like a little struct along the lines of:

struct Nullable<T> {
  T value;
  bool hasValue;
}```
I don't think it does any boxing by default
peak scarab
#

this type of specialization probably already mentioned in the docs.. im pretty sure

#
  • If HasValue returns false, the null reference is produced.
    If HasValue returns true, the corresponding value of the underlying value type T is boxed, not the instance of Nullable<T>.

yep there it is

#

using nullables wont benefit you in most cases and you'd lose all sorts of compiler optimization. but its up to you

peak scarab