1

I have always thought that methods and functions with an explicit signature and 3-5 lines of code would make the code more clear, but in many cases I have been told that I make too many functions/methods. Apparently it is easier to navigate inside a class that has few methods. These people say that a method should be split only for a mather of reusability. I personally believe that when a method is longer, it tends to become longer over modifications and that it will grow in complexity. Even whorse, it won't be testable anymore. I have read on the subject, and I haven't changed my mind, but it seems like I'm alone to think this way. Am I wrong?

I took this code from msdn:

   private void CreatePO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer serializer = 
      new XmlSerializer(typeof(PurchaseOrder));
      TextWriter writer = new StreamWriter(filename);
      PurchaseOrder po=new PurchaseOrder();

      // Create an address to ship and bill to.
      Address billAddress = new Address();
      billAddress.Name = "Teresa Atkinson";
      billAddress.Line1 = "1 Main St.";
      billAddress.City = "AnyTown";
      billAddress.State = "WA";
      billAddress.Zip = "00000";
      // Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress;
      po.OrderDate = System.DateTime.Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem i1 = new OrderedItem();
      i1.ItemName = "Widget S";
      i1.Description = "Small widget";
      i1.UnitPrice = (decimal) 5.23;
      i1.Quantity = 3;
      i1.Calculate();

      // Insert the item into the array.
      OrderedItem [] items = {i1};
      po.OrderedItems = items;
      // Calculate the total cost.
      decimal subTotal = new decimal();
      foreach(OrderedItem oi in items)
      {
         subTotal += oi.LineTotal;
      }
      po.SubTotal = subTotal;
      po.ShipCost = (decimal) 12.51; 
      po.TotalCost = po.SubTotal + po.ShipCost; 
      // Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po);
      writer.Close();
   }

I manipulated to transform it into this code:

    private void CreatePO(string filename)
    {
        Serialize(GetPurchaseOrder(), filename);
    }

    private PurchaseOrder GetPurchaseOrder()
    {
        return new PurchaseOrder()
            {

                ShipTo = GetBillAdress(),
                OrderDate = System.DateTime.Now.ToLongDateString(),
                OrderedItems = GetOrderedItems(),
                ShipCost = (decimal)12.51
            };
    }

    //Will be inside of PurchaseOrder class
    private decimal GetSubTotal(OrderedItem[] items)
    {
        return items.Sum(x => x.LineTotal);
    }

    private OrderedItem[] GetOrderedItems()
    {
        OrderedItem i1 = new OrderedItem()
            {
                ItemName = "Widget S",
                Description = "Small widget",
                UnitPrice = (decimal)5.23,
                Quantity = 3,
                Calculate()
            };

        // Insert the item into the array.
        return new OrderedItem[]{ i1 };
    }

    private void Serialize<T>(T toSerialize, string filename)
    {
        using (var w = new StreamWriter(filename))
        {
            var s = new XmlSerializer(typeof(T));

            s.Serialize(w, toSerialize);
        }            
    }

    private Adress GetBillAdress()
    {
        return new Address()
            {
                Name = "Teresa Atkinson",
                Line1 = "1 Main St.",
                City = "AnyTown",
                State = "WA",
                Zip = "00000"
            };
    }

Some may say that most of the functions here will only be used once. But what is the best practice? Would this way of splitting the code slower the execution? and complexifie the compilation? What are the real advantages of both other than readability?

Fjodr
  • 919
  • 13
  • 32
  • 3
    This question as currently stated is asking for opinions. Please try to restate your question in such a manner that it can be more about facts than opinions. What you could do for example is ask a question along the line of "I have this concrete class with these and these methods, I am considering redesigning it in this manner, because I expect these *concrete* benefits and downsides. Am I overlooking something, what would be some other downsides." Accompany that with an actual real concrete code / design example that you address concretely in your question. – Alex Apr 17 '15 at 13:35
  • I think this question is more suited for Programmers stackexchange – Guanxi Apr 19 '15 at 13:38

1 Answers1

0

Well in my opinion you are right. But it is an opinion.

For best practices about number and size of methods see this question

But it is possible to do this in a completely wrong way!

While splitting work in smaller methods you have to take care not to introduce unwanted dependencies between those methods.

For example, when a methods starts relying on state set by another method instead of passing that information as a parameter we are entering murky waters.

So it certainly depends on how it is implemented.

For testability it should not actually matter, since most of those small methods are private and can only be tested trough the public interface of a class.

It is certainly not the intention to go test each and every method on its own. This would make test very brittle. When you start out with a tested big method and you refactor in to a bunch of smaller methods, the tests should not be updated on you should keep 100% coverage.

Community
  • 1
  • 1
Glenner003
  • 1,450
  • 10
  • 20