Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Long switch case

ID: cpp/long-switchKind: problemSecurity severity: Severity: recommendationPrecision: highTags:   - maintainability   - readabilityQuery suites:   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds switch statements that have too much code in their cases. Long case statements often lead to large amounts of nesting, adding to the difficulty of understanding what the code actually does. Consider wrapping the code for each case in a function and just using the switch statement to invoke the appropriate function in each case.

The indicated switch statement has a case that is more than 30 lines long.

Recommendation

Consider creating a separate function for the code in the long case statement.

Example

//This switch statement has long case statements, and can become difficult to//read as the processing for each message type becomes more complexswitch(message_type){caseCONNECT:_state=CONNECTING;intmessage_id=message_get_id(message);intsource=connect_get_source(message);//More code here...send(connect_response);break;caseDISCONNECT:_state=DISCONNECTING;intmessage_id=message_get_id(message);intsource=disconnect_get_source(message);//More code here...send(disconnect_response);break;default:log("Invalid message, id : %d",message_get_id(message));}//This is better, as each case is split out to a separate functionswitch(packet_type){caseSTREAM:process_stream_packet(packet);break;caseDATAGRAM:process_datagram_packet(packet);break;default:log("Invalid packet type: %d",packet_type);}

References


[8]ページ先頭

©2009-2025 Movatter.jp