Details
-
Type:
Code Smell Detection
-
Status: Active
-
Resolution: Unresolved
-
Message:Remove this "restriction", and consider "extension" instead.
-
Highlighting:
-
Default Severity:Major
-
Impact:Low
-
Likelihood:High
-
Default Quality Profiles:Sonar way
-
Targeted languages:XML
-
Irrelevant for Languages:ABAP, C#, C, C++, Cobol, CSS, Flex, HTML, Java, JavaScript, Objective-C, PHP, PL/I, PL/SQL, Python, RPG, Swift, VB.Net, VB6
-
Remediation Function:Constant/Issue
-
Constant Cost:15min
-
Analysis Scope:Main Sources, Test Sources
Description
Complex types can be restricted by means of an xs:restriction element. But restriction is anti-inheritance: the derived type has less information than the base type. Further, restriction causes the redefinition of the complex types elements and attributes, which leads to fragility in your XML schema; any change to a super type will require corresponding changes in all restricting subtypes, even those in other schemas. For example, if the base type defines a mandatory "color" element of type xs:int, the restricting type must also define a "color" element whose type cannot be, say, xs:string.
xs:extension, on the other hand, allows the extending element to inherit the base class' elements and add new ones.
Noncompliant Code Example
<xs:complexType name="Fruit> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="color" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="UncoloredFruit"> <xs:complexContent> <xs:restriction base="Fruit"> <!-- Noncompliant --> <xs:sequence> <xs:element name="name" type="xs:string"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType>
Compliant Solution
<xs:complexType name="FruitBase> <xs:sequence> <xs:element name="name" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="ColoredFruit> <xs:sequence> <!-- Bottom-up design, using aggregation --> <xs:element name="base" type="FruitBase"/> <xs:element name="color" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType>