001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 the original author or authors.
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////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.coding;
021
022import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
023import com.puppycrawl.tools.checkstyle.api.DetailAST;
024import com.puppycrawl.tools.checkstyle.api.TokenTypes;
025
026/**
027 * <p>
028 * Checks that the clone method is not overridden from the
029 * Object class.
030 * </p>
031 *
032 * <p>Rationale: The clone method relies on strange/hard to follow rules that
033 * do not work it all situations.  Consequently, it is difficult to
034 * override correctly.  Below are some of the rules/reasons why the clone
035 * method should be avoided.
036 *
037 * <ul>
038 * <li>
039 * Classes supporting the clone method should implement the Cloneable
040 * interface but the Cloneable interface does not include the clone method.
041 * As a result, it doesn't enforce the method override.
042 * </li>
043 * <li>
044 * The Cloneable interface forces the Object's clone method to work
045 * correctly. Without implementing it, the Object's clone method will
046 * throw a CloneNotSupportedException.
047 * </li>
048 * <li>
049 * Non-final classes must return the object returned from a call to
050 * super.clone().
051 * </li>
052 * <li>
053 * Final classes can use a constructor to create a clone which is different
054 * from non-final classes.
055 * </li>
056 * <li>
057 * If a super class implements the clone method incorrectly all subclasses
058 * calling super.clone() are doomed to failure.
059 * </li>
060 * <li>
061 * If a class has references to mutable objects then those object
062 * references must be replaced with copies in the clone method
063 * after calling super.clone().
064 * </li>
065 * <li>
066 * The clone method does not work correctly with final mutable object
067 * references because final references cannot be reassigned.
068 * </li>
069 * <li>
070 * If a super class overrides the clone method then all subclasses must
071 * provide a correct clone implementation.
072 * </li>
073 * </ul>
074 *
075 * <p>Two alternatives to the clone method, in some cases, is a copy constructor
076 * or a static factory method to return copies of an object. Both of these
077 * approaches are simpler and do not conflict with final fields. They do not
078 * force the calling client to handle a CloneNotSupportedException.  They also
079 * are typed therefore no casting is necessary. Finally, they are more
080 * flexible since they can take interface types rather than concrete classes.
081 *
082 * <p>Sometimes a copy constructor or static factory is not an acceptable
083 * alternative to the clone method.  The example below highlights the
084 * limitation of a copy constructor (or static factory). Assume
085 * Square is a subclass for Shape.
086 *
087 * <pre>
088 * Shape s1 = new Square();
089 * System.out.println(s1 instanceof Square); //true
090 * </pre>
091 * ...assume at this point the code knows nothing of s1 being a Square
092 *    that's the beauty of polymorphism but the code wants to copy
093 *    the Square which is declared as a Shape, its super type...
094 *
095 * <pre>
096 * Shape s2 = new Shape(s1); //using the copy constructor
097 * System.out.println(s2 instanceof Square); //false
098 * </pre>
099 * The working solution (without knowing about all subclasses and doing many
100 * casts) is to do the following (assuming correct clone implementation).
101 *
102 * <pre>
103 * Shape s2 = s1.clone();
104 * System.out.println(s2 instanceof Square); //true
105 * </pre>
106 * Just keep in mind if this type of polymorphic cloning is required
107 * then a properly implemented clone method may be the best choice.
108 *
109 * <p>Much of this information was taken from Effective Java:
110 * Programming Language Guide First Edition by Joshua Bloch
111 * pages 45-52.  Give Bloch credit for writing an excellent book.
112 * </p>
113 *
114 * <p>This check is almost exactly the same as the {@link NoFinalizerCheck}
115 *
116 * @author Travis Schneeberger
117 * @see Object#clone()
118 */
119public class NoCloneCheck extends AbstractCheck {
120
121    /**
122     * A key is pointing to the warning message text in "messages.properties"
123     * file.
124     */
125    public static final String MSG_KEY = "avoid.clone.method";
126
127    @Override
128    public int[] getDefaultTokens() {
129        return getAcceptableTokens();
130    }
131
132    @Override
133    public int[] getAcceptableTokens() {
134        return new int[] {TokenTypes.METHOD_DEF};
135    }
136
137    @Override
138    public int[] getRequiredTokens() {
139        return getAcceptableTokens();
140    }
141
142    @Override
143    public void visitToken(DetailAST aAST) {
144        final DetailAST mid = aAST.findFirstToken(TokenTypes.IDENT);
145        final String name = mid.getText();
146
147        if ("clone".equals(name)) {
148
149            final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS);
150            final boolean hasEmptyParamList =
151                !params.branchContains(TokenTypes.PARAMETER_DEF);
152
153            if (hasEmptyParamList) {
154                log(aAST.getLineNo(), MSG_KEY);
155            }
156        }
157    }
158}