Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411490 Posts in 69371 Topics- by 58428 Members - Latest Member: shelton786

April 25, 2024, 03:04:49 AM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)The "Elegant" Code Thread
Pages: [1] 2 3 4
Print
Author Topic: The "Elegant" Code Thread  (Read 5782 times)
Photon
Level 4
****


View Profile
« on: October 19, 2017, 09:40:40 AM »

On one hand, I like elegant code. On the other hand, I feel like I'm not very good at writing it. Its the constant struggle among the ideas of just getting something done, making something I'll be able to understand months down the road and making something that isn't a tangled mess.

So I want to see some examples of what you guys consider "elegant" code, whether it be from big-name projects or just your own.

Go!
Logged
ProgramGamer
Administrator
Level 10
******


aka Mireille


View Profile
« Reply #1 on: October 19, 2017, 10:13:38 AM »

I don't know if this counts, but I made a little macro thing a while ago to replicate the repeat statement from Game Maker in C++.

Code:
#define repeat(count) for(int i = 0; i < count; ++i)

repeat(5)
{
    //This code would execute five times
}
Logged

InfiniteStateMachine
Level 10
*****



View Profile
« Reply #2 on: October 19, 2017, 11:13:33 AM »

I find pattern matching against discriminated unions in a language that supports to be quite pretty because it's such a common problem and such an airtight way to solve it (say as opposed to a c union with a enum indicating the type and fallible case statements).

I was going to post an example but then I realized my gitlab stuff isn't visible publicly and I dont know what my password is Sad

EDIT : This article is pretty much the exact opposite of what I'm describing haha


https://bitbashing.io/std-visit.html

EDIT EDIT : This article describes what I'm talking about

https://fsharpforfunandprofit.com/posts/discriminated-unions/
Logged

InfiniteStateMachine
Level 10
*****



View Profile
« Reply #3 on: October 19, 2017, 11:19:05 AM »

One other one.

When I work with C# where the majority of queries are linq method syntax I find that both terse AND more readable than loops.

EX

var someSubGroupOfStuff = stuff.OrderByDescending(x => x.Id).Where(x => x.Id < 100).Take(10);
Logged

ferreiradaselva
Level 3
***



View Profile
« Reply #4 on: October 19, 2017, 02:48:17 PM »

I don't have any in hand now, but a function that doesn't dynamically allocate memory already gain some points with me.

APIs that take pointer to a structure and modify that structure is much more elegant (safer and flexible):

Code:

void init_nice(struct nice *n, int32_t x, int32_t y)
{
  n->i = x * y;
  n->x = x;
  n->y = y;
}

struct nice n;
init_nice(&n);

The user has more flexibility to allocate the structure the way they want.
Logged

qMopey
Level 6
*


View Profile WWW
« Reply #5 on: October 19, 2017, 06:46:33 PM »

I've been programming for about 7 years now, and have never once thought of code as elegant. Don't really get it. Why would anyone want "elegant" code? Actually for some time I used to think co-workers that strived for "elegant" code were just wasting their time, as if it was a sign of their inexperience. Harsh, I know, but I really just don't get it.

That said, I'm extra interested in seeing what you guys think of elegant! Maybe I could finally "get it" after seeing some examples.

For me, the best example I can think of is some code I wrote for doing a one-dimensional lerp to perform a 3D orthographic clipping of a polygon to the inside of a 3D AABB. Specifically, q3Orthographic used in q3Clip (but still, I would actually call this novel, moreso than "elegant")... It's doing one-dimensional dot products in there, along with Sutherland-Hodgman clipping  Grin

The algorithm goes something like this:
  • inverse transform geometry to a special reference frame
  • do sutherland hodgman clipping
  • perform 1d lerps via 1d dot products in the clipping routine
  • swap the input arguments to the clip routine each time it's called
  • transform geometry back into world space
  • the input geometry has now been orthographically clipped inside of a planar AABB
« Last Edit: October 19, 2017, 06:53:35 PM by qMopey » Logged
ferreiradaselva
Level 3
***



View Profile
« Reply #6 on: October 20, 2017, 06:43:11 AM »

At that time, I think I haven't even heard of "elegant code" (that's probably because I didn't have a "formal" education in programming). But, it's something that is easier to identify when you see it than to give a proper description. I think the Unix Philosophy has a good list of what a good program does, and that is applicable to programming too:

Quote
(i) Make each program do one thing well. To do a new job, build afresh rather than complicate old programs by adding new features.
(ii) Expect the output of every program to become the input to another, as yet unknown, program. Don't clutter output with extraneous information. Avoid stringently columnar or binary input formats. Don't insist on interactive input.
(iii) Design and build software, even operating systems, to be tried early, ideally within weeks. Don't hesitate to throw away the clumsy parts and rebuild them.
(iv) Use tools in preference to unskilled help to lighten a programming task, even if you have to detour to build the tools and expect to throw some of them out after you've finished using them.
Quote
1. Rule of Modularity: Write simple parts connected by clean interfaces.
2. Rule of Clarity: Clarity is better than cleverness.
3. Rule of Composition: Design programs to be connected to other programs.
4. Rule of Separation: Separate policy from mechanism; separate interfaces from engines.
5. Rule of Simplicity: Design for simplicity; add complexity only where you must.
6. Rule of Parsimony: Write a big program only when it is clear by demonstration that nothing else will do.
7. Rule of Transparency: Design for visibility to make inspection and debugging easier.
8. Rule of Robustness: Robustness is the child of transparency and simplicity.
9. Rule of Representation: Fold knowledge into data so program logic can be stupid and robust.
10. Rule of Least Surprise: In interface design, always do the least surprising thing.
11. Rule of Silence: When a program has nothing surprising to say, it should say nothing.
12. Rule of Repair: When you must fail, fail noisily and as soon as possible.
13. Rule of Economy: Programmer time is expensive; conserve it in preference to machine time.
14. Rule of Generation: Avoid hand-hacking; write programs to write programs when you can.
15. Rule of Optimization: Prototype before polishing. Get it working before you optimize it.
16. Rule of Diversity: Distrust all claims for “one true way”.
17. Rule of Extensibility: Design for the future, because it will be here sooner than you think.
http://www.catb.org/esr/writings/taoup/html/ch01s06.html

I think that the rules of Modularity, Clarity, Composition, Separation and Parsimony are broken by many programmers.

To me, the importance of elegance (simplicity) is for making code more readable and maintainable, it's not about fancy optimizations. If the non-optimized code can do the job just fine, I'd prefer the non-optimized code.
Logged

InfiniteStateMachine
Level 10
*****



View Profile
« Reply #7 on: October 20, 2017, 06:57:41 AM »

I've been programming for about 7 years now, and have never once thought of code as elegant. Don't really get it. Why would anyone want "elegant" code? Actually for some time I used to think co-workers that strived for "elegant" code were just wasting their time, as if it was a sign of their inexperience. Harsh, I know, but I really just don't get it.

That said, I'm extra interested in seeing what you guys think of elegant! Maybe I could finally "get it" after seeing some examples.

For me, the best example I can think of is some code I wrote for doing a one-dimensional lerp to perform a 3D orthographic clipping of a polygon to the inside of a 3D AABB. Specifically, q3Orthographic used in q3Clip (but still, I would actually call this novel, moreso than "elegant")... It's doing one-dimensional dot products in there, along with Sutherland-Hodgman clipping  Grin

The algorithm goes something like this:
  • inverse transform geometry to a special reference frame
  • do sutherland hodgman clipping
  • perform 1d lerps via 1d dot products in the clipping routine
  • swap the input arguments to the clip routine each time it's called
  • transform geometry back into world space
  • the input geometry has now been orthographically clipped inside of a planar AABB


Might just be the choice of the word "elegant". The example I posted regarding the linq stuff is mainly a common pattern that people tend to do with a lot of temporary variables and loops and can have a lot of slight variations. I find the linq method syntax example "elegant" because it's both easier to read and less prone to errors (no loop state variables or visible temps).
Logged

J-Snake
Level 10
*****


A fool with a tool is still a fool.


View Profile WWW
« Reply #8 on: October 30, 2017, 06:26:20 PM »

For those who are familiar with compiler-construction basics, "recursive-descent parsing" is certainly considered elegant.

But "elegant code" has no clear semantics and can be misleading. Like there is beauty on the outside there is also an inner beauty. While code can appear elegant on the outside it can be dirty on lower levels. How well can you translate a high level construct to code the machine can easily "digest", that will determine the inner beauty of the code. Ideally there is a match in inner and outer beauty, but it is not always possible.
Logged

Independent game developer with an elaborate focus on interesting gameplay, rewarding depth of play and technical quality.<br /><br />Trap Them: http://store.steampowered.com/app/375930
InfiniteStateMachine
Level 10
*****



View Profile
« Reply #9 on: October 31, 2017, 08:13:23 AM »

it's like beauty or art etc. It's subjective
Logged

bateleur
Level 10
*****



View Profile
« Reply #10 on: November 02, 2017, 09:04:01 AM »

For me, elegant code is defined by the negative space that is ugly code. I don't notice elegant code. I notice when something's hard to read, semantically nasty or inefficient. Some examples:

* Javascript's scoping rules.
* Doing things in loops that could be done outside the loop.
* Functions that take lots of non-optional parameters.
* Code which is full of calls but you can't tell which code is being called.
* Code which uses five classes and ten interfaces for a job one class could do just fine.
* 200+ line functions.
* Almost anything written in C++, especially by me.
* Memory allocation happening avoidably inside the game loop.
* Hardcoded magic numbers.
* Tab characters in source code.
* Any style of parenthesis use which doesn't exactly match my personal preferences.
* Code comments with no capital letters (or all capital letters, but that's mercifully rare).
* Use of inappropriate design patterns because the programmer bought a book on design patterns.
* Using <boolean expression>?<value 1>:<value 2> in code written after 1980.
* Needlessly abbreviated variable names.
* Using horrible hacks where the language/environment has a perfectly good way to do the thing built in.

etc. etc.

Basically I hate most code, so when I find something I don't hate it's an unexpected pleasure!
Logged

InfiniteStateMachine
Level 10
*****



View Profile
« Reply #11 on: November 02, 2017, 09:35:28 AM »

If you ever have to read my code, I apologize in advance :D
Logged

Crimsontide
Level 5
*****


View Profile
« Reply #12 on: November 02, 2017, 11:50:25 AM »

"Perfection is Achieved Not When There Is Nothing More to Add, But When There Is Nothing Left to Take Away"

I always have mixed feelings when I finish a project, as it usually ends up being much smaller/simpler in the end than when I started prototyping.  On one hand I'm happy that it turned out so clean, simple, and elegant.  On the other hand I always feel a little cheated for putting so much time and effort for (what often ends up being) so little code.

*edit: tabs > spaces
Logged
Ordnas
Level 10
*****



View Profile WWW
« Reply #13 on: November 03, 2017, 12:54:10 AM »

I remember Bjarne Stroustrup mentioning in his book his ideal lines per function of around 10, against the 40 lines per function that much everyone else consider the optimal one. I am confortable with that, it is more probable that it will come out a more modular code.
Logged

Games:

JWki
Level 4
****


View Profile
« Reply #14 on: November 03, 2017, 04:25:24 AM »

I remember Bjarne Stroustrup mentioning in his book his ideal lines per function of around 10, against the 40 lines per function that much everyone else consider the optimal one. I am confortable with that, it is more probable that it will come out a more modular code.

Opinions differ on whether one should listen to Bjarne Stroustrup when it comes to programming but regardless of whoever says it I highly disagree with that and prefer this as external advice if any should be given:

http://number-none.com/blow/john_carmack_on_inlined_code.html

In my code you will find super short functions but you'll also find one or two that are a few hundred lines of code - my recent prototyping playground has like three 1k+ line functions. Now I'd say that's probably too much but I don't think you can always chunk up code into 10, 20, 30, 40 or even 100 line segments without hurting readability.
Logged
InfiniteStateMachine
Level 10
*****



View Profile
« Reply #15 on: November 03, 2017, 06:51:49 AM »

Definitely, I'm very much against that whole 20-40 lines max per function stuff. That makes some code extremely unreadable if I have to keep jumping around the file. Especially if it's mostly sequential. If you extract a function that's only called in one place by another function then I don't really think that does anything for readability.

I'm a fan of languages that support local function definitions for code that's used more than once in a single function. Failing that you can always use a lambda.
Logged

oahda
Level 10
*****



View Profile
« Reply #16 on: November 03, 2017, 09:32:54 AM »

Then there was me back when I was ~13 and learning web and coded up a large community/newsportal website in one single bit 13k-or-so PHP/HTML file. Durr...?
Logged

NowSayPillow
Level 1
*


John Carmack Clone


View Profile WWW
« Reply #17 on: November 03, 2017, 10:48:05 AM »

I remember Bjarne Stroustrup mentioning in his book his ideal lines per function of around 10, against the 40 lines per function that much everyone else consider the optimal one. I am confortable with that, it is more probable that it will come out a more modular code.

Opinions differ on whether one should listen to Bjarne Stroustrup when it comes to programming but regardless of whoever says it I highly disagree with that and prefer this as external advice if any should be given:

http://number-none.com/blow/john_carmack_on_inlined_code.html

In my code you will find super short functions but you'll also find one or two that are a few hundred lines of code - my recent prototyping playground has like three 1k+ line functions. Now I'd say that's probably too much but I don't think you can always chunk up code into 10, 20, 30, 40 or even 100 line segments without hurting readability.

As with most things I agree entirely with John C. here. I generally only break code up into functions if there's repeated code. If a function is doing the one thing it's designed to do, and there's no repetition in the code then I really don't care how long it gets. There's nothing I hate more than having to jump all over a file just to follow a straight line of logic. Coffee
Logged

InfiniteStateMachine
Level 10
*****



View Profile
« Reply #18 on: November 03, 2017, 02:13:48 PM »

Then there was me back when I was ~13 and learning web and coded up a large community/newsportal website in one single bit 13k-or-so PHP/HTML file. Durr...?

heh, yeah that's probably crosses the threshold :D

I once got a task to improve a computer vision application. It was a C program with a main that was a few thousand lines. At the time I remember thinking it was a nightmare but now that I've seen some pretty rough inheritance/callback nightmares I don't find it so bad. FWIW the program didn't have a lot of jumps so I could read it from top to bottom. The main issue was just keeping track of the state of locals.
Logged

ferreiradaselva
Level 3
***



View Profile
« Reply #19 on: November 03, 2017, 02:56:39 PM »

Quote
don't notice elegant code. I notice when something's hard to read, semantically nasty or inefficient.

This is true, hahaha, if this thread was the "unelegant code", there's a lot of examples on the internet.
Logged

Pages: [1] 2 3 4
Print
Jump to:  

Theme orange-lt created by panic