The account of David and Bathsheba's affair was outlined in II Samuel 11. So how could II Samuel 5:18 list their second son, Solomon, way before the affair had taken place? Is the book out of sequence?
II Samuel, like many books in the Bible, is a historical account. This does not mean it was written as the events took place. Most often the accounts were written several years after the events. At times, the writer includes information because it was a convenient point to pull related items together. Thus, after David conquered Jerusalem, the writer lists out the children born to David while Jerusalem was his capital in II Samuel 5:13-16. Exactly when these children were born is not mentioned.
A similar example is in John 2:19-22, "Jesus answered them, "Destroy this temple, and in three days I will raise it up." The Jews then said, "It took forty-six years to build this temple, and will You raise it up in three days?" But He was speaking of the temple of His body. So when He was raised from the dead, His disciples remembered that He said this; and they believed the Scripture and the word which Jesus had spoken" (John 2:19-22). The last statement is out of chronological sequence with the immediate context. The disciples did not realize what Jesus meant until three years later, but this was a good spot to discuss it because the topic was brought up.
John is in chronological order, but there is inserted commentary in the text as needed. II Samuel is also in chronological order, but additional information is sometimes added to give a fuller account.