Ask HN: How to Write Readable Code
1–10 of 13 posts
Re: Ask HN: How to Write Readable Code
#2(Looking back I often wonder how long this guy wrote code like this before someone said “knock it off”..)
Re: Ask HN: How to Write Readable Code
#3Re: Ask HN: How to Write Readable Code
#4``` if service_is_disabled: start_service() else: send_notification(“Service is running”) ```
Re: Ask HN: How to Write Readable Code
#5What does “code like prose” look like? I had a group project in college with a guy who used MS Word to write code in paragraphs..formatted like an English paper (I’m not kidding); is this what you mean? (Looking back I often wonder how long this guy wrote code like this before someone said “knock it off”..)
function test_addition() {
given_two_integers(2,3);
when_summed_up();
then_the_result_should_be(5);
}
Whereas I would prefer something like function test_addition() {
int a = 2;
int b = 3;
int result = new Addition(a, b);
Assert.AreEqual(result.Sum(), 5);
}
For a non-coder it might seem more intuitive to read the first example, because it only contains natural language.
For a coder it seems more intuitive to read the second example, because it prevents "method hopping" (I have to go into the methods from example one to see what's actually happening inside them).Re: Ask HN: How to Write Readable Code
#6You might want to look at BDD. It's a way to be able to discuss what has to happen and use code to make it happen.
Re: Ask HN: How to Write Readable Code
#7Re: Ask HN: How to Write Readable Code
#8Re: Ask HN: How to Write Readable Code
#9What does “code like prose” look like? I had a group project in college with a guy who used MS Word to write code in paragraphs..formatted like an English paper (I’m not kidding); is this what you mean? (Looking back I often wonder how long this guy wrote code like this before someone said “knock it off”..)
Regarding a unit test it looks something like this in pseudocode: function test_addition() { given_two_integers(2,3); when_summed_up(); then_the_result_should_be(5); } Whereas I would prefer something like function test_addition() { int a = 2; int b = 3; int result = new Addition(a, b); Assert.AreEqual(result.Sum(), 5); } For a non-coder it might seem more intuitive to read the first example, because it only contains…
Re: Ask HN: How to Write Readable Code
#10I’ve always tried to use naming of variables and methods to make it obvious what the code is doing. Something like: ``` if service_is_disabled: start_service() else: send_notification(“Service is running”) ```