如何优化逻辑避免空值,将API返回结果正确传递到项目对象中
空值规避与API结果传递优化方案
- 前置参数与数据校验
入参先做合法性判断:pair、type字符串判空、amount校验大于0,不符合要求直接返回默认值或抛出业务异常,避免无效执行。遍历匹配交易对订单簿完成后,第一时间判断book是否为null,匹配不到直接中断逻辑,返回「交易对未找到」相关的明确错误,不要继续执行后续访问book属性的逻辑。 - API返回结果预处理
对接第三方API拉取订单簿数据时就做非空兜底:存入全局Program.array前,校验book、Asks、Bids的返回值,API请求失败、返回空值时,要么不存储该条无效数据,要么将Asks/Bids赋值为空列表而非null,从数据源层面避免后续调用踩空。 - 中间变量空值防护
初始化lst时直接赋值为空列表:List<BinanceOrderBookEntry> lst = new List<BinanceOrderBookEntry>();,就算后续匹配type失败,遍历空列表也不会触发空引用异常。额外增加type参数合法值校验,不在asks/bids范围内直接返回错误,避免lst无有效赋值。遍历lst前再判断一次列表长度,为空直接返回兜底值。 - 异常与返回值补全
不要吞掉所有异常:catch块中增加错误日志记录,区分空引用、API调用失败、参数非法等不同错误类型,方便问题排查。补全所有逻辑分支的返回值:当前代码如果循环走完未命中return、或者try块触发异常进入catch,都没有返回值,需要增加兜底返回逻辑。
优化后代码示例
public decimal getBook(string pair, decimal amount, string type, string operation, bool division = true) { // 前置入参校验 if (string.IsNullOrWhiteSpace(pair) || amount <= 0 || string.IsNullOrWhiteSpace(type)) { throw new ArgumentException("非法入参"); } type = type.ToLower(); if (type is not "asks" and not "bids") { throw new ArgumentException("type仅支持asks/bids"); } try { BinanceOrderBook book = null; foreach (var item in Program.array) { var orderItem = item as Program.ClassDetailOrder; if (orderItem?.symbol == pair.ToLower()) { book = orderItem.book; break; } } // book空值校验 if (book == null) { // 可根据业务需求返回默认值或抛异常 return 0; } List<BinanceOrderBookEntry> lst = type == "asks" ? book.Asks : book.Bids; // 列表空值兜底 lst ??= new List<BinanceOrderBookEntry>(); if (lst.Count == 0) { return 0; } decimal[] arrayValue = new decimal[2] { 0, 0 }; decimal orderPrice = 0; decimal orderAmount = 0; decimal totalCost = 0; decimal totalAmount = 0; decimal remaining = amount; decimal cost = 0; foreach (var item in lst) { if (item == null) continue; orderPrice = item.Price; orderAmount = item.Quantity; cost = orderPrice * orderAmount; if (cost < remaining) { remaining -= cost; totalCost += cost; totalAmount += orderAmount; } else { remaining -= amount; totalCost += amount * orderPrice; totalAmount += amount; if (division) { arrayValue[0] = Math.Round(amount / (totalCost / totalAmount), 8); arrayValue[1] = Math.Round(amount / orderPrice, 8); } else { arrayValue[0] = Math.Round((totalCost / totalAmount) * amount, 8); arrayValue[1] = Math.Round(orderPrice * amount, 8); } return arrayValue[0]; } } // 遍历完未满足amount需求的兜底返回 return totalAmount > 0 ? Math.Round(totalCost / totalAmount, 8) : 0; } catch (Exception ex) { // 此处增加日志记录逻辑 Console.WriteLine($"执行出错:{ex.Message}"); return 0; } }
内容的提问来源于stack exchange,提问作者Marlon Money
相关产品推荐
相关产品推荐

