Skip to content

Instantly share code, notes, and snippets.

@DhavalDalal
Last active September 15, 2022 08:58
Show Gist options
  • Save DhavalDalal/5fce9f3de630c355ca6843b203bef333 to your computer and use it in GitHub Desktop.
Save DhavalDalal/5fce9f3de630c355ca6843b203bef333 to your computer and use it in GitHub Desktop.
Identify the Code-Smell?

Identify the Code Smells

  • Can you identify the code-smell?
  • How will you Refactor it?
public class Employee {
private final Integer id;
private final String name;
public Employee(final Integer id, final String name) {
this.id = id;
this.name = name;
}
public String toString() {
return String.format("Employee(%d, %s)", id, name);
}
}
import java.util.ArrayList;
import java.util.List;
public class Filter {
public static List<Integer> selectPerfect(List<Integer> numbers) {
List<Integer> perfectNumbers = new ArrayList<>();
for (Integer number : numbers) {
if (isPerfect(number)) {
perfectNumbers.add(number);
}
}
return perfectNumbers;
}
private static boolean isPerfect(int number) {
if (number > 0) {
List<Integer> factors = new ArrayList<>();
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
factors.add(i);
}
}
// Sum of factors
int sumOfFactors = 0;
for (Integer i : factors) {
sumOfFactors += i;
}
// It is a perfect number if the difference between sum of factors and the
// number is equal to the number itself
return sumOfFactors - number == number;
}
return false;
}
public static void main(String[] args) {
List<Integer> numbers = List.of(-1, 0, 1, 2, 3, 4, 5, 6, 10, 28, 29);
List<Integer> perfectNumbers = Filter.selectPerfect(numbers);
System.out.println("perfectNumbers = " + perfectNumbers);
}
}
import java.sql.*;
import java.util.*;
public class Sql {
public List<Employee> fetchEmployees(String driverFQN, String dburl) throws SQLException, ClassNotFoundException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Employee> employees = new ArrayList<Employee>();
try {
Class.forName(driverFQN);
connection = DriverManager.getConnection(dburl);
statement = connection.createStatement();
statement.execute("select * from employee");
resultSet = statement.getResultSet();
while (resultSet.next()) {
int empId = resultSet.getInt(0);
String name = resultSet.getString(1);
employees.add(new Employee(empId, name));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
if (statement != null) {
statement.close();
if (resultSet != null)
resultSet.close();
}
}
}
return employees;
}
public static void main(String[] args) throws Exception {
var sql = new Sql();
var employees = sql.fetchEmployees("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/test");
System.out.println("Got Employees = " + employees);
System.out.println("DONE");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment