Question

I'm looking to control the output of values to always be below (X) without calling an argument every time ::

Small Example~

public int CurrentSpeed;
public int MaxSpeed;
private int caracceleration;
private int Blarg;

public int CarAcceleration{
    get{ 
        Blarg = CurrentSpeed + caracceleration;
        if(Blarg >= MaxSpeed){
            Blarg = MaxSpeed
        }

        return Blarg

    set;
    }

Is there a better way to do this without calling arguments every time?? Sadly as the amount and complexity of numbers increase (I'm using 3d arrays of values in my code) this becomes a light bottleneck

Was it helpful?

Solution 2

public int Speed
{
  get
  {
     return CurrentSpeed + CarAcceleration;
  {
}

public int CarAcceleration{
    get
    { 
        if(Speed >= MaxSpeed)
        {
            return MaxSpeed
        }

        return Speed;
    }
    set;
    }

I guess you can roll up the calculations to avoid repeating the summations in multiple places.

I recommend avoiding premature optimization. Based on your example it doesn't seem like performance will be much of an issue. Are you actually seeing performance problems?

OTHER TIPS

Right now you're doing the addition twice. I would do this:

get{ 
        var newSpeed = CurrentSpeed + CarAcceleration;
        if( newSpeed >= MaxSpeed){
            return MaxSpeed;
        }
        else{
            return newSpeed;
        }
}

In hindsight, a cleaner version of this code would be:

get{ 
        var newSpeed = CurrentSpeed + CarAcceleration;
        if( newSpeed >= MaxSpeed){
            newSpeed = MaxSpeed;
        }

        return newSpeed;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top