this post was submitted on 09 Aug 2024
602 points (98.2% liked)

Programmer Humor

31997 readers
552 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 

Those who know, know.

you are viewing a single comment's thread
view the rest of the comments
[–] shy_mia@lemmy.blahaj.zone 38 points 1 month ago* (last edited 1 month ago) (12 children)

I've found it's mostly two things: readability (ironically) and performance. I'll describe a few crude examples, but I won't get too much into specifics, otherwise I might as well write another book myself.

The performance part is simple: its excessive reliance on polymorphism and the presence of several levels of abstraction just doesn't allow for good code generation. I've seen 10x+ performance improvements by dropping all of the above, with often minimal loss in readability; on the contrary, oftentimes the code became more readable as well.

The readability part is harder to explain; not only because it depends on the codebase and the problem at hand, but also on the coding style each programmer has (though in my opinion, in that particular case it's the programmer's problem, not the codebase's).
I like to think of codebases as puzzles. To understand a codebase, you need to piece together said puzzle. What I've found with Clean Code codebases is that each piece of the puzzle is itself a smaller puzzle to piece together, which isn't ideal.

Functions

They should be small and do one thing

I generally disagree, not because those ideas are wrong, but because they're often too limiting.
What often happens by following those principles is you end up with a slew of tiny functions scattered around your codebase (or a single file), and you are forced to piece together the behaviour they exhibit when called together. Your code loses locality and, much like with CPU cache locality, your brain has to do extra work to retrieve the information it needs every time it needs to jump somewhere else.
It may work for describing what the code does at a high level, but understanding how it works to make meaningful changes will require a lot more work as a result.

Don't repeat yourself

Once again, it makes sense in principle, but in practice it often creates more problems. I agree that having massive chunks of repeated code is bad, no questions about it, but for smaller chunks it may actually be desirable in some circumstances.
By never repeating code, you end up with functions that are over-parameterized to account for all possible uses and combinations that particular code snippet needs to work with. As a result, that code becomes more complex, and the code that calls it does too, because it requires you to know all the right parameters to pass for it to do the right thing.

Exceptions

Exceptions are just bad. They are a separate, hidden control flow that you constantly need to be wary of.
The name itself is a misnomer in my opinion, because they're rarely exceptional: errors are not just common, but an integral part of software development, and they should be treated as such.
Errors as values are much clearer, because they explicitly show that a function may return an error and that it should be handled.

Classes, interfaces and polymorphism

I have lots of gripes with object orientation. Not everything needs to be an object, not everything needs to be polymorphic. There's no need to have a Base64Decoder, much less an IBase64Decoder or an AbstractBase64Decoder. Base64 only works one way, there are no alternative implementations, a function is enough.

I'm a lot more on the data oriented side of the isle than the OO one, but I digress.
Object orientation can be good in certain contexts, but it's not a silver bullet.

Encapsulation for the sake of it

Let's say you have something like this:

class Point {
	public float X, Y;
}

With the Clean Code approach, it magically becomes:

class Point {
	private float x, y;
	
	public float get_x() {
		return this.x;
	}
	public float get_y() {
		return this.y;
	}
	public void set_x(float x) {
		this.x = x;
	}
	public void set_y(float y) {
		this.y = y;
	}
}

Why? Who the hell knows. It makes absolutely no tangible difference, it only makes your code longer and more verbose. Now, if a value needs validation, sure, but oftentimes this is just done regardless and it drives me insane.

Abstract classes for everything!

  • "You'll never know when you'll need to add another implementation, right?"
  • "You don't need to know the underlying implementation"

The problem with wanting to create the most generalized code in advance is that you end up stuck in abstraction hell.
You may as well not need the ability to have arbitrary implementations, but now you need to plan for that.

Not only that, but it also makes reasoning about your code harder: how many times have you had to step through your code just to figure out what was being executed | just to figure out what particular concrete class was hiding behind an abstract class reference?
I myself, way too many, and there was often no reason for that.

Also, the idea that you shouldn't know about the implementation is crazy to me. Completely encapsulating data and behaviour not only makes you miss out on important optimizations, but often leads to code bloat.

There's more but I'm tired of typing :)

Take a look at these if you want more info or someone else's view on the matter, I wholeheartedly recommend both:

[–] bleistift2@sopuli.xyz 16 points 1 month ago* (last edited 1 month ago) (4 children)

Functions should be small and do one thing […] you end up with a slew of tiny functions scattered around your codebase (or a single file), and you are forced to piece together the behaviour they exhibit when called together

I believe you have a wrong idea of what “one thing” is. This comes together with “functions should not mix levels of abstraction” (cited from the first blog entry you referenced). In a very low-level library, “one thing” may be sending an IP packet over a network interface. Higher up, “one thing” may be establishing a database connection. Even higher up, “one thing” may be querying a list of users from the database, and higher up yet again is responding to the GET /users http request. All of these functions do ‘one thing’, but they rely on calls to a few methods that are further down on the abstraction scheme.

By allowing each function to do ‘one thing’, you decompose the huge problem that responding to an HTTP request actually is into more manageable chunks. When you figure out what a function does, it’s way easier to see that the function connectToDb will not be responsible for why all users are suddenly called "Bob". You’ll look into the http handler first, and if that’s not responsible, into getUsersFromDb, and then check what sendQuery does. If all methods truly do one thing, you’ll be certain that checkAuthorization will not be related to the problem.

Tell me if I just didn’t get the point you were trying to make.

Edit: I just read

Martin says that functions should not be large enough to hold nested control structures (conditionals and loops); equivalently, they should not be indented to more than two levels. He says blocks should be one line long, consisting probably of a single function call. […] Most bizarrely, Martin asserts that an ideal function is two to four lines of code long.

If that’s the standard of “doing one thing”, then I agree with you. This is stupid.

[–] shy_mia@lemmy.blahaj.zone 6 points 1 month ago* (last edited 1 month ago) (2 children)

Yeah that was essentially what I was referring to (referring to your edit).

I generally dislike stuff like (crappy example incoming):

void do_stuff(int count, bool cond) {
	function1(count);
	function2(b);
	function3();
}

void function1(int count) {
	for (var i = 0; i < count; i++) {
		...
	}
}

void function2(bool cond) {
	if (cond) { ... }
	else { ... }
}

void function3() {
	...
}

I'm not a fan of this kind of code fragmentation.
If all those actions were related and it could have been just one thing, retaining a lot more context, then it should be one function imo.
If by not splitting it it became massive with various disconnected code blocks, sure, but otherwise I'd much prefer being able to read everything together.

If splitting the functions required producing side effects to maintain the same functionality, then that's even worse.

[–] flying_sheep@lemmy.ml 4 points 1 month ago* (last edited 1 month ago) (1 children)

Huh, I really like code like that. Having a multi-step process split up into sections like that is amazing to reason about actual dependencies of the individual sections. Granted, that only applies if the individual steps are kinda independently meaningful

To adapt your example to what I mean:

Baz do_stuff(int count, boolean cond) {
	Foo part1 = function1(count);
	Bar part2 = function2(cond);
	return function3(part1, part2);
}

This allows you to immediately see that part1 and part2 are independently calculated, and what goes into calculating them.

There are several benefits, e.g.:

  1. if there is a problem, you can more easily narrow down where it is (e.g. if part2 calculates as expected and part1 doesn't, the problem is probably in function1, not function2 or function3). If you have to understand the whole do_stuff before you can effectively debug it, you waste time.
  2. if the function needs to be optimized, you know immediately that function1 and function 2 can probably run in parallel, and even if you don't want to do that, the slow part will show up in a flame graph.
[–] shy_mia@lemmy.blahaj.zone 5 points 1 month ago

It really depends on the context frankly. I did say it was a crappy example ;)
Try to read this snippet I stole from Clean Code and tell me if it's readable without having to uselessly jump everywhere to understand what's going on:

public class SetupTeardownIncluder {
  private PageData pageData;
  private boolean isSuite;
  private WikiPage testPage;
  private StringBuffer newPageContent;
  private PageCrawler pageCrawler;


  public static String render(PageData pageData) throws Exception {
    return render(pageData, false);
  }

  public static String render(PageData pageData, boolean isSuite) throws Exception {
    return new SetupTeardownIncluder(pageData).render(isSuite);
  }

  private SetupTeardownIncluder(PageData pageData) {
    this.pageData = pageData;
    testPage = pageData.getWikiPage();
    pageCrawler = testPage.getPageCrawler();
    newPageContent = new StringBuffer();
  }

  private String render(boolean isSuite) throws Exception {
     this.isSuite = isSuite;
    if (isTestPage())
      includeSetupAndTeardownPages();
    return pageData.getHtml();
  }

  private boolean isTestPage() throws Exception {
    return pageData.hasAttribute("Test");
  }

  private void includeSetupAndTeardownPages() throws Exception {
    includeSetupPages();
    includePageContent();
    includeTeardownPages();
    updatePageContent();
  }


  private void includeSetupPages() throws Exception {
    if (isSuite)
      includeSuiteSetupPage();
    includeSetupPage();
  }

  private void includeSuiteSetupPage() throws Exception {
    include(SuiteResponder.SUITE_SETUP_NAME, "-setup");
  }

  private void includeSetupPage() throws Exception {
    include("SetUp", "-setup");
  }

  private void includePageContent() throws Exception {
    newPageContent.append(pageData.getContent());
  }

  private void includeTeardownPages() throws Exception {
    includeTeardownPage();
    if (isSuite)
      includeSuiteTeardownPage();
  }

  private void includeTeardownPage() throws Exception {
    include("TearDown", "-teardown");
  }

  private void includeSuiteTeardownPage() throws Exception {
    include(SuiteResponder.SUITE_TEARDOWN_NAME, "-teardown");
  }

  private void updatePageContent() throws Exception {
    pageData.setContent(newPageContent.toString());
  }

  private void include(String pageName, String arg) throws Exception {
    WikiPage inheritedPage = findInheritedPage(pageName);
    if (inheritedPage != null) {
      String pagePathName = getPathNameForPage(inheritedPage);
      buildIncludeDirective(pagePathName, arg);
    }
  }

  private WikiPage findInheritedPage(String pageName) throws Exception {
    return PageCrawlerImpl.getInheritedPage(pageName, testPage);
  }

  private String getPathNameForPage(WikiPage page) throws Exception {
    WikiPagePath pagePath = pageCrawler.getFullPath(page);
    return PathParser.render(pagePath);
  }

  private void buildIncludeDirective(String pagePathName, String arg) {
    newPageContent
      .append("\n!include ")
      .append(arg)
      .append(" .")
      .append(pagePathName)
      .append("\n");
  }
}

That's what I was talking about.

load more comments (1 replies)
load more comments (8 replies)