I have always suffered with too many conditionals in some of my methods. The following is a pseudocode/skeleton of one of my method like that:
private List<ReturnType> DoSth(string name = null)
{
List<ReturnType> names = new List<ReturnType>();
for (int i = 0; i < somearray.Length; i++)
{
if (somecondition)
{
if (name == null)
{
//'Add' to list
}
else
{
if (someothercondition)
{
//'Add' to list
}
}
}
}
return names;
}
Actual Code which returns an object filled with Controller and corresponding Action names:
private List<AppController> GetControllerActions(string ControllerName = null)
{
Type[] typelist = Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "Project.Web.Controllers", StringComparison.Ordinal)).ToArray();
List<AppController> names = new List<AppController>();
for (int i = 0; i < typelist.Length; i++)
{
if (typelist[i].BaseType.Name == "Controller")
{
if (ControllerName == null)
{
names.Add(new AppController
{
ControllerName = typelist[i].Name,
ActionName = typelist[i].GetMethods()
.Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
.Select(s => s.Name).ToList()
});
}
else
{
if (typelist[i].Name == ControllerName)
{
names.Add(new AppController
{
ControllerName = typelist[i].Name,
ActionName = typelist[i].GetMethods()
.Where(w => w.ReturnType.BaseType != null && (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult"))
.Select(s => s.Name).ToList()
});
}
}
}
}
return names;
}
As you can see the same Add
code is being repeated twice and the 'Add' code is not an external method and I would prefer not making it one also. I can also provide the actual code if required.
Is there any scope of making this code more concise and compact like you can do with ternary operators for example?