Thread: How to more intuitively wrote more elegant c++ code?

  1. #1
    Registered User
    Join Date
    Jun 2016
    Posts
    40

    How to more intuitively wrote more elegant c++ code?

    When writing programs, my code tends to be very inelegant; I just have very little intuition for writing code that isn't longer than it needs to be.

    Is there anything I could do to improve my thinking, so that when I write a program, the code isn't so ugly right off the bat? I already know about pseudocode, but my not-too-ugly pseudocode tends to get translated into very ugly actual code.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Give us an example of your raw code, and we can come up with ways to improve it.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,739
    Don't beat yourself up about it. To write elegant code, you need experience. Planning plays a critical role in big projects, but single-file solutions can be just mentally mapped/planned and the code flows out of your fingers without even thinking about it.
    Devoted my life to programming...

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    A few very important things to keep in mind any time you write code:

    Consistent indentation and formatting.
    Descriptive identifier (variables, functions, classes, etc.) names.
    Keep functions short - ideally no longer than the height of your screen.
    Keep functions simple - one purpose and responsibility.
    Avoid global variables, and prefer passing things around as parameters. If you must have a global variable, consider making it a static member of a class or struct, or wrap it in a namespace, possibly named "globals."
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  5. #5
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I also feel like elegance is dependent upon your skill level as well as your overall knowledge of C++.

    I think that on the quest to inner peace as a programmer in general, you should write something you think is elegant now and come back to it later and gasp in horror and its absolute inelegance. Then refactor it until it's once again become elegant. Rinse and repeat this process until you retire.

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,616
    I feel like for a lot of your problems that I've seen, elegance is the same as knowing how to solve it more or less. For example, in this problem all you really need is a function that determines if a number is prime and a decent algorithm to find the prime factors of a given number.

    Sure, I could write a solution in fewer lines, and I have, (It runs in about 1 second! XD) but if you take a look at the components of the answer, it has the same functions. So what basis do we have to say your code is inelegant?

    On top of that, some people would prefer a program with all of these bullet points addressed:
    • There is no vector of all the integers found.
    • Another way to write the program is to use remove_if() from the STL to reduce a larger vector containing all the integers below 1,000.
    • The only way to reuse the IsPrime() function and GetFactors() function in another program is basically to copy and paste currently. These components ought to be reusable.


    To address these points, you basically have to re-write my program but there are reasons not to like what I did. What you should take away is that elegance can be more about hitting a certain sweet spot.

  7. #7
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Going off what whiteflags said, I'd also recommend embracing the STL as much as possible. The STL is expressive and decently performant. Honestly, until you have a proven bottleneck, I'd make the assumption that the STL code will be "fast enough".

    But yeah, modularize. Separate interface from implementation by pulling things into well-named functions.

    Also, write tests. Write. Tests. If you are going to refactor code at any point in the future, you better have a test-suite backing it up. Tests are great because they also force you to write code that is a) easily testable and b) they test your code.

    Reading code is also a good way to get better but Lord help us all, C++ is one ugly language.

  8. #8
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    Quote Originally Posted by MutantJohn View Post
    I think that on the quest to inner peace as a programmer in general, you should write something you think is elegant now and come back to it later and gasp in horror and its absolute inelegance. Then refactor it until it's once again become elegant. Rinse and repeat this process until you retire.
    This is what I've done with code I decide I'm going to keep. Review as best I can, go back and look at it again a few days later, look at it again in a month or two, until I settle on it being good.

  9. #9
    Registered User
    Join Date
    Jun 2016
    Posts
    40
    Quote Originally Posted by Elkvis View Post
    Give us an example of your raw code, and we can come up with ways to improve it.
    Well, I dont need to know how to improve a specific program I wrote; I just asked for tips on writing programs shorter than they need be. But if you need the best example of my inelegant code, look here: http://cboard.cprogramming.com/redir...2Fe2cc640466d5

    Though in my defense, that problem was far too advanced for the chapter it was introduced in; never seen a good solution for that that didnt involve recursion. Keep in mind that recursion was taught well after that point in the book, so yeah ^^;

    Quote Originally Posted by GReaper View Post
    Don't beat yourself up about it. To write elegant code, you need experience. Planning plays a critical role in big projects, but single-file solutions can be just mentally mapped/planned and the code flows out of your fingers without even thinking about it.
    All right. I certainly dont have much (if any) meaningful experience.

    Quote Originally Posted by Elkvis View Post
    A few very important things to keep in mind any time you write code:

    Consistent indentation and formatting.
    Descriptive identifier (variables, functions, classes, etc.) names.
    Keep functions short - ideally no longer than the height of your screen.
    Keep functions simple - one purpose and responsibility.
    Avoid global variables, and prefer passing things around as parameters. If you must have a global variable, consider making it a static member of a class or struct, or wrap it in a namespace, possibly named "globals."
    I got all of those except the third and maybe fifth one.

    Quote Originally Posted by MutantJohn View Post
    I also feel like elegance is dependent upon your skill level as well as your overall knowledge of C++.

    I think that on the quest to inner peace as a programmer in general, you should write something you think is elegant now and come back to it later and gasp in horror and its absolute inelegance. Then refactor it until it's once again become elegant. Rinse and repeat this process until you retire.
    I get what you mean about skill and overall knowledge, but what if I write a program for the first time, and think its ugly?

  10. #10
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I get what you mean about skill and overall knowledge, but what if I write a program for the first time, and think its ugly?
    For one, write tests that verify the behavior.

    Then refactor, refactor and refactor.

    Run it through your tests and make sure you didn't break anything.

    By "write tests", you could always do what I do, just fill your main with a bunch of calls to functions that are full of assert statements. I know there are some frameworks out there but for me, I don't mind just assert statements that are ultimately called from the main.

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,616
    Tesp, most of your posts at bpaste have 404'd. I thought you should know.

  12. #12
    Registered User
    Join Date
    Jun 2016
    Posts
    40
    Quote Originally Posted by MutantJohn View Post
    For one, write tests that verify the behavior.

    Then refactor, refactor and refactor.

    Run it through your tests and make sure you didn't break anything.

    By "write tests", you could always do what I do, just fill your main with a bunch of calls to functions that are full of assert statements. I know there are some frameworks out there but for me, I don't mind just assert statements that are ultimately called from the main.
    I have written simple tests for all my assignments, but I'm not yet familiar with assert statements. I'll use those when I learn them. Thanks

    Quote Originally Posted by whiteflags View Post
    Tesp, most of your posts at bpaste have 404'd. I thought you should know.
    Odd. Thought I set the expiry to "never". Well, I can't edit those past posts, so I guess I'll have to leave that as is :/

  13. #13
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I have written simple tests for all my assignments, but I'm not yet familiar with assert statements. I'll use those when I learn them. Thanks
    All they do is crash your code if what you pass in isn't true.

    For example,
    Code:
    assert((1 == 2));
    will just flat out crash your code.

    This is useful in testing because if you write a function that is supposed to remove all odd numbers from an array, it's really useful to test it by doing this:
    Code:
    for (auto a : my_array)
        assert((a % 2 == 0));

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by MutantJohn View Post
    All they do is crash your code if what you pass in isn't true.
    That's not true.
    Also, most debuggers will break on failed assertions. And some implementations will show an error dialog.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 10-09-2011, 03:01 AM
  2. how to make this 10 lines more elegant?
    By Ignazio Calò in forum C Programming
    Replies: 2
    Last Post: 06-08-2011, 04:19 PM
  3. How can I make this code more elegant?
    By ejohns85 in forum C++ Programming
    Replies: 3
    Last Post: 04-02-2009, 08:55 AM
  4. I wrote a piece of code, can't find where is the bug....
    By meili100 in forum C++ Programming
    Replies: 7
    Last Post: 06-08-2007, 11:25 AM
  5. The Elegant Universe
    By DISGUISED in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 08-21-2002, 12:54 PM

Tags for this Thread