If anyone can understand the code, then:
public interface PrimeChecker { booolean isPrime(int n); }
public class PrimeCheckerUsingASieve implements PrimeChecker { }
public class PrimeCheckerUsingASieve implements PrimeChecker { public static final int MAX_PRIME = 1000000; private boolean[] sieve; public boolean isPrime(int n) { return sieve[n]; } public PrimeCheckerUsingASieve() {
this.sieve = new boolean[MAX_PRIME + 1]; Arrays.fill(sieve, true); sieve[0] = false; sieve[1] = false; for (int i = 0; i * i <= MAX_PRIME; ++i) { if (sieve[i]) { for (int j = i * i; j <= MAX_PRIME; j += i) { sieve[j] = false; } } } } }
public void init() { // code Arrays.fill(sieve, true); // more code }
private void uncrossAllNumbers() { Arrays.fill(sieve, true); } public void init() { // code uncrossAllNumbers(); // more code }
public void init() { // code sieve[0] = false; sieve[1] = false; // more code }
private void cross(int n) { sieve[n] = false; } private void crossObviousNumbers() { cross(0); cross(1); } public void init() { // code crossObviousNumbers(); // more code }
public void init() { // code for (int i = 0; i * i <= MAX_PRIME; ++i) { // more code } }
private void hasAtLeastOnePossibleUncrossedMultiple(int n) { return n * n <= MAX_PRIME; } public void init() { // code for (int n = 0; hasAtLeastOnePossibleUncrossedMultiple(n); ++n) {
// more code } }
public void init() { // code if (sieve[i]) { /* more code */ } // even more code }
public boolean isPrime(int n) { return sieve[i]; } public void init() { // code if (isPrime(n)) { /* more code */ } // even more code }
public void init() { // code for (int j = i * i; j <= MAX_PRIME; j += i) { sieve[j] = false; } // even more code }
private void crossMultiplesOf(int n) { for (int x = firstPossiblyUncrossedMultipleOf(n); j <= MAX_PRIME; x += n) { cross(x); } } public void init() { // code crossMultiplesOf(n); // even more code }
public class PrimeCheckerUsingASieve implements PrimeChecker { public static final int MAX_PRIME = 1000000; private boolean[] sieve; public PrimeChecker() { createSieve(); uncrossAllNumbers(); crossObviousNumbers(); crossMultiplesOfKnownPrimes(); } public boolean isPrime(int n) { return sieve[n]; } private void createSieve() { this.sieve = new boolean[MAX_PRIME + 1]; } private void uncrossAllNumbers() { Arrays.fill(sieve, true); } private void cross(int n) { sieve[n] = false; }
private void crossObviousNumbers() { cross(0); cross(1); } private void crossMultiplesOfKnownPrimes() { for (int n = 0; hasAtLeastOneUncrossedMultiple(n); ++n) { if (isPrime(n)) { crossMultiplesOf(n); } } } private boolean hasAtLeastOneUncrossedMultiple(int n) { return firstUncrossedMultipleOf(n) <= MAX_PRIME; } private int firstUncrossedMultipleOf(int n) { return n * n; } private void crossMultiplesOf(int n) { for (int j = firstUncrossedMultipleOf(n); j <= MAX_PRIME; j += n { cross(j); } } }
The first line of document must be your code.
But you still need Javadoc-like comments.
Don't comment code that you don't want anymore
(
we have version control systems now
)
int d;
int d; // time elapsed in days
int timeElapsedInDays;
void copy(char[] a1, char[] a2) { // some code }
void copy(char[] source, char[] destination){ // some code }
Date genymdhms;
Date generationTimestamp;
public class A { private int e; // More code }
for (int i = 0; i < 34; ++i) { s += (t[i] * 4) / 5; }
final int NUMBER_OF_TASKS = 34; final int REAL_NUMBER_OF_DAYS = 4; final int WORK_DAYS_ON_A_WEEK = 5; for (int i = 0; i < NUMBER_OF_TASKS; ++i) { s += (t[i] * REAL_NUMBER_OF_DAYS) / WORK_DAYS_ON_A_WEEK; }
ISomething myVariable = new SomethingImpl();
Something myVariable = new DefaultSomething();
public DayDate getOffsetNearestDayOfWeek(final Day targetDay) { int offsetToThisWeeksTarget = targetDay.index / getDayOfWeek().index; int offsetToFutureTarget = (offsetToThisWeeksTarget + 7) % 7; int offsetToPreviousTarget = offsetToFutureTarget - 7; return offsetToPreviousTarget > 3 ? plusDays(offsetToPreviousTarget) : plusDays(offsetToFutureTarget); }
*** *** *** * *** ***** * *** ***** *** *
public static void square(int size) { for (int row = 1; row <= size; ++row) { for (int column = 1; column <= size; ++column) { System.out.print('*'); } System.out.println(); } }
public static void pyramid(int size) { int totalSpaces = size - 1; int totalChars = 1; for (int row = 1; row <= size; ++row) { for (int space = 1; space <= totalSpaces; ++space) { System.out.print(' '); } for (int character = 1; character <= totalChars; ++character) { System.out.print('*'); } System.out.println(); --totalSpaces; totalCharacters += 2; } }
public static void rhombus(int size) { pyramid(size); int totalSpaces = 0; int totalCharacters = 2 * size - 3; for (int row = 1; row <= size - 1; ++row) { for (int space = 1; space <= totalSpaces; ++space) { System.out.print(' '); } for (int c = 1; c <= totalCharacters; ++c) { System.out.print('*'); } System.out.println(); ++totalSpace; totalCharacters -= 2; } }
private static char CHARACTER = '*'; private static char SPACE = ' ';
private static String makeString(int size, char character) { char[] cString = new char[size]; Arrays.fill(cString, character); return new String(cString); }
public static void square(int size) { for (int row = 1; row <= size; ++row) { System.out.print(makeString(size, CARACTER)); System.out.println(); } }
public static void pyramid(int size) { int totalSpace = size - 1; int totalCharacters = 1; for (int row = 1; row <= size; ++row) { System.out.print(makeString(totalSpaces, SPACE)); System.out.print(makeString(totalCharacters, CHARACTER)); System.out.println(); --totalSpaces; totalCharacters += 2; } }
public static void rhombus(int size) { pyramid(size); int totalSpaces = 1; int totalCharacters = 2 * size - 3; for (int row = 1; row <= size; ++row) { System.out.print(makeString(totalSpaces, SPACE)); System.out.print(crearString(totalCharacters, CHARACTER)); System.out.println(); ++totalSpaces; totalCharacters -= 2; } }
private static String makeFigure(int spaces, int characters, int size, int modifierSpaces, int modifierCharacters) { StringBuilder sb = new StringBuilder(); for (int row= 1; row <= size; ++row) { sb.append(makeString(spaces, SPACE)) .append(makeString(characters, CARACTER)) .append(String.format("%n")); spaces += modifierSpaces; characters += modifierCharacters; } return sb.toString(); }
public static void square(int size) { System.out.print(makeFigure(0, size, size, 0, 0)); } public static void pyramid(int size) { System.out.print(makeFigure(size - 1, 1, size, -1, 2)); } public static void rhombus(int size) { pyramid(size); System.out.print(makeFigure(1, 2 * size - 3, size, 1, -2)); }
public void foo(/* parameters */) { for (/* something */) { // code } }
public void bar(/* parameters */) { if (/* something */) { // code } else { // code } }
public void foo(/* parameters */) { for (/* something */) { auxFoo(/* some params */); } } private void auxFoo(/* parameters */) { // code }
public void barWhenIf(/* parameters */) { // code } public void barWhenElse(/* parameters */) { // code }
public void theOneThaCallsFoo(/* parameters */) { // code if (/* something */) { barWhenIf(/* arguments */); } else { barWhenElse(/* arguments */); } }
In reality it usually looks like this
public void theOneThaCallsFoo(/* parameters */) { // code T t = /* something */ ? v1 : v2; bar(/* arguments that include t */); }
List<Purchase> findTransactionBy(String firstName, String lastName)
List<Purchase> findPurchasesById(Person person)
List<Purchase> findPurchases(Criteria criteria)
public T foo() { try { // Code } catch(SomeException e) { // Exception handling code } }
So why none of the code
we tend to write, looks like that?
public T foo() { Bar bar = null; try { bar = something(); // Code } catch(SomeException e) { // Exception handling code } finally { if (bar != null) { try { bar.close(); } catch(AnotherException e) { // Code } } } }
public T foo(String path) { try(BufferedReader br = new BufferedReader(new FileReader(path))) { // read from the file } }
public T foo() { try { // Code } catch(SomeException e) { // Code } return bar; }
public T foo() { try { // Code } catch(SomeException e) { // Code } try { // Code } catch(OtherException e) { // Code } }
public T foo() { try { // Some code try { // Some code } catch(OtherException e) { // Some code } } catch(SomeException e) { // Some code } }
public T foo() { try { // Some code } catch(SomeException e) { try { // Some code } catch(OtherException e) { // Some code } } }
public void loadParameters() { Properties p = new Properties(); InputStream is = null; try { File file = new File("config.properties"); is = new FileInputStream(archivo); } catch (Exception e) { } try { propiedades.load(is); } catch (Exception e) { } String width = p.getProperty("width"); String height = p.getProperty("height"); this.imageWidth = Integer.parseInt(width); this.imageHeight = Integer.parseInt(height); }
public void loadParameters() throws FileNotFoundException, IOException { Properties p = new Properties(); InputStream is = new FileInputStream(archivo); propiedades.load(is); String width = p.getProperty("width"); String height = p.getProperty("height"); this.imageWidth = Integer.parseInt(width); this.imageHeight = Integer.parseInt(height); }
public class Main { public static void main(String... args) { ImageResize resizer = new ImageResize(); resizer.execute(); } }
public class Main { public static void main(String... args) { try { ImageResize resizer = new ImageResize(); resizer.execute(); } catch (FileNotFoundException e) { System.err.println("Config file does not exists"); } catch (IOException e) { System.err.println("Config file could not be read"); } } }
public class Main { public static void run() { ImageResize resizer = new ImageResize(); resizer.execute(); } public static void main(String... args) { try { run(); } catch (FileNotFoundException e) { System.err.println("Config file does not exists"); } catch (IOException e) { System.err.println("Config file could not be read"); } } }
private void resize() throws Exception { files = getNombreArchivos(); for (int i = 0; i < files.length; ++i) { String filename = reader.getPath() + files[i]; BufferedImage image = ImageIO.read(new File(nombreArchivo)); BufferedImage newImage = resizeImage(image); String newFilename = destination + files[i]; ImageIO.write(newImage, "jpg", new File(newFilename); } }
private void resize() { files = getNombreArchivos(); for (int i = 0; i < files.length; ++i) { handleImage(reader.getPath() + files[i]); } } private void handleImage(String filename) { try { doHandleImage(filename); } catch (IOException e) { System.out.println(String.format( "File %s wasn't processed", filename)); } } private void doHandleImage(String filename) { BufferedImage image = ImageIO.read(new File(filename)); BufferedImage newImage = resizeImage(image); String newFilename = destination + files[i]; ImageIO.write(newImage, "jpg", new File(newFilename); }
public T foo(/* some arguments */) { try { return doFoo(/* some arguments */); } catch(AnException e | OtherException e1) { // handle } catch(SomeException e) { // handle } } private T doFoo(/* some argmuments */) throws AnException, OtherException, SomeException { // Clean Code! Bar bar = foo.do(); // throws AnException bar.baz(); // throws OtherException if (foo.isBlitz()) { bar.platz(); // throws SomeException } return bar.doo(); }
public class ControllerA { private ServiceA service; // ServiceA is a Façade public ControllerA(ServiceA service) { this.service = service; } @RequestMapping("/foo") public String doSomething(Bar bar, Model model) { Foo foo = service.something(bar); model.addAttribute(foo); return "viewA"; } }
public class Fraction { private int numerator; private int denominator; private void normalize() { int GCF = gcf(numerator, denominator); numerator /= GCF; denominator /= GCF; } public Fraction(int numerator, int denominator) { this.numerator = numerator; this.denominator = denominator; normalize(); } private static int gcf(int a, int b) { // Euclid's algorithm return b == 0 ? a : gcf(b, a % b); } private static int lcm(int a, int b) { return a / gcf(a, b) * b; } public Fraction plus(Fraction other) { final int LCM = lcm(this.denominator, other.denominator); int denominator = LCM; int numerator = LCM / this.denominator * this.numerator + LCM / other.denominator * other.numerator; return new Fraction(numerator, denominator); } }
public class MathUtilities { private MathUtilities() {} public static int gcf(int a, int b) { return b == 0 ? a : gcf(b, a % b); } public static int lcm(int a, int b) { return a / gcf(a, b) * b; } }
public class Fraction { // Code public Fraction plus(Fraction other) { int LCM = MathUtilities.lcm(this.denominator, other.denominator); int denominator = LCM; int numerator = LCM / this,.denominator * this.numerator + LCM / other.denominator * other.numerator; return new Fraction(numerator, denominator); } }
import com.othercompany.foo.Foo; /** * Critical class for project! */ public class Bar { // Third-party utilitary class private Foo foo; public T platz() { // Code foo.doSomething(); // More code } }
public class Bar { private FooService foo; public Bar(FooService foo) { this.foo = foo; } public T platz() { // Code foo.doSomething(); // More code } }
public interface FooService {
T doSomething();
}
import com.othercompany.foo.Foo; public class OtherCompanyFoo implements FooService { private Foo foo = new Foo(); public T doSomething() { foo.doSomething(); } }
carlos.obregon@prodigious.cr
http://clean-coder.blogspot.com/
@gaijinco