Właściwości, modyfikacja poprzez pola - pytanie

0

Cześć wszystkim. Czy modyfikacja wartości pól obiektu w stylu pkt.x = np. 50 jest poprawną praktyką?

    public struct Punkt
    {
        private int _x;
        private int _y;

        public Punkt(int x, int y)
        {
            _x = x;
            _y = y;
        }

        public int x
        {
            get
            {
                return _x;
            }
            set
            {
                _x = value;
            }
        }

        public int y
        {
            get
            {
                return _y;
            }
            set
            {
                _y = value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Punkt pkt = new Punkt(20, 30);
            Console.WriteLine(pkt.x);
            pkt.x = 50;
            Console.WriteLine(pkt.x);
        }
    }
1

Jest, ponieważ często bywa tak, że nie wszystkie dane są dostępne podczas konstrukcji obiektu.

0

Ale aby w pełni korzystać z dobrych praktyk OOP lepszym rozwiązaniem byłoby ustawienie prywatnego settera dla X i utworzenie metody SetX(int x), która to wewnętrznie w obiekcie ustawi i zabezpieczy np przed tym, aby obiekt był zawsze w poprawnym stanie (np sprawdził czy zmienna x nie jest ujemna).

2

@XardasLord: Jakby setter nie mógł tego zrobić.

1
grzesiek51114 napisał(a):

@XardasLord: Jakby setter nie mógł tego zrobić.

oby tylko setter pod spodem nie pobierał pół internetu i strzelał do 50 baz

0
WeiXiao napisał(a):
grzesiek51114 napisał(a):

@XardasLord: Jakby setter nie mógł tego zrobić.

oby tylko setter pod spodem nie pobierał pół internetu i strzelał do 50 baz

Dokładnie :) @grzesiek51114 ogólnie przykład który został podany w zupełności można obsłużyć przez pole i settera i na potrzeby tego przykładu jest to wystarczające. Ale już jakaś bardziej złożona logika to lepiej mieć właściwości i obsługę zmiany stanu obiektu realizować przez metody.

2

Dobra praktyką jest używanie automatycznych właściwości tam gdzie jest to możliwe i nieużywanie struct tam gdzie nie jest to konieczne. Poza tym dobre praktyki mają to do siebie, że sens ich stosowania widać na kodzie, który coś robi i jest dłuższy niż parę linii, klasa Punkt nie spełnia tych wymagań.

0

@WeiXiao: @XardasLord co Wy chcecie walidowac pobieraniem połowy internetu w klasie Punkt? To nowa forma trollingu?

1

@Saalin:

za to ignorowanie kontekstu to stara forma trollingu :D

Ja odnosiłem się do @grzesiek51114 który odnosił się do @XardasLord który pisał ogólnie o OOP.

2

@Saalin: Akurat tutaj struct idealnie pasuje.

1

@Saalin:

Lol, nie.

Dlaczego nie? Wszystkie składowe klasy są typu wartościowego, itp. Czemu to niby miałoby nie być strukturą?

2

Tutaj struct idealnie pasuje, tyle że Punkt powinien być niemutowalny. Kod w obecnej postaci nie ma większego sensu.

2

Jeżeli get lub set nie wykonuje dodatkowych operacji poza wyciągnięciem ze zmiennej i przypisania do zmiennej w przypadku set, to można zastosować skrótowy zapis np.

public int X { get; set; }

http://johnstejskal.com/wp/getters-setters-and-auto-properties-in-c-explained-get-set/

Sam set w zasadzie nie jest tu potrzebny, skoro konstruktor uzupełnia dane.

0
namespace System.Drawing
 {
    using System.Runtime.Serialization.Formatters;
 
    using System.Diagnostics;
 
    using System;
    using System.IO;
    using Microsoft.Win32;
    using System.ComponentModel;
    using System.Drawing.Internal;
    using System.Diagnostics.CodeAnalysis;    
    using System.Globalization;

    [
    TypeConverterAttribute(typeof(PointConverter)),
    ]
    [Serializable]
    [System.Runtime.InteropServices.ComVisible(true)]
    [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates")]
    public struct Point {
 
    
        public static readonly Point Empty = new Point();
 
        private int x;
        private int y;
 
        
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
 
  
        public Point(Size sz) {
            this.x = sz.Width;
            this.y = sz.Height;
        }
 
   
        public Point(int dw) {
            unchecked {
                this.x = (short)LOWORD(dw);
                this.y = (short)HIWORD(dw);
            }
        }
 
     
        [Browsable(false)]
        public bool IsEmpty {
            get {
                return x == 0 && y == 0;
            }
        }
 
    
        public int X {
            get {
                return x;
            }
            set {
                x = value;
            }
        }
 
     
        public int Y {
            get {
                return y;
            }
            set {
                y = value;
            }
        }
 
      
        public static implicit operator PointF(Point p) {
            return new PointF(p.X, p.Y);
        }
 

        public static explicit operator Size(Point p) {
            return new Size(p.X, p.Y);
        }
 
      
        public static Point operator +(Point pt, Size sz) {
            return Add(pt, sz);
        }
 
       
        public static Point operator -(Point pt, Size sz) {
            return Subtract(pt, sz);
        }
 
   
        public static bool operator ==(Point left, Point right) {
            return left.X == right.X && left.Y == right.Y;
        }
        
    
        public static bool operator !=(Point left, Point right) {
            return !(left == right);
        }
      
        public static Point Add(Point pt, Size sz) {
            return new Point(pt.X + sz.Width, pt.Y + sz.Height);
        }
 
       
        public static Point Subtract(Point pt, Size sz) {
            return new Point(pt.X - sz.Width, pt.Y - sz.Height);
        }
 

        public static Point Ceiling(PointF value) {
            return new Point((int)Math.Ceiling(value.X), (int)Math.Ceiling(value.Y));
        }
 
  
        public static Point Truncate(PointF value) {
            return new Point((int)value.X, (int)value.Y);
        }
 
   
        public static Point Round(PointF value) {
            return new Point((int)Math.Round(value.X), (int)Math.Round(value.Y));
        }
 

        public override bool Equals(object obj) {
            if (!(obj is Point)) return false;
            Point comp = (Point)obj;
         
            return comp.X == this.X && comp.Y == this.Y;
        }
 

        public override int GetHashCode() {
            return unchecked(x ^ y);
        }
        
      
        public void Offset(int dx, int dy) {
            X += dx;
            Y += dy;
        }
 
    
        public void Offset(Point p) {
            Offset(p.X, p.Y);
        }
 
        public override string ToString() {
            return "{X=" + X.ToString(CultureInfo.CurrentCulture) + ",Y=" + Y.ToString(CultureInfo.CurrentCulture) + "}";
        }
 
        private static int HIWORD(int n) {
            return(n >> 16) & 0xffff;
        }
 
        private static int LOWORD(int n) {
            return n & 0xffff;
        }
    }
}
0
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Runtime.InteropServices;
using MS.Internal;
using MS.Internal.WindowsBase;
using System.Diagnostics;
using System.Windows.Markup;
using System.Windows.Converters;
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;

namespace System.Windows
{
 
    public struct Point : IFormattable
    {
   
        public Point(double x, double y)
        {
            _x = x;
            _y = y;
        }

        public void Offset(double offsetX, double offsetY)
        {
            _x += offsetX;
            _y += offsetY;
        }


        public static Point operator +(Point point, Vector vector)
        {
            return new Point(point._x + vector._x, point._y + vector._y);
        }

        public static Point Add(Point point, Vector vector)
        {
            return new Point(point._x + vector._x, point._y + vector._y);
        }

        public static Point operator -(Point point, Vector vector)
        {
            return new Point(point._x - vector._x, point._y - vector._y);
        }


        public static Point Subtract(Point point, Vector vector)
        {
            return new Point(point._x - vector._x, point._y - vector._y);
        }

        public static Vector operator -(Point point1, Point point2)
        {
            return new Vector(point1._x - point2._x, point1._y - point2._y);
        }

 
        public static Vector Subtract(Point point1, Point point2)
        {
            return new Vector(point1._x - point2._x, point1._y - point2._y);
        }

        public static Point operator *(Point point, Matrix matrix)
        {
            return matrix.Transform(point);
        }

       
        public static Point Multiply(Point point, Matrix matrix)
        {
            return matrix.Transform(point);
        }

        public static explicit operator Size(Point point)
        {
            return new Size(Math.Abs(point._x), Math.Abs(point._y));
        }

     
        public static explicit operator Vector(Point point)
        {
            return new Vector(point._x, point._y);
        }


        public static bool operator ==(Point point1, Point point2)
        {
            return point1.X == point2.X &&
                   point1.Y == point2.Y;
        }


        public static bool operator !=(Point point1, Point point2)
        {
            return !(point1 == point2);
        }

        public static bool Equals(Point point1, Point point2)
        {
            return point1.X.Equals(point2.X) &&
                   point1.Y.Equals(point2.Y);
        }

        public override bool Equals(object o)
        {
            if ((null == o) || !(o is Point))
            {
                return false;
            }

            Point value = (Point)o;
            return Point.Equals(this, value);
        }


        public bool Equals(Point value)
        {
            return Point.Equals(this, value);
        }

        public override int GetHashCode()
        {
      
            return X.GetHashCode() ^
                   Y.GetHashCode();
        }

        public static Point Parse(string source)
        {
            IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;

            TokenizerHelper th = new TokenizerHelper(source, formatProvider);

            Point value;

            String firstToken = th.NextTokenRequired();

            value = new Point(
                Convert.ToDouble(firstToken, formatProvider),
                Convert.ToDouble(th.NextTokenRequired(), formatProvider));

            th.LastTokenRequired();

            return value;
        }

    
        public double X
        {
            get
            {
                return _x;
            }

            set
            {
                _x = value;
            }

        }


        public double Y
        {
            get
            {
                return _y;
            }

            set
            {
                _y = value;
            }

        }

        public override string ToString()
        {

            return ConvertToString(null , null);
        }

  
        public string ToString(IFormatProvider provider)
        {

        
            return ConvertToString(null, provider);
        }

    
        string IFormattable.ToString(string format, IFormatProvider provider)
        {

            return ConvertToString(format, provider);
        }

 
        internal string ConvertToString(string format, IFormatProvider provider)
        {
          
            char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider);
            return String.Format(provider,
                                 "{1:" + format + "}{0}{2:" + format + "}",
                                 separator,
                                 _x,
                                 _y);
        }

        internal double _x;
        internal double _y;

    }


    [Serializable]
    [TypeConverter(typeof(VectorConverter))]
    [ValueSerializer(typeof(VectorValueSerializer))]
    public struct Vector : IFormattable
    {

        public static bool operator ==(Vector vector1, Vector vector2)
        {
            return vector1.X == vector2.X &&
                   vector1.Y == vector2.Y;
        }

        public static bool operator !=(Vector vector1, Vector vector2)
        {
            return !(vector1 == vector2);
        }

        public static bool Equals(Vector vector1, Vector vector2)
        {
            return vector1.X.Equals(vector2.X) &&
                   vector1.Y.Equals(vector2.Y);
        }

        public override bool Equals(object o)
        {
            if ((null == o) || !(o is Vector))
            {
                return false;
            }

            Vector value = (Vector)o;
            return Vector.Equals(this, value);
        }


        public bool Equals(Vector value)
        {
            return Vector.Equals(this, value);
        }

        public override int GetHashCode()
        {
            return X.GetHashCode() ^
                   Y.GetHashCode();
        }

        public static Vector Parse(string source)
        {
            IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;

            TokenizerHelper th = new TokenizerHelper(source, formatProvider);

            Vector value;

            String firstToken = th.NextTokenRequired();

            value = new Vector(
                Convert.ToDouble(firstToken, formatProvider),
                Convert.ToDouble(th.NextTokenRequired(), formatProvider));

            th.LastTokenRequired();

            return value;
        }

        public double X
        {
            get
            {
                return _x;
            }

            set
            {
                _x = value;
            }

        }

        public double Y
        {
            get
            {
                return _y;
            }

            set
            {
                _y = value;
            }

        }

        public override string ToString()
        {

            return ConvertToString(null /* format string */, null /* format provider */);
        }

        public string ToString(IFormatProvider provider)
        {

            return ConvertToString(null /* format string */, provider);
        }


        string IFormattable.ToString(string format, IFormatProvider provider)
        {

            return ConvertToString(format, provider);
        }

        internal string ConvertToString(string format, IFormatProvider provider)
        {

            char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider);
            return String.Format(provider,
                                 "{1:" + format + "}{0}{2:" + format + "}",
                                 separator,
                                 _x,
                                 _y);
        }

        internal double _x;
        internal double _y;

            public Vector(double x, double y)
            {
                _x = x;
                _y = y;
            }

            public double Length
            {
                get
                {
                    return Math.Sqrt(_x * _x + _y * _y);
                }
            }
            public double LengthSquared
            {
                get
                {
                    return _x * _x + _y * _y;
                }
            }

            public void Normalize()
            {
                this /= Math.Max(Math.Abs(_x), Math.Abs(_y));
                this /= Length;
            }

            public static double CrossProduct(Vector vector1, Vector vector2)
            {
                return vector1._x * vector2._y - vector1._y * vector2._x;
            }

            public static double AngleBetween(Vector vector1, Vector vector2)
            {
                double sin = vector1._x * vector2._y - vector2._x * vector1._y;
                double cos = vector1._x * vector2._x + vector1._y * vector2._y;

                return Math.Atan2(sin, cos) * (180 / Math.PI);
            }

            public static Vector operator -(Vector vector)
            {
                return new Vector(-vector._x, -vector._y);
            }

            public void Negate()
            {
                _x = -_x;
                _y = -_y;
            }

            public static Vector operator +(Vector vector1, Vector vector2)
            {
                return new Vector(vector1._x + vector2._x,
                                  vector1._y + vector2._y);
            }

            public static Vector Add(Vector vector1, Vector vector2)
            {
                return new Vector(vector1._x + vector2._x,
                                  vector1._y + vector2._y);
            }

            public static Vector operator -(Vector vector1, Vector vector2)
            {
                return new Vector(vector1._x - vector2._x,
                                  vector1._y - vector2._y);
            }

            public static Vector Subtract(Vector vector1, Vector vector2)
            {
                return new Vector(vector1._x - vector2._x,
                                  vector1._y - vector2._y);
            }

            public static Point operator +(Vector vector, Point point)
            {
                return new Point(point._x + vector._x, point._y + vector._y);
            }

            public static Point Add(Vector vector, Point point)
            {
                return new Point(point._x + vector._x, point._y + vector._y);
            }

            public static Vector operator *(Vector vector, double scalar)
            {
                return new Vector(vector._x * scalar,
                                  vector._y * scalar);
            }

            public static Vector Multiply(Vector vector, double scalar)
            {
                return new Vector(vector._x * scalar,
                                  vector._y * scalar);
            }

            public static Vector operator *(double scalar, Vector vector)
            {
                return new Vector(vector._x * scalar,
                                  vector._y * scalar);
            }

            public static Vector Multiply(double scalar, Vector vector)
            {
                return new Vector(vector._x * scalar,
                                  vector._y * scalar);
            }

            public static Vector operator /(Vector vector, double scalar)
            {
                return vector * (1.0 / scalar);
            }

            public static Vector Divide(Vector vector, double scalar)
            {
                return vector * (1.0 / scalar);
            }

            public static Vector operator *(Vector vector, Matrix matrix)
            {
                return matrix.Transform(vector);
            }

        
            public static Vector Multiply(Vector vector, Matrix matrix)
            {
                return matrix.Transform(vector);
            }

            public static double operator *(Vector vector1, Vector vector2)
            {
                return vector1._x * vector2._x + vector1._y * vector2._y;
            }

       
            public static double Multiply(Vector vector1, Vector vector2)
            {
                return vector1._x * vector2._x + vector1._y * vector2._y;
            }

            public static double Determinant(Vector vector1, Vector vector2)
            {
                return vector1._x * vector2._y - vector1._y * vector2._x;
            }

            
            public static explicit operator Size(Vector vector)
            {
                return new Size(Math.Abs(vector._x), Math.Abs(vector._y));
            }

            public static explicit operator Point(Vector vector)
            {
                return new Point(vector._x, vector._y);
            }
           
        }
    }

1 użytkowników online, w tym zalogowanych: 0, gości: 1