001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2014 Oliver Burn 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018//////////////////////////////////////////////////////////////////////////////// 019package com.puppycrawl.tools.checkstyle.checks.metrics; 020 021import java.math.BigInteger; 022 023import com.puppycrawl.tools.checkstyle.api.DetailAST; 024import com.puppycrawl.tools.checkstyle.api.TokenTypes; 025 026/** 027 * Checks cyclomatic complexity against a specified limit. The complexity is 028 * measured by the number of "if", "while", "do", "for", "?:", "catch", 029 * "switch", "case", "&&" and "||" statements (plus one) in the body of 030 * the member. It is a measure of the minimum number of possible paths through 031 * the source and therefore the number of required tests. Generally 1-4 is 032 * considered good, 5-7 ok, 8-10 consider re-factoring, and 11+ re-factor now! 033 * 034 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> 035 * @author Oliver Burn 036 */ 037public class CyclomaticComplexityCheck 038 extends AbstractComplexityCheck 039{ 040 /** default allowed complexity */ 041 private static final int DEFAULT_VALUE = 10; 042 043 /** Create an instance. */ 044 public CyclomaticComplexityCheck() 045 { 046 super(DEFAULT_VALUE); 047 } 048 049 @Override 050 public int[] getDefaultTokens() 051 { 052 return new int[] { 053 TokenTypes.CTOR_DEF, 054 TokenTypes.METHOD_DEF, 055 TokenTypes.INSTANCE_INIT, 056 TokenTypes.STATIC_INIT, 057 TokenTypes.LITERAL_WHILE, 058 TokenTypes.LITERAL_DO, 059 TokenTypes.LITERAL_FOR, 060 TokenTypes.LITERAL_IF, 061 TokenTypes.LITERAL_CASE, 062 TokenTypes.LITERAL_CATCH, 063 TokenTypes.QUESTION, 064 TokenTypes.LAND, 065 TokenTypes.LOR, 066 }; 067 } 068 069 @Override 070 protected final void visitTokenHook(DetailAST ast) 071 { 072 incrementCurrentValue(BigInteger.ONE); 073 } 074 075 @Override 076 protected final String getMessageID() 077 { 078 return "cyclomaticComplexity"; 079 } 080}