Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > .NET для новичков > Форматирование кода, "разреженный код"


Автор: ToLive 8.10.2011, 07:25
Здравствуйте!

Не так давно начал программировать на C#, изучаю по книге Шилдта "Полное руководство С# 2.0. Т.к. переучиваться всегда гораздо сложнее, чем сразу научиться правильно, то прошу дать мне совет по поводу форматирования кода. Сильно ли ухудшает или улучшает читаемость кода дополнительные пробелы и переводы строк (пробел между методом и его аргументами, открывающая фигурная скобка блока всегда с новой строки, перевод строки после комментария и т.п.). Чтобы не быть голословным, то я приведу два примера, один из них написан мной по книге, а второй - этот же пример, но из исходников автора:

Мой:
Код

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BinaryOverload
{
    //class of 3D system

    class ThreeD
    {
        int x, y, z; //coordinates of the object

        //default constuctor without arguments

        public ThreeD ()
        {
            x = y = z = 0;
        }

        //constructor with all three arguments

        public ThreeD (int i, int j, int k)
        {
            x = i;
            y = j;
            z = k;
        }

        //overload the binary '+' operation. It will return the object with new coordinates, which will be the sum of the coordinates of the sended objects.

        public static ThreeD operator + (ThreeD op1, ThreeD op2)
        {
            ThreeD result = new ThreeD ();

            result.x = op1.x + op2.x;
            result.y = op1.y + op2.y;
            result.z = op1.z + op2.z;

            return result;
        }

        //override the binary '+' operation. It will return the object with new coordinates, which will be the subtract of the coordinates of the sended objects.

        public static ThreeD operator - (ThreeD op1, ThreeD op2)
        {
            ThreeD result = new ThreeD ();

            result.x = op1.x - op2.x;
            result.y = op1.y - op2.y;
            result.z = op1.z - op2.z;

            return result;
        }

        //show the current coordinates

        public void show ()
        {
            Console.WriteLine (x + ", " + y + ", " + z);
        }

    }
        
    class Program
    {
        static void Main (string[] args)
        {
            //creating three objects of ThreeD

            ThreeD a = new ThreeD (1, 2, 0);
            ThreeD b = new ThreeD (5, 6, 7);
            ThreeD c = new ThreeD ();

            //show original coordinates of the points

            Console.Write ("Coordinates of point \"a\": ");
            a.show ();
            Console.WriteLine ();

            Console.Write ("Coordinates of point \"b\": ");
            b.show ();
            Console.WriteLine ();
            
            Console.Write ("Coordinates of point \"c\": ");
            c.show ();
            Console.WriteLine ();

            //results of plus and sub operations

            c = a + b;
            Console.Write ("Result of \"a + b\": ");
            c.show ();
            Console.WriteLine();

            c = a + b + c;
            Console.Write("Result of \"a + b + c\":");
            c.show();
            Console.WriteLine();

            c = c - a;
            Console.Write("Result of \"c - a\": ");
            c.show();
            Console.WriteLine();

            c = c - b;
            Console.Write("Result of \"c - b\": ");
            c.show();
            Console.WriteLine();
 
            Console.ReadKey();
        }
    }
}


Авторский:
Код

// An example of operator overloading. 
 
using System; 
 
// A three-dimensional coordinate class. 
class ThreeD { 
  int x, y, z; // 3-D coordinates   
 
  public ThreeD() { x = y = z = 0; } 
  public ThreeD(int i, int j, int k) { x = i; y = j; z = k; } 
 
  // Overload binary +. 
  public static ThreeD operator +(ThreeD op1, ThreeD op2) 
  { 
    ThreeD result = new ThreeD(); 
 
    /* This adds together the coordinates of the two points 
       and returns the result. */ 
    result.x = op1.x + op2.x; // These are integer additions 
    result.y = op1.y + op2.y; // and the + retains its original 
    result.z = op1.z + op2.z; // meaning relative to them. 
 
    return result; 
  } 
 
  // Overload binary -. 
  public static ThreeD operator -(ThreeD op1, ThreeD op2) 
  { 
    ThreeD result = new ThreeD(); 
 
    /* Notice the order of the operands. op1 is the left 
       operand and op2 is the right. */ 
    result.x = op1.x - op2.x; // these are integer subtractions 
    result.y = op1.y - op2.y;  
    result.z = op1.z - op2.z;  
 
    return result; 
  } 
   
  // Show X, Y, Z coordinates. 
  public void show() 
  { 
    Console.WriteLine(x + ", " + y + ", " + z); 
  } 
} 
 
class ThreeDDemo { 
  public static void Main() { 
    ThreeD a = new ThreeD(1, 2, 3); 
    ThreeD b = new ThreeD(10, 10, 10); 
    ThreeD c = new ThreeD(); 
 
    Console.Write("Here is a: "); 
    a.show(); 
    Console.WriteLine(); 
    Console.Write("Here is b: "); 
    b.show(); 
    Console.WriteLine(); 
 
    c = a + b; // add a and b together 
    Console.Write("Result of a + b: "); 
    c.show(); 
    Console.WriteLine(); 
 
    c = a + b + c; // add a, b and c together 
    Console.Write("Result of a + b + c: "); 
    c.show(); 
    Console.WriteLine(); 
 
    c = c - a; // subtract a 
    Console.Write("Result of c - a: "); 
    c.show(); 
    Console.WriteLine(); 
 
    c = c - b; // subtract b 
    Console.Write("Result of c - b: "); 
    c.show(); 
    Console.WriteLine(); 
  } 
}


Если подобная тема уже обсуждалась, прошу ткнуть меня носом, поиском не нашел что-то похожее.
Спасибо всем, за ответы! smile

Автор: semibug 8.10.2011, 09:27
Кажется это из тонких вопросов вкусов и личных предпочтений.
Оба варианта вполне себе читаемы.
Тут как с порядком на столе - завалить хламом, чашками, огрызками яблок - плохо, а куда поставить рамку с фотографией, слева или справа на чистеньком столе, дело личное.
Автоматизировано привести сырцы в нужный вид можно, например, с помощью бесплатного плагина к студии StyleManager. Это на случай работы с чужим кодом.
В разных компаниях могут требоваться определенные стили оформления, и у каждой, кончено, свои аргументы.
От себя могу сказать, что открывающую фигурную скобку ставлю с новой строки, чтобы можно было оперативно закомментировать предшествующую строку с условием. Пробелы после имени функции, до открывающей скобки не ставлю (даже не задумывался почему..).

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)