Search code examples
c#class-design

Passing A Data Object Or Parts Of Data Object In Methods?


public class DataObject{
    public int Value1;
    public int Value2;
    public int Value3;
    public int Value4;
    public int Value5;

    public DataObject(){}
}

public class SomeClass{
    public SomeClass(){}
    public void MultiplyFirstThreeValues(int Value1, int Value2, int Value3){
        return Value1*Value2*Value3;
    }
    public void MultiplyFirstThreeValues(DataObject d){
        return d.Value1*d.Value2*d.Value3;
    }
}

Which is a better practice, to send each variable needed to a method or an entire data object (in the case where not every variable in the data object is used)? This may be an "art more than science" question, but if you can't give a hard and fast rule, then I'd be interested in hearing what would be the motivation to do one over the other (in this case where not all of the data object's values are used in the method).

Thanks, I'm looking forward to learning more about this.


Solution

  • I would opt for option C leave the logic within the object itself:

      public class DataObject
      {
        private int Value1;
        private int Value2;
        private int Value3;
        private int Value4;
        private int Value5;
    
        public DataObject(){}
    
        public int MultiplyFirstThreeValues()
        {
            return Value1*Value2*Value3;
        }
     }
    

    Edit: In response to the comment - I'll add a quote:

    Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.

    It's just a better design approach imo since it lets you hide the way you actually get your results / do your implementation. The way you have it currently set up more reflects the Visitor pattern, which can be powerful, but also adds more complexity since the interface to your class has now all these public members. If your calculation would span multiple DataObject's and/or other types this actually might make sense though but I would definitely use encapsulation if I can get away with it.