Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create multiple overloads of CRUD methods? [closed]

If I have a class which represent a mapping to a specific table in my db in somehow. This class contains about 30 properties.

I have created the CRUD Methods.

And find myself need to another (UPDATE) method which should update just two fields.

What should I do in a good manner with simple example?

  1. Using my exist method, Filling the whole object and update all the fields including my intended two fields? (Useless work)

  2. Create static Method with another name (but I want to keep my method name because it's expressive)! And takes two parameters?

like image 337
Anyname Donotcare Avatar asked Apr 22 '15 14:04

Anyname Donotcare


4 Answers

I would go by by creating two separate interface and create overloaded functions for each interface. I would group properties based on usage, like I want status to be updated some time separate from other common properties.

public interface ICommonProperties
{
   public string P1{get; set;}
   public string P2{get; set;}
   public string P3{ get; set; }
}
public interface ITrackable
{
   public string Status{get; set;}
}
public class FinalClass : ICommonProperties, ITrackable
{
   public string P1{get; set;}
   public string P2{get; set;}
   public string P3{get; set;}
   public string Status{get; set;}
}

public class FinalClassOperations
{
   public void Update(FinalClass finalClassInstance) { }; //Updates everything
   public void Update(ICommonProperties finalClassInstance) { }; //Updates only ICommonProperties
   public void Update(ITrackable finalClassInstance) { }; //updates only Status.
}

Additionally, if you want you can create a separate class for just updating the status, and that would still fit in:

public class Tracker : ITrackable{
    public string Status{get; set;}
}

But yes, if the two properties cannot be separated out logically, I would not do that and keep them together.

like image 132
Guanxi Avatar answered Sep 19 '22 17:09

Guanxi


I would suggest to follow your second option but there is no need to change the name as the number of method parameter will be different on both it's Let's as walk into few example

I will try to create an similar situation, I hope it's your situation. you can clarify if i got wrongly the question.

CLASSES AND METHOD

/// <summary>
/// CLass to store properties related to database
/// </summary>
class ObjectoA
{
   public string A{get; set;}
   public string B{get; set;}
   public string C{ get; set; }
}

/// <summary>
/// class to call method to update.
/// 
/// </summary>
class ObjectB
{
    /// <summary>
    /// update method.
    /// I would go with this solution.
    /// optionlay you can call the method which receive parameter of object
    /// </summary>
    /// <param name="A"> Object with properties mapped to database</param>
    /// <param name="updatetwoproperties">Optional paramneter to decide which update to run.
    /// the default value should be for update  that run most. For your need if you want to create an update methods for other
    /// two sets of parameter a suggest you create an Enum and pass this enum as optional parameter instead of bool parameter or you
    /// can pass as string and map each string value to specific update inside. IF YOU NEED EXAMPLE
    /// REPLAY ON COMMENTS</param>
    /// <returns></returns>
    public bool update(ObjectoA A, bool updatetwoproperties=false)
    {
        //method implementation
        if (updatetwoproperties)
        {
            //implement a update to all field
        }
        else
        {
            //implement update just to two field
        }
        return true;
    }

    /// <summary>
    /// update method based on parameter to update
    /// </summary>
    /// <param name="a">this properties is mapped on database</param>
    /// <param name="b">this propertie is mapped on database</param>
    /// <returns></returns>
    public bool update(string a, string b)
    {
        //method implementation e validate the return value
        return true;
    }       
}

/// <summary>
/// I don't suggest to use this solution because
/// it will add a method on string type while this method isn't related to string
/// I just added here as a workaround for you.
/// </summary>

public static class ObjectC { public static bool update(this string a, string b) { //implementation of update and validate the return value return true; } }

CALLING METHOD AND EXPLANATION

    static void Main(string[] args)
    {
                    ObjectB B = new ObjectB(); //Class with methods
        ObjectoA A = new ObjectoA(); //object with properties

        #region Using Optional parameter to decide which update to run
        //Calling a method to update all columns
        B.update(A);
        //Calling a method to update two columns
        B.update(A, true); 
        #endregion

        #region Using polymorphism to update
        //Calling a method to update all columns
        B.update(A);
        //Update only using paramenter
        B.update(A.B, A.C); 
        #endregion

        //NOT RECOMMEND BECAUSE THIS UPDATE ISN'T RELATED TO STRING TYPE
        #region Using extension method to update
        //Calling a method to update all columns
        B.update(A);
        //using the extension method on variable type
        A.B.update(A.C); 
        #endregion

        //WE COULD USE EXTENSION METHOD ON YOUR OBJECT BUT IT WILL FAIL BECAUSE WE ALREADY AS UPDATE METHOD ON CLASS
        //IF YOU WANT TO SEE HOW JUST REPLAY
    }

I SUGGEST YOU ADD OPTIONAL PARAMETER ON YOUR METHOD TO DECIDE WHICH UPDATE TO USE

like image 29
Felicio Balane Avatar answered Sep 19 '22 17:09

Felicio Balane


It depends on what your priorities are on the project: using your already existing update method is gonna update everything all the time, incressing traffic, IO and process time (validation and so on...) If you're on a project where properties are timestamped, they would be updated even if the value hasn't really changed...

If you don't mind about all this, use your update() method all the time.

My personnal POV is: create a new method (with an explicit name). This will same process time from now on and thinking time in 2 years when you'll have to change this class ;)

like image 26
gfd Avatar answered Sep 18 '22 17:09

gfd


I don't know if this is what you should do necessarily, but here's something you could do: Create a SetAll or SetMany or whatever method where you pass in another instance of your class (source). Check each property and if it's non-null, you set the destination object's property value to the source object's property value. Note that this tactic will depend on nullable types, and assumes you can ignore null values passed into a new setter method. Here's an illustration:

using System;

namespace BlogPartialUpdateTrick
{
    public class SomeClass
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int? HeightInches { get; set; }
        public DateTime? Dob { get; set; }

        public void SetAll(SomeClass source)
        {
            this.FirstName = source.FirstName ?? this.FirstName;
            this.LastName = source.LastName ?? this.LastName;
            this.HeightInches = source.HeightInches ?? this.HeightInches;
            this.Dob = source.Dob ?? this.Dob;
        }

        public override string ToString()
        {
            return String.Format("fn: {0}, ln: {1}, height: {2}, DOB: {3}", FirstName ?? String.Empty, LastName ?? String.Empty, 
                HeightInches.HasValue ? HeightInches.Value.ToString() : "null", Dob.HasValue ? Dob.Value.ToShortDateString() : "null" );
        }
    }
}

In this first code sample, We have my spiffy class SomeClass. It's got 4 properties, all of which are nullable. The noteworthy part of this class is the SetAllMethod where I can pass in a source object which is also of type SomeClass. It sets this instance's property values to the values passed in the source parameter, but only if they're non-null. Here's a 2nd code blurb where I'm using this stuff:

using System;
using System.Windows.Forms;

namespace BlogPartialUpdateTrick
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var destination = new SomeClass() { FirstName = "Freddy", LastName = "Fingers", Dob = DateTime.Parse("01/01/1970"), HeightInches = 72 };
            var source = new SomeClass() { FirstName = null, LastName="Flippers", Dob = null, HeightInches = 80 };
            destination.SetAll(source);
            MessageBox.Show(destination.ToString());
        }
    }
}

Create a destination object, a source object, call the new method, voila! output is this:

"fn: Freddy, ln: Flippers, height: 80, DOB: 1/1/1970"

like image 30
Peeticus Avatar answered Sep 20 '22 17:09

Peeticus