3

I have an app where every object is checked based on various types of business rules. For this, i used multiple nested if-else statement which was done in one class. I am not happy with this situation because it became hard to manage.

I tried to add some design pattern such as chain of responsibility and specification but i still used if-else statement while applying these. I am stuck and i don't know which way to go. Here is pseudocode about business logic;

if name not in nameList
    Obj newObj = getObjByName(obj.name)
    if newObj = null
        error()
    else        
        Status newStatus = getStatusObj(obj.name, obj.status)
        if newStatus = sold 
            success()
        else if not newObj.type = obj.type
            error()
        else
            Transport trans = getTransByType(obj.type)
            if not trans = null
                success()
            else
                if not newObj.count < 10
                    success()
                else
                    error()             
        
else
    error()
  • 1
    Has any of the closer tried to apply the answer of that "duplicate" to the example here? The prerequisites of the accepted answer seem somewhat irrelevant here, since it assumes the conditions can be evaluated on beforehand, whereas here the conditions can only be evaluated if the previous steps are ok (e.g you can't get the transport if you don't know the type, and you don't know the type if you couldn't find the object in first place, etc...). – Christophe Jan 24 '21 at 15:28
  • I tried to [Karnaugh table](https://en.wikipedia.org/wiki/Karnaugh_map) to be simplified code but as you said steps are connected each other so it doesn't help me. – Arife Kübra Jan 24 '21 at 17:20
  • 2
    3 options: 1) avoid nesting by decomposing every inner step into a function; 2) use an ok code, and structure the flow of control as a linear succession of `if ok ...` and factorize the error at the end if not ok; 3) rule engine as explained [here](https://softwareengineering.stackexchange.com/a/376438/209774) and [here](https://softwareengineering.stackexchange.com/a/378873/209774). However 3) requires feasibility of 1. – Christophe Jan 24 '21 at 18:03
  • 1
    Reverse the problem. Most of that `if` tree is for validating its okay to ask a question. Ask the question instead, have its implementation ask its own questions, etc... – Kain0_0 Jan 25 '21 at 04:36
  • 1
    There seem to be too many else's. – gnasher729 Jan 25 '21 at 17:21
  • You could make everyone’s head explode by using “goto” to jump to a label “success” or a label “error”. The code actually becomes very readable. – gnasher729 Jan 25 '21 at 19:07
  • I think, instead of considering the features of an object, I need to deal with the rules so that, it can be easier to manage rules. I looked at it from a very narrow perspective, as I looked at the comments, my point of view expanded, thanks all. – Arife Kübra Jan 26 '21 at 19:15

0 Answers0