repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/NextFromIterator.java | public class NextFromIterator implements Iterator<String> {
private int position = -1;
private List<String> list = new ArrayList<String>() {{
add("alpha"); add("bravo"); add("charlie"); add("delta"); add("echo"); add("foxtrot");
}};
public boolean hasNext() {
return next() != null; // BAD: Call to 'next'
}
public String next() {
position++;
return position < list.size() ? list.get(position) : null;
}
public void remove() {
// ...
}
public static void main(String[] args) {
NextFromIterator x = new NextFromIterator();
while(x.hasNext()) {
System.out.println(x.next());
}
}
} | 616 | 22.730769 | 88 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/DefaultToString.java | // This class does not have a 'toString' method, so 'java.lang.Object.toString'
// is used when the class is converted to a string.
class WrongPerson {
private String name;
private Date birthDate;
public WrongPerson(String name, Date birthDate) {
this.name =name;
this.birthDate = birthDate;
}
}
public static void main(String args[]) throws Exception {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
WrongPerson wp = new WrongPerson("Robert Van Winkle", dateFormatter.parse("1967-10-31"));
// BAD: The following statement implicitly calls 'Object.toString',
// which returns something similar to:
// WrongPerson@4383f74d
System.out.println(wp);
} | 683 | 31.571429 | 90 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/CallsToRunFinalizersOnExitGood.java | // Instead of using finalizers, define explicit termination methods
// and call them in 'finally' blocks.
class LocalCache {
private Collection<File> cacheFiles = ...;
// Explicit method to close all cacheFiles
public void dispose() {
for (File cacheFile : cacheFiles) {
disposeCacheFile(cacheFile);
}
}
}
void main() {
LocalCache cache = new LocalCache();
try {
// Use the cache
} finally {
// Call the termination method in a 'finally' block, to ensure that
// the cache's resources are freed.
cache.dispose();
}
} | 544 | 22.695652 | 69 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/CallsToStringToString.java | public static void main(String args[]) {
String name = "John Doe";
// BAD: Unnecessary call to 'toString' on 'name'
System.out.println("Hi, my name is " + name.toString());
// GOOD: No call to 'toString' on 'name'
System.out.println("Hi, my name is " + name);
} | 270 | 29.111111 | 57 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/DefaultToStringGood.java | // This class does have a 'toString' method, which is used when the object is
// converted to a string.
class Person {
private String name;
private Date birthDate;
public String toString() {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
return "(Name: " + name + ", Birthdate: " + dateFormatter.format(birthDate) + ")";
}
public Person(String name, Date birthDate) {
this.name =name;
this.birthDate = birthDate;
}
}
public static void main(String args[]) throws Exception {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
Person p = new Person("Eric Arthur Blair", dateFormatter.parse("1903-06-25"));
// GOOD: The following statement implicitly calls 'Person.toString',
// which correctly returns a human-readable string:
// (Name: Eric Arthur Blair, Birthdate: 1903-06-25)
System.out.println(p);
} | 857 | 32 | 84 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/PrintLnArray.java | public static void main(String args[]) {
String[] words = {"Who", "is", "John", "Galt"};
String[][] wordMatrix = {{"There", "is"}, {"no", "spoon"}};
// BAD: This implicitly uses 'Object.toString' to convert the contents
// of 'words[]', and prints out something similar to:
// [Ljava.lang.String;@459189e1
System.out.println(words);
// GOOD: 'Arrays.toString' calls 'toString' on
// each of the array's elements. The statement prints out:
// [Who, is, John, Galt]
System.out.println(Arrays.toString(words));
// ALMOST RIGHT: This calls 'toString' on each of the multi-dimensional
// array's elements. However, because the elements are arrays, the statement
// prints out something similar to:
// [[Ljava.lang.String;@55f33675, [Ljava.lang.String;@527c6768]]
System.out.println(Arrays.toString(wordMatrix));
// GOOD: This properly prints out the contents of the multi-dimensional array:
// [[There, is], [no, spoon]]
System.out.println(Arrays.deepToString(wordMatrix));
} | 997 | 40.583333 | 79 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/CallsToRunFinalizersOnExit.java | void main() {
// ...
// BAD: Call to 'runFinalizersOnExit' forces execution of all finalizers on termination of
// the runtime, which can cause live objects to transition to an invalid state.
// Avoid using this method (and finalizers in general).
System.runFinalizersOnExit(true);
// ...
} | 297 | 36.25 | 92 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Implementation Hiding/GetClassGetResource.java | package framework;
class Address {
public URL getPostalCodes() {
// AVOID: The call is made on the run-time type of 'this'.
return this.getClass().getResource("postal-codes.csv");
}
}
package client;
class UKAddress extends Address {
public void convert() {
// Looks up "framework/postal-codes.csv"
new Address().getPostalCodes();
// Looks up "client/postal-codes.csv"
new UKAddress().getPostalCodes();
}
} | 471 | 26.764706 | 66 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Implementation Hiding/StaticArray.java | public class Display {
// AVOID: Array constant is vulnerable to mutation.
public static final String[] RGB = {
"FF0000", "00FF00", "0000FF"
};
void f() {
// Re-assigning the "constant" is legal.
RGB[0] = "00FFFF";
}
} | 231 | 20.090909 | 52 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Implementation Hiding/StaticArrayGood.java | // Solution 1: Extract to individual constants
public class Display {
public static final String RED = "FF0000";
public static final String GREEN = "00FF00";
public static final String BLUE = "0000FF";
}
// Solution 2: Define constants using in an enum type
public enum Display
{
RED ("FF0000"), GREEN ("00FF00"), BLUE ("0000FF");
private String rgb;
private Display(int rgb) {
this.rgb = rgb;
}
public String getRGB(){
return rgb;
}
}
// Solution 3: Use an unmodifiable collection
public class Display {
public static final List<String> RGB =
Collections.unmodifiableList(
Arrays.asList("FF0000",
"00FF00",
"0000FF"));
}
// Solution 4: Use a utility method
public class Utils {
public static <T> List<T> constList(T... values) {
return Collections.unmodifiableList(
Arrays.asList(values));
}
}
public class Display {
public static final List<String> RGB =
Utils.constList("FF0000", "00FF00", "0000FF");
}
| 1,103 | 24.674419 | 58 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Implementation Hiding/ExposeRepresentation.java | public class Cart {
private Set<Item> items;
// ...
// AVOID: Exposes representation
public Set<Item> getItems() {
return items;
}
}
....
int countItems(Set<Cart> carts) {
int result = 0;
for (Cart cart : carts) {
Set<Item> items = cart.getItems();
result += items.size();
items.clear(); // AVOID: Changes internal representation
}
return result;
} | 365 | 19.333333 | 58 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Implementation Hiding/GetClassGetResourceGood.java | package framework;
class Address {
public URL getPostalCodes() {
// GOOD: The call is always made on an object of the same type.
return Address.class.getResource("postal-codes.csv");
}
}
package client;
class UKAddress extends Address {
public void convert() {
// Looks up "framework/postal-codes.csv"
new Address().getPostalCodes();
// Looks up "framework/postal-codes.csv"
new UKAddress().getPostalCodes();
}
} | 477 | 27.117647 | 71 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Implementation Hiding/AbstractToConcreteCollection.java | Customer getNext(List<Customer> queue) {
if (queue == null)
return null;
LinkedList<Customer> myQueue = (LinkedList<Customer>)queue; // AVOID: Cast to concrete type.
return myQueue.poll();
}
Customer getNext(Queue<Customer> queue) {
if (queue == null)
return null;
return queue.poll(); // GOOD: Use abstract type.
}
| 328 | 24.307692 | 94 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Boxed Types/BoxedVariableBad.java | Boolean done = false;
while (!done) {
// ...
done = true;
// ...
}
| 73 | 9.571429 | 21 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Boxed Types/BoxedVariableGood.java | boolean done = false;
while (!done) {
// ...
done = true;
// ...
}
| 73 | 9.571429 | 21 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/DeadStoreOfLocal.java | Person find(String name) {
Person result;
for (Person p : people.values())
if (p.getName().equals(name))
result = p; // Redundant assignment
result = people.get(name);
return result; | 192 | 26.571429 | 39 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/CreatesEmptyZip.java | class Archive implements Closeable
{
private ZipOutputStream zipStream;
public Archive(File zip) throws IOException {
OutputStream stream = new FileOutputStream(zip);
stream = new BufferedOutputStream(stream);
zipStream = new ZipOutputStream(stream);
}
public void archive(String name, byte[] content) throws IOException {
ZipEntry entry = new ZipEntry(name);
zipStream.putNextEntry(entry);
// Missing call to 'write'
zipStream.closeEntry();
}
public void close() throws IOException {
zipStream.close();
}
} | 533 | 24.428571 | 70 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/AssignmentInReturn.java | public class Utilities
{
public static int max(int a, int b, int c) {
int ret = Math.max(a, b)
return ret = Math.max(ret, c); // Redundant assignment
}
} | 160 | 22 | 57 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/InterfaceCannotBeImplemented.java | interface I {
int clone();
}
class C implements I {
public int clone() {
return 23;
}
} | 108 | 11.111111 | 24 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/UnreadLocal.java | // Version containing unread local variable
public class Cart {
private Map<Item, Integer> items = ...;
public void add(Item i) {
Integer quantity = items.get(i);
if (quantity = null)
quantity = 1;
else
quantity++;
Integer oldQuantity = items.put(i, quantity); // AVOID: Unread local variable
}
}
// Version with unread local variable removed
public class Cart {
private Map<Item, Integer> items = ...;
public void add(Item i) {
Integer quantity = items.get(i);
if (quantity = null)
quantity = 1;
else
quantity++;
items.put(i, quantity);
}
} | 577 | 22.12 | 80 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/PointlessForwardingMethod.java | import static java.lang.System.out;
public class PointlessForwardingMethod {
private static class Bad {
// Violation: This print does nothing but forward to the other one, which is not
// called independently.
public void print(String firstName, String lastName) {
print(firstName + " " + lastName);
}
public void print(String fullName) {
out.println("Pointless forwarding methods are bad, " + fullName + "...");
}
}
private static class Better1 {
// Better: Merge the methods, using local variables to replace the parameters in
// the original version.
public void print(String firstName, String lastName) {
String fullName = firstName + " " + lastName;
out.println("Pointless forwarding methods are bad, " + fullName + "...");
}
}
private static class Better2 {
// Better: If there's no complicated logic, you can often remove the extra
// variables entirely.
public void print(String firstName, String lastName) {
out.println(
"Pointless forwarding methods are bad, " +
firstName + " " + lastName + "..."
);
}
}
public static void main(String[] args) {
new Bad().print("Foo", "Bar");
new Better1().print("Foo", "Bar");
new Better2().print("Foo", "Bar");
}
} | 1,234 | 29.121951 | 82 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/NonAssignedFields.java | class Person {
private String name;
private int age;
public Person(String name, int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
| 247 | 13.588235 | 41 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/UnusedLabel.java | public class WebStore {
public boolean itemIsBeingBought(Item item) {
boolean found = false;
carts: // AVOID: Unused label
for (int i = 0; i < carts.size(); i++) {
Cart cart = carts.get(i);
for (int j = 0; j < cart.numItems(); j++) {
if (item.equals(cart.getItem(j))) {
found = true;
break;
}
}
}
return found;
}
} | 354 | 21.1875 | 46 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/FinalizerNullsFields.java | class FinalizedClass {
Object o = new Object();
String s = "abcdefg";
Integer i = Integer.valueOf(2);
@Override
protected void finalize() throws Throwable {
super.finalize();
//No need to nullify fields
this.o = null;
this.s = null;
this.i = null;
}
} | 269 | 18.285714 | 45 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Dead Code/EmptyFinalize.java | class ExtendedLog extends Log
{
// ...
protected void finalize() {
// BAD: This empty 'finalize' stops 'super.finalize' from being executed.
}
}
class Log implements Closeable
{
// ...
public void close() {
// ...
}
protected void finalize() {
close();
}
} | 274 | 12.095238 | 75 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Magic Constants/MagicNumbersUseConstant.java | // Problem version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final String USERNAME = "test";
public static final int TIMEOUT = 60000;
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
int internalPort = 8080; // AVOID: Magic number
new MagicConstants().serve(IP, internalPort, USERNAME, TIMEOUT);
}
}
// Fixed version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final String USERNAME = "test";
public static final int TIMEOUT = 60000;
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
new MagicConstants().serve(IP, PORT, USERNAME, TIMEOUT); // Use 'PORT' constant
}
} | 903 | 24.111111 | 82 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Magic Constants/MagicConstantsNumbers.java | // Problem version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final String USERNAME = "test";
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
int timeout = 60000; // AVOID: Magic number
new MagicConstants().serve(IP, PORT, USERNAME, timeout);
}
}
// Fixed version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final String USERNAME = "test";
public static final int TIMEOUT = 60000; // Magic number is replaced by named constant
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
new MagicConstants().serve(IP, PORT, USERNAME, TIMEOUT); // Use 'TIMEOUT' constant
}
} | 899 | 24.714286 | 88 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Magic Constants/MagicConstantsString.java | // Problem version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final int TIMEOUT = 60000;
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
String username = "test"; // AVOID: Magic string
new MagicConstants().serve(IP, PORT, username, TIMEOUT);
}
}
// Fixed version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final int USERNAME = "test"; // Magic string is replaced by named constant
public static final int TIMEOUT = 60000;
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
new MagicConstants().serve(IP, PORT, USERNAME, TIMEOUT); // Use 'USERNAME' constant
}
} | 897 | 24.657143 | 90 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Magic Constants/MagicStringsUseConstant.java | // Problem version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final String USERNAME = "test";
public static final int TIMEOUT = 60000;
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
String internalIp = "127.0.0.1"; // AVOID: Magic string
new MagicConstants().serve(internalIp, PORT, USERNAME, TIMEOUT);
}
}
// Fixed version
public class MagicConstants
{
public static final String IP = "127.0.0.1";
public static final int PORT = 8080;
public static final String USERNAME = "test";
public static final int TIMEOUT = 60000;
public void serve(String ip, int port, String user, int timeout) {
// ...
}
public static void main(String[] args) {
new MagicConstants().serve(IP, PORT, USERNAME, TIMEOUT); //Use 'IP' constant
}
} | 908 | 24.25 | 79 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Declarations/BreakInSwitchCase.java | class Server
{
public void respond(Event event)
{
Message reply = null;
switch (event) {
case PING:
reply = Message.PONG;
// Missing 'break' statement
case TIMEOUT:
reply = Message.PING;
case PONG:
// No reply needed
}
if (reply != null)
send(reply);
}
private void send(Message message) {
// ...
}
}
enum Event { PING, PONG, TIMEOUT }
enum Message { PING, PONG } | 401 | 15.08 | 37 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Declarations/NoConstantsOnly.java | public class NoConstantsOnly {
static interface MathConstants
{
public static final Double Pi = 3.14;
}
static class Circle implements MathConstants
{
public double radius;
public double area()
{
return Math.pow(radius, 2) * Pi;
}
}
} | 275 | 17.4 | 45 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Declarations/MakeImportsExplicit.java | import java.util.*; // AVOID: Implicit import statements
import java.awt.*;
public class Customers {
public List getCustomers() { // Compiler error: 'List' is ambiguous.
...
}
} | 184 | 22.125 | 70 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Exception Handling/DroppedExceptions.java | // Dropped exception, with no information on whether
// the exception is expected or not
synchronized void waitIfAutoSyncScheduled() {
try {
while (isAutoSyncScheduled) {
this.wait(1000);
}
} catch (InterruptedException e) {
}
} | 239 | 23 | 53 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Exception Handling/NumberFormatException.java | String s = ...;
int n;
n = Integer.parseInt(s); // BAD: NumberFormatException is not caught.
try {
n = Integer.parseInt(s);
} catch (NumberFormatException e) { // GOOD: The exception is caught.
// Handle the exception
}
| 240 | 20.909091 | 71 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Exception Handling/IgnoreExceptionalReturn.java | java.io.InputStream is = (...);
byte[] b = new byte[16];
is.read(b); | 68 | 22 | 31 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Exception Handling/DroppedExceptions-comment.java | synchronized void waitIfAutoSyncScheduled() {
try {
while (isAutoSyncScheduled) {
this.wait(1000);
}
} catch (InterruptedException e) {
// Expected exception. The file cannot be synchronized yet.
}
} | 211 | 22.555556 | 61 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Exception Handling/DroppedExceptions-good.java | // Exception is passed to 'ignore' method with a comment
synchronized void waitIfAutoSyncScheduled() {
try {
while (isAutoSyncScheduled) {
this.wait(1000);
}
} catch (InterruptedException e) {
Exceptions.ignore(e, "Expected exception. The file cannot be synchronized yet.");
}
} | 290 | 28.1 | 83 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Exception Handling/ExceptionCatch.java | FileInputStream fis = ...
try {
fis.read();
} catch (Throwable e) { // BAD: The exception is too general.
// Handle this exception
}
FileInputStream fis = ...
try {
fis.read();
} catch (IOException e) { // GOOD: The exception is specific.
// Handle this exception
}
| 274 | 18.642857 | 63 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Exception Handling/DroppedExceptions-ignore.java | // 'ignore' method. This method does nothing, but can be called
// to document the reason why the exception can be ignored.
public static void ignore(Throwable e, String message) {
} | 183 | 35.8 | 63 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Naming Conventions/ConfusingOverridesNames.java | public class Customer
{
private String title;
private String forename;
private String surname;
// ...
public String tostring() { // Incorrect capitalization of 'toString'
return title + " " + forename + " " + surname;
}
} | 232 | 18.416667 | 70 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Naming Conventions/AmbiguousOuterSuper.java | public class Outer
{
void printMessage() {
System.out.println("Outer");
}
class Inner extends Super
{
void ambiguous() {
printMessage(); // Ambiguous call
}
}
public static void main(String[] args) {
new Outer().new Inner().ambiguous();
}
}
class Super
{
void printMessage() {
System.out.println("Super");
}
}
| 338 | 12.56 | 41 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Naming Conventions/ConfusingMethodNames.java | public class InternetResource
{
private String protocol;
private String host;
private String path;
// ...
public String toUri() {
return protocol + "://" + host + "/" + path;
}
// ...
public String toURI() {
return toUri();
}
} | 244 | 12.611111 | 46 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Naming Conventions/FieldMasksSuperField.java | public class FieldMasksSuperField {
static class Person {
protected int age;
public Person(int age)
{
this.age = age;
}
}
static class Employee extends Person {
protected int age; // This field hides 'Person.age'.
protected int numberOfYearsEmployed;
public Employee(int age, int numberOfYearsEmployed)
{
super(age);
this.numberOfYearsEmployed = numberOfYearsEmployed;
}
}
public static void main(String[] args) {
Employee e = new Employee(20, 2);
System.out.println(e.age);
}
} | 629 | 25.25 | 63 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Naming Conventions/SameNameAsSuper.java | import com.company.util.Attendees;
public class Meeting
{
private Attendees attendees;
// ...
// Many lines
// ...
// AVOID: This class has the same name as its superclass.
private static class Attendees extends com.company.util.Attendees
{
// ...
}
} | 264 | 15.5625 | 66 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Naming Conventions/LocalShadowsFieldConfusing.java | public class Container
{
private int[] values; // Field called 'values'
public Container (int... values) {
this.values = values;
}
public Container dup() {
int length = values.length;
int[] values = new int[length]; // Local variable called 'values'
Container result = new Container(values);
return result;
}
}
| 330 | 19.6875 | 68 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Boolean Logic/SimplifyBoolExpr.java | boolean f1(List<Boolean> l) {
for(Boolean x : l) {
if (x == true) return true;
}
return false;
}
boolean f2(List<Boolean> l) {
for(Boolean x : l) {
if (x) return true;
}
return false;
}
void g1(List<Boolean> l1) {
List<Boolean> l2 = new ArrayList<Boolean>();
for(Boolean x : l1) {
l2.add(x == true);
}
}
void g2(List<Boolean> l1) {
List<Boolean> l2 = new ArrayList<Boolean>();
for(Boolean x : l1) {
if (x == null) {
// handle null case
}
l2.add(x);
}
}
| 483 | 14.612903 | 45 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/legacy/UnnecessaryCast.java | public class UnnecessaryCast {
public static void main(String[] args) {
Integer i = 23;
Integer j = (Integer)i; // AVOID: Redundant cast
}
} | 165 | 26.666667 | 57 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/legacy/ParameterAssignment.java | final private static double KM_PER_MILE = 1.609344;
// AVOID: Example that assigns to a parameter
public double milesToKM(double miles) {
miles *= KM_PER_MILE;
return miles;
}
// GOOD: Example of using an expression instead
public double milesToKM(double miles) {
return miles * KM_PER_MILE;
}
// GOOD: Example of using a local variable
public double milesToKM(double miles) {
double kilometres = miles * KM_PER_MILE;
return kilometres;
}
| 447 | 22.578947 | 51 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/legacy/InexactVarArg.java | class InexactVarArg
{
private static void length(Object... objects) {
System.out.println(objects.length);
}
public static void main(String[] args) {
String[] words = { "apple", "banana", "cherry" };
String[][] lists = { words, words };
length(words); // avoid: Argument does not clarify
length(lists); // which parameter type is used.
}
}
| 354 | 24.357143 | 52 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/legacy/AutoBoxing.java | Long sum = 0L;
for (long k = 0; k < Integer.MAX_VALUE; k++) {
sum += k; // AVOID: Inefficient unboxing and reboxing of 'sum'
} | 129 | 31.5 | 64 | java |
codeql | codeql-master/java/ql/src/Language Abuse/WrappedIteratorGood.java | class MySequence implements Iterable<MyElem> {
// ... some reference to data
public Iterator<MyElem> iterator() {
return new Iterator<MyElem>() {
// Correct: iteration state inside returned iterator
final Iterator<MyElem> it = data.iterator();
public boolean hasNext() {
return it.hasNext();
}
public MyElem next() {
return transformElem(it.next());
}
public void remove() {
// ...
}
};
}
}
| 477 | 24.157895 | 58 | java |
codeql | codeql-master/java/ql/src/Language Abuse/IterableIteratorBad.java | class ElemIterator implements Iterator<MyElem>, Iterable<MyElem> {
private MyElem[] data;
private idx = 0;
public boolean hasNext() {
return idx < data.length;
}
public MyElem next() {
return data[idx++];
}
public Iterator<MyElem> iterator() {
return this;
}
// ...
}
void useMySequence(Iterable<MyElem> s) {
// do some work by traversing the sequence
for (MyElem e : s) {
// ...
}
// do some more work by traversing it again
for (MyElem e : s) {
// ...
}
}
| 510 | 17.925926 | 66 | java |
codeql | codeql-master/java/ql/src/Language Abuse/UselessUpcast.java | public class UselessUpcast {
private static class B {}
private static class D extends B {}
private static void Foo(B b) { System.out.println("Foo(B)"); }
private static void Foo(D d) { System.out.println("Foo(D)"); }
private static class Expr {}
private static class AddExpr extends Expr {}
private static class SubExpr extends Expr {}
public static void main(String[] args) {
D d = new D();
B b_ = (B)d; // violation: redundant cast, consider removing
B b = new D();
D d_ = (D)b; // non-violation: required downcast
Foo(d);
Foo((B)d); // non-violation: required to call Foo(B)
// Non-violation: required to specify the type of the ternary operands.
Expr e = d != null ? (Expr)new AddExpr() : new SubExpr();
}
} | 743 | 28.76 | 73 | java |
codeql | codeql-master/java/ql/src/Language Abuse/EnumIdentifier.java | class Old
{
public static void main(String[] args) {
int enum = 13; // AVOID: 'enum' is a variable.
System.out.println("The value of enum is " + enum);
}
}
| 163 | 19.5 | 53 | java |
codeql | codeql-master/java/ql/src/Language Abuse/TypeVarExtendsFinalType.java | class Printer
{
void print(List<? extends String> strings) { // Unnecessary wildcard
for (String s : strings)
System.out.println(s);
}
} | 144 | 19.714286 | 70 | java |
codeql | codeql-master/java/ql/src/Language Abuse/UselessNullCheckBad.java | Object o = new Object();
if (o == null) {
// this cannot happen!
}
| 69 | 13 | 24 | java |
codeql | codeql-master/java/ql/src/Language Abuse/CastThisToTypeParameterFix.java | public class CastThisToTypeParameter {
private abstract static class GoodBaseNode<T extends GoodBaseNode<T>> {
public abstract T getSelf();
public abstract T getParent();
public T getRoot() {
// GOOD: introduce an abstract method to enforce the constraint
// that 'this' can be converted to T for derived types
T cur = getSelf();
while(cur.getParent() != null)
{
cur = cur.getParent();
}
return cur;
}
}
private static class GoodConcreteNode extends GoodBaseNode<GoodConcreteNode> {
private String name;
private GoodConcreteNode parent;
public GoodConcreteNode(String name, GoodConcreteNode parent)
{
this.name = name;
this.parent = parent;
}
@Override
public GoodConcreteNode getSelf() {
return this;
}
@Override
public GoodConcreteNode getParent() {
return parent;
}
@Override
public String toString() {
return name;
}
}
public static void main(String[] args) {
GoodConcreteNode a = new GoodConcreteNode("a", null);
GoodConcreteNode b = new GoodConcreteNode("b", a);
GoodConcreteNode c = new GoodConcreteNode("c", a);
GoodConcreteNode d = new GoodConcreteNode("d", b);
GoodConcreteNode root = d.getRoot();
System.out.println(a + " " + root);
}
} | 1,248 | 23.019231 | 79 | java |
codeql | codeql-master/java/ql/src/Language Abuse/DubiousTypeTestOfThis.java | public class DubiousTypeTestOfThis {
private static class BadBase {
private Derived d;
public BadBase(Derived d) {
if(d != null && this instanceof Derived) // violation
this.d = (Derived)this;
else
this.d = d;
}
}
private static class Derived extends BadBase {
public Derived() {
super(null);
}
}
public static void main(String[] args) {}
} | 375 | 17.8 | 56 | java |
codeql | codeql-master/java/ql/src/Language Abuse/IterableIteratorGood2.java | class ElemIterator implements Iterator<MyElem>, Iterable<MyElem> {
private MyElem[] data;
private idx = 0;
private boolean usedAsIterable = false;
public boolean hasNext() {
return idx < data.length;
}
public MyElem next() {
return data[idx++];
}
public Iterator<MyElem> iterator() {
if (usedAsIterable || idx > 0)
throw new IllegalStateException();
usedAsIterable = true;
return this;
}
// ...
}
| 444 | 21.25 | 66 | java |
codeql | codeql-master/java/ql/src/Language Abuse/TypeVariableHidesType.java | import java.util.Map;
import java.util.Map.Entry;
class Mapping<Key, Entry> // The type variable 'Entry' shadows the imported interface 'Entry'.
{
// ...
} | 158 | 21.714286 | 95 | java |
codeql | codeql-master/java/ql/src/Language Abuse/WrappedIteratorBad2.java | class MySequence implements Iterable<MyElem> {
// ... some reference to data
final Iterator<MyElem> it = data.iterator();
// Wrong: iteration state outside returned iterator
public Iterator<MyElem> iterator() {
return new Iterator<MyElem>() {
public boolean hasNext() {
return it.hasNext();
}
public MyElem next() {
return transformElem(it.next());
}
public void remove() {
// ...
}
};
}
}
| 468 | 23.684211 | 53 | java |
codeql | codeql-master/java/ql/src/Language Abuse/MissedTernaryOpportunity.java | public class MissedTernaryOpportunity {
private static int myAbs1(int x) {
// Violation
if(x >= 0)
return x;
else
return -x;
}
private static int myAbs2(int x) {
// Better
return x >= 0 ? x : -x;
}
public static void main(String[] args) {
int i = 23;
// Violation
String s1;
if(i == 23)
s1 = "Foo";
else
s1 = "Bar";
System.out.println(s1);
// Better
String s2 = i == 23 ? "Foo" : "Bar";
System.out.println(s2);
}
} | 464 | 14.5 | 41 | java |
codeql | codeql-master/java/ql/src/Language Abuse/OverridePackagePrivate.java | // File 1
package gui;
abstract class Widget
{
// ...
// Return the width (in pixels) of this widget
int width() {
// ...
}
// ...
}
// File 2
package gui.extras;
class PhotoResizerWidget extends Widget
{
// ...
// Return the new width (of the photo when resized)
public int width() {
// ...
}
// ...
} | 369 | 11.758621 | 55 | java |
codeql | codeql-master/java/ql/src/Language Abuse/ImplementsAnnotationGood.java | @Deprecated
public abstract class ImplementsAnnotationFix {
// ...
} | 69 | 16.5 | 47 | java |
codeql | codeql-master/java/ql/src/Language Abuse/WrappedIteratorBad1.java | class MySequence implements Iterable<MyElem> {
// ... some reference to data
final Iterator<MyElem> it = data.iterator();
// Wrong: reused iterator
public Iterator<MyElem> iterator() {
return it;
}
}
void useMySequence(MySequence s) {
// do some work by traversing the sequence
for (MyElem e : s) {
// ...
}
// do some more work by traversing it again
for (MyElem e : s) {
// ...
}
}
| 419 | 20 | 46 | java |
codeql | codeql-master/java/ql/src/Language Abuse/EmptyStatement.java | public class Cart {
// AVOID: Empty statement
List<Item> items = new ArrayList<Cart>();;
public void applyDiscount(float discount) {
// AVOID: Empty statement as loop body
for (int i = 0; i < items.size(); items.get(i++).applyDiscount(discount));
}
} | 258 | 31.375 | 76 | java |
codeql | codeql-master/java/ql/src/Language Abuse/IterableIteratorGood1.java | class ElemSequence implements Iterable<MyElem> {
private MyElem[] data;
public Iterator<MyElem> iterator() {
return new Iterator<MyElem>() {
private idx = 0;
public boolean hasNext() {
return idx < data.length;
}
public MyElem next() {
return data[idx++];
}
};
}
// ...
}
| 335 | 18.764706 | 48 | java |
codeql | codeql-master/java/ql/src/Language Abuse/ChainedInstanceof.java | import java.util.*;
public class ChainedInstanceof {
public static void main(String[] args) {
// BAD: example of a sequence of type tests
List<BadAnimal> badAnimals = new ArrayList<BadAnimal>();
badAnimals.add(new BadCat());
badAnimals.add(new BadDog());
for(BadAnimal a: badAnimals) {
if(a instanceof BadCat) System.out.println("Miaow!");
else if(a instanceof BadDog) System.out.println("Woof!");
else throw new RuntimeException("Oops!");
}
// GOOD: solution using polymorphism
List<PolymorphicAnimal> polymorphicAnimals = new ArrayList<PolymorphicAnimal>();
polymorphicAnimals.add(new PolymorphicCat());
polymorphicAnimals.add(new PolymorphicDog());
for(PolymorphicAnimal a: polymorphicAnimals) a.speak();
// GOOD: solution using the visitor pattern
List<VisitableAnimal> visitableAnimals = new ArrayList<VisitableAnimal>();
visitableAnimals.add(new VisitableCat());
visitableAnimals.add(new VisitableDog());
for(VisitableAnimal a: visitableAnimals) a.accept(new SpeakVisitor());
}
//#################### TYPES FOR BAD EXAMPLE ####################
private interface BadAnimal {}
private static class BadCat implements BadAnimal {}
private static class BadDog implements BadAnimal {}
//#################### TYPES FOR POLYMORPHIC EXAMPLE ####################
private interface PolymorphicAnimal {
void speak();
}
private static class PolymorphicCat implements PolymorphicAnimal {
public void speak() { System.out.println("Miaow!"); }
}
private static class PolymorphicDog implements PolymorphicAnimal {
public void speak() { System.out.println("Woof!"); }
}
//#################### TYPES FOR VISITOR EXAMPLE ####################
private interface Visitor {
void visit(VisitableCat c);
void visit(VisitableDog d);
}
private static class SpeakVisitor implements Visitor {
public void visit(VisitableCat c) { System.out.println("Miaow!"); }
public void visit(VisitableDog d) { System.out.println("Woof!"); }
}
private interface VisitableAnimal {
void accept(Visitor v);
}
private static class VisitableCat implements VisitableAnimal {
public void accept(Visitor v) { v.visit(this); }
}
private static class VisitableDog implements VisitableAnimal {
public void accept(Visitor v) { v.visit(this); }
}
}
| 2,321 | 34.181818 | 82 | java |
codeql | codeql-master/java/ql/src/Language Abuse/DubiousDowncastOfThis.java | public class DubiousDowncastOfThis {
private static class BadBase {
private Derived d;
public BadBase(Derived d) {
if(d != null && this instanceof Derived)
this.d = (Derived)this; // violation
else
this.d = d;
}
}
private static class Derived extends BadBase {
public Derived() {
super(null);
}
}
public static void main(String[] args) {}
} | 376 | 17.85 | 47 | java |
codeql | codeql-master/java/ql/src/Language Abuse/UselessTypeTest.java | public class UselessTypeTest {
private static class B {}
private static class D extends B {}
public static void main(String[] args) {
D d = new D();
if(d instanceof B) { // violation
System.out.println("Mon dieu, d is a B!");
}
}
} | 245 | 21.363636 | 45 | java |
codeql | codeql-master/java/ql/src/Language Abuse/CastThisToTypeParameter.java | public class CastThisToTypeParameter {
private abstract static class BadBaseNode<T extends BadBaseNode<T>> {
public abstract T getParent();
public T getRoot() {
// BAD: relies on derived types to use the right pattern
T cur = (T)this;
while(cur.getParent() != null) {
cur = cur.getParent();
}
return cur;
}
}
} | 338 | 23.214286 | 70 | java |
codeql | codeql-master/java/ql/src/Language Abuse/ImplementsAnnotation.java | public abstract class ImplementsAnnotation implements Deprecated {
// ...
} | 76 | 24.666667 | 66 | java |
codeql | codeql-master/java/ql/src/DeadCode/DeadEnumConstant.java | public enum Result {
SUCCESS,
FAILURE,
ERROR
}
public Result runOperation(String value) {
if (value == 1) {
return SUCCESS;
} else {
return FAILURE;
}
}
public static void main(String[] args) {
Result operationResult = runOperation(args[0]);
if (operationResult == Result.ERROR) {
exit(1);
} else {
exit(0);
}
} | 332 | 13.478261 | 48 | java |
codeql | codeql-master/java/ql/src/DeadCode/DeadMethodTest.java | public class TestClass {
@Before
public void setUp() {
// ...
}
@Test
public void testCustomer() {
// ...
}
} | 121 | 9.166667 | 29 | java |
codeql | codeql-master/java/ql/src/DeadCode/DeadFieldWrittenTo.java | public class FieldOnlyRead {
private int writtenToField;
public void runThing() {
writtenToField = 2;
callOtherThing();
}
public static main(String[] args) {
runThing();
}
} | 186 | 14.583333 | 36 | java |
codeql | codeql-master/java/ql/src/DeadCode/NamespaceClass.java | /*
* This class is dead because it is never constructed, and the instance methods are not
* called.
*/
public class CustomerActions {
public CustomerActions() {
}
// This method is never called,
public Action createAddCustomerAction () {
return new AddCustomerAction();
}
// These two are used directly
public static class AddCustomerAction extends Action { /* ... */ }
public static class RemoveCustomerAction extends Action { /* ... */ }
}
public static void main(String[] args) {
// Construct the actions directly
Action action = new CustomerActions.AddCustomerAction();
action.run();
Action action = new CustomerActions.RemoveCustomerAction();
action.run();
}
| 685 | 25.384615 | 87 | java |
codeql | codeql-master/java/ql/src/DeadCode/DeadFieldSerialized.java | @XmlRootElement
public class SerializableClass {
@XmlAttribute
private String field;
public void setField(String field) {
this.field = field;
}
} | 152 | 16 | 37 | java |
codeql | codeql-master/java/ql/src/DeadCode/NamespaceClass2.java | // This class is now live - it is used as a namespace class
public class CustomerActions {
/*
* This constructor is suppressing construction of this class, so is not considered
* dead.
*/
private CustomerActions() { }
// These two are used directly
public static class AddCustomerAction extends Action { /* ... */ }
public static class RemoveCustomerAction extends Action { /* ... */ }
}
public static void main(String[] args) {
// Construct the actions directly
Action action = new CustomerActions.AddCustomerAction();
action.run();
Action action = new CustomerActions.RemoveCustomerAction();
action.run();
}
| 627 | 30.4 | 84 | java |
codeql | codeql-master/java/ql/src/DeadCode/UselessParameter.java | public void isAbsolutePath(String path, String name) {
return path.startsWith("/") || path.startsWith("\\");
} | 111 | 36.333333 | 54 | java |
codeql | codeql-master/java/ql/src/DeadCode/DeadClass.java | public static void main(String[] args) {
String firstName = /*...*/; String lastName = /*...*/;
// Construct a customer
Customer customer = new Customer();
// Set important properties (but not the address)
customer.setName(firstName, lastName);
// Save the customer
customer.save();
}
public class Customer {
private Address address;
// ...
// This setter and getter are unused, and so may be deleted.
public void addAddress(String line1, String line2, String line3) {
address = new Address(line1, line2, line3);
}
public Address getAddress() { return address; }
}
/*
* This class is only constructed from dead code, and may be deleted.
*/
public class Address {
// ...
public Address(String line1, String line2, String line3) {
// ...
}
}
| 765 | 23.709677 | 69 | java |
codeql | codeql-master/java/ql/src/DeadCode/DeadField.java | public class FieldOnlyRead {
private int deadField;
private int getDeadField() {
return deadField;
}
} | 108 | 14.571429 | 29 | java |
codeql | codeql-master/java/ql/src/DeadCode/DeadMethod.java | public static void main(String[] args) {
// Only call the live method
liveMethod();
}
/** This method is live because it is called by main(..) */
public static void liveMethod() {
otherLiveMethod()
}
/** This method is live because it is called by a live method */
public static void otherLiveMethod() {
}
/** This method is dead because it is never called */
public static void deadMethod() {
otherDeadMethod();
}
/** This method is dead because it is only called by dead methods */
public static void otherDeadMethod() {
} | 533 | 22.217391 | 68 | java |
codeql | codeql-master/java/ql/src/Complexity/ComplexCondition.java | public class Dialog
{
// ...
private void validate() {
// TODO: check that this covers all cases
if ((id != null && id.length() == 0) ||
((partner == null || partner.id == -1) &&
((option == Options.SHORT && parameter.length() == 0) ||
(option == Options.LONG && parameter.length() < 8))))
{
disableOKButton();
} else {
enableOKButton();
}
}
// ...
} | 381 | 19.105263 | 59 | java |
codeql | codeql-master/java/ql/src/Complexity/ComplexConditionGood.java | public class Dialog
{
// ...
private void validate() {
if(idIsEmpty() || (noPartnerId() && parameterLengthInvalid())){ // GOOD: Condition is simpler
disableOKButton();
} else {
enableOKButton();
}
}
private boolean idIsEmpty(){
return id != null && id.length() == 0;
}
private boolean noPartnerId(){
return partner == null || partner.id == -1;
}
private boolean parameterLengthInvalid(){
return (option == Options.SHORT && parameter.length() == 0) ||
(option == Options.LONG && parameter.length() < 8);
}
// ...
} | 627 | 22.259259 | 99 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/MissingVoidConstructorsOnSerializable.java | class WrongItem {
private String name;
// BAD: This class does not have a no-argument constructor, and throws an
// 'InvalidClassException' at runtime.
public WrongItem(String name) {
this.name = name;
}
}
class WrongSubItem extends WrongItem implements Serializable {
public WrongSubItem() {
super(null);
}
public WrongSubItem(String name) {
super(name);
}
}
class Item {
private String name;
// GOOD: This class declares a no-argument constructor, which allows serializable
// subclasses to be deserialized without error.
public Item() {}
public Item(String name) {
this.name = name;
}
}
class SubItem extends Item implements Serializable {
public SubItem() {
super(null);
}
public SubItem(String name) {
super(name);
}
} | 859 | 19.47619 | 86 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/NonSerializableFieldTooGeneral.java | class WrongPair<L, R> implements Serializable{
private final L left; // BAD
private final R right; // BAD: L and R are not guaranteed to be serializable
public WrongPair(L left, R right){ ... }
...
}
class Pair<L extends Serializable, R extends Serializable> implements Serializable{
private final L left; // GOOD: L and R must implement Serializable
private final R right;
public Pair(L left, R right){ ... }
...
}
class WrongEvent implements Serializable{
private Object eventData; // BAD: Type is too general.
public WrongEvent(Object eventData){ ... }
}
class Event implements Serializable{
private Serializable eventData; // GOOD: Force the user to supply only serializable data
public Event(Serializable eventData){ ... }
}
| 827 | 26.6 | 93 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/TransientNotSerializable.java | class State {
// The 'transient' modifier has no effect here because
// the 'State' class does not implement 'Serializable'.
private transient int[] stateData;
}
class PersistentState implements Serializable {
private int[] stateData;
// The 'transient' modifier indicates that this field is not part of
// the persistent state and should therefore not be serialized.
private transient int[] cachedComputedData;
} | 421 | 34.166667 | 69 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/MissingVoidConstructorOnExternalizable.java | class WrongMemo implements Externalizable {
private String memo;
// BAD: No public no-argument constructor is defined. Deserializing this object
// causes an 'InvalidClassException'.
public WrongMemo(String memo) {
this.memo = memo;
}
public void writeExternal(ObjectOutput arg0) throws IOException {
//...
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
//...
}
}
class Memo implements Externalizable {
private String memo;
// GOOD: Declare a public no-argument constructor, which is used by the
// serialization framework when the object is deserialized.
public Memo() {
}
public Memo(String memo) {
this.memo = memo;
}
public void writeExternal(ObjectOutput out) throws IOException {
//...
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
//...
}
}
| 966 | 24.447368 | 89 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/NonSerializableComparator.java | // BAD: This is not serializable, and throws a 'java.io.NotSerializableException'
// when used in a serializable sorted collection.
class WrongComparator implements Comparator<String> {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
// GOOD: This is serializable, and can be used in collections that are meant to be serialized.
class StringComparator implements Comparator<String>, Serializable {
private static final long serialVersionUID = -5972458403679726498L;
public int compare(String arg0, String arg1) {
return arg0.compareTo(arg1);
}
} | 607 | 37 | 94 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/ReadResolveObject.java | class FalseSingleton implements Serializable {
private static final long serialVersionUID = -7480651116825504381L;
private static FalseSingleton instance;
private FalseSingleton() {}
public static FalseSingleton getInstance() {
if (instance == null) {
instance = new FalseSingleton();
}
return instance;
}
// BAD: Signature of 'readResolve' does not match the exact signature that is expected
// (that is, it does not return 'java.lang.Object').
public FalseSingleton readResolve() throws ObjectStreamException {
return FalseSingleton.getInstance();
}
}
class Singleton implements Serializable {
private static final long serialVersionUID = -7480651116825504381L;
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// GOOD: Signature of 'readResolve' matches the exact signature that is expected.
// It replaces the singleton that is read from a stream with an instance of 'Singleton',
// instead of creating a new singleton.
private Object readResolve() throws ObjectStreamException {
return Singleton.getInstance();
}
} | 1,195 | 28.9 | 89 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/NonSerializableField.java | class DerivedFactors { // Class that contains derived values computed from entries in a
private Number efficiency; // performance record
private Number costPerItem;
private Number profitPerItem;
...
}
class WrongPerformanceRecord implements Serializable {
private String unitId;
private Number dailyThroughput;
private Number dailyCost;
private DerivedFactors factors; // BAD: 'DerivedFactors' is not serializable
// but is in a serializable class. This
// causes a 'java.io.NotSerializableException'
// when 'WrongPerformanceRecord' is serialized.
...
}
class PerformanceRecord implements Serializable {
private String unitId;
private Number dailyThroughput;
private Number dailyCost;
transient private DerivedFactors factors; // GOOD: 'DerivedFactors' is declared
// 'transient' so it does not contribute to the
// serializable state of 'PerformanceRecord'.
...
}
| 1,147 | 40 | 99 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/NonSerializableInnerClass.java | class NonSerializableServer {
// BAD: The following class is serializable, but the enclosing class
// 'NonSerializableServer' is not. Serializing an instance of 'WrongSession'
// causes a 'java.io.NotSerializableException'.
class WrongSession implements Serializable {
private static final long serialVersionUID = 8970783971992397218L;
private int id;
private String user;
WrongSession(int id, String user) { /*...*/ }
}
public WrongSession getNewSession(String user) {
return new WrongSession(newId(), user);
}
}
class Server {
// GOOD: The following class can be correctly serialized because it is static.
static class Session implements Serializable {
private static final long serialVersionUID = 1065454318648105638L;
private int id;
private String user;
Session(int id, String user) { /*...*/ }
}
public Session getNewSession(String user) {
return new Session(newId(), user);
}
} | 1,044 | 30.666667 | 82 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/IncorrectSerializableMethods.java | class WrongNetRequest implements Serializable {
// BAD: Does not match the exact signature required for a custom
// deserialization protocol. Will not be called during deserialization.
void readObject(ObjectInputStream in) {
//...
}
// BAD: Does not match the exact signature required for a custom
// serialization protocol. Will not be called during serialization.
protected void writeObject(ObjectOutputStream out) {
//...
}
}
class NetRequest implements Serializable {
// GOOD: Signature for a custom deserialization implementation.
private void readObject(ObjectInputStream in) {
//...
}
// GOOD: Signature for a custom serialization implementation.
private void writeObject(ObjectOutputStream out) {
//...
}
} | 743 | 28.76 | 72 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/IncorrectSerialVersionUID.java | class WrongNote implements Serializable {
// BAD: serialVersionUID must be static, final, and 'long'
private static final int serialVersionUID = 1;
//...
}
class Note implements Serializable {
// GOOD: serialVersionUID is of the correct type
private static final long serialVersionUID = 1L;
} | 300 | 26.363636 | 59 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Serialization/IncorrectSerializableMethodsSig.java | private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream out)
throws IOException; | 184 | 45.25 | 56 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Nullness/NullExprDeref.java | public int getID() {
return helper == null ? null : helper.getID();
}
| 74 | 17.75 | 50 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Nullness/NullMaybe.java | public Integer f(Integer p) {
return true ? p : 5;
}
| 54 | 12.75 | 29 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Nullness/NullAlways.java | public void createDir(File dir) {
if (dir != null || !dir.exists()) // BAD
dir.mkdir();
}
public void createDir(File dir) {
if (dir != null && !dir.exists()) // GOOD
dir.mkdir();
}
| 188 | 17.9 | 42 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Concurrency/UnreleasedLock.java | public void m() {
lock.lock();
// A
try {
// ... method body
} finally {
// B
lock.unlock();
}
} | 129 | 12 | 24 | java |
codeql | codeql-master/java/ql/src/Likely Bugs/Concurrency/DoubleCheckedLockingGood.java | private Object lock = new Object();
private volatile MyObject f = null;
public MyObject getMyObject() {
MyObject result = f;
if (result == null) {
synchronized(lock) {
result = f;
if (result == null) {
result = new MyObject();
result.init();
f = result; // GOOD
}
}
}
return result;
}
| 344 | 18.166667 | 35 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.