Search code examples
c#design-patternsremove-if

Return same Parameter On Some Objects By type


I want that remove my if what can I do?

I retrieve my data from database and in all of type they have some field named IsVerified

is anyway that i can remove ifs???

private bool CheckDetailsAreVerified(type)
    {
        bool isVerified;

        if (type == sometype1)
        {
            isVerified = this.retrieveFromDB<obj1>()
            .somcondition()
            .All(it => it.IsVerified);
        }
        else if (type == sometype2)
        {
            isVerified = this.retrieveFromDB<obj2>()
            .somcondition()
            .All(it => it.IsVerified);
        }
        else if (type == sometype3)
        {
            isVerified = this.retrieveFromDB<obj3>()
            .somcondition()
            .All(it => it.IsVerified);
        }
        else if (type == sometype4)
        {
            isVerified = this.retrieveFromDB<obj4>()
            .somcondition()
            .All(it => it.IsVerified);
        }

        return isVerified;
    }

Solution

  • Use Reflection. Method name and typeName must be equals

    public bool CheckDetailsAreVerified(string typeName)
    {
       //"this" == CurrentClass
       var verified = typeof(CurrentClass).GetMethod(typeName).Invoke(null, null);
       return Convert.ToBoolean(verified);
    }
    
    private bool Type1()
    {
       return isVerified = this.retrieveFromDB<obj1>()
                .somcondition()
                .All(it => it.IsVerified);
    }
    
    private bool Type2()
    {
       return isVerified = this.retrieveFromDB<obj2>()
                .somcondition()
                .All(it => it.IsVerified);
    }
    //type3, type4...etc
    

    If you need params to method:

    public bool CheckDetailsAreVerified(string typeName)
    {
       //"this" == CurrentClass
       var verified = typeof(CurrentClass).GetMethod(typeName).Invoke(null, 
                                                                  new object[] 
                                                                  { 
                                                                  myIntList
                                                                  });
       return Convert.ToBoolean(verified);
    }
    
    private bool TypeN(List<int> value)
    {
       return isVerified = this.retrieveFromDB<obj1>()
                .somcondition()
                .All(it => it.IsVerified);
    }