Refactoring of graph buliding logic