r/shittyprogramming • • Dec 02 '15

Pls critique my code style

Of late I've become dissatisfied with statements like

x += 5;

because they seem to me to be insufficiently self-documenting. So I've begun factoring all my operations like this into self-documenting functions, so the above, for example becomes

int giveMeAnIntegerAndIllAddFiveToIt(int x)
{
    return x + 5;
}

But in the end, is

x = giveMeAnIntegerAndIllAddFiveToIt(x);

any better? There's still far too much going on here that isn't (self-)documented. Clearly further factorization is needed:

void giveMeAPointerToAnIntegerAndIllAssignANewValueToItItBeingTheVariableNotThePointerAlsoPleaseProvideTheNewValueYouWishToAssign(int *x, int newValue)
{
    *x = newValue;
}

So now the original statement would look like:

giveMeAPointerToAnIntegerAndIllAssignANewValueToItItBeingTheVariableNotThePointerAlsoPleaseProvideTheNewValueYouWishToAssign(&x, giveMeAnIntegerAndIllAddFiveToIt(x));

Much clearer. But I'm still worried that there might be something going on here that isn't self-documented. I don't want someone else to run my code and say, "Whoa, I wasn't expecting that to happen!" Is there anything else I can do to avoid such ambiguities?

290 Upvotes

56 comments sorted by

4

u/madhousechild Dec 03 '15

I like how you said "please" but can you also work in "thank you" and "you're welcome"?

5

u/[deleted] Dec 03 '15

This is a good idea. Ideally the function should take a third parameter, in which the caller passes a char buffer of at least 10 bytes, which the function will fill with the string "Thank you". I think it's worth the extra work in the name of civility.

193

u/Gera- Dec 02 '15

Hmm. x? That's a little vague. Maybe call it variableWellBeAddingANumberToOnceWeHaveTheNumberEnteredByTheUser

21

u/[deleted] Dec 03 '15

That's still pretty unclear. If only he were using perl 6! The variable could be named variable-We'll-Be-Adding-A-Number-To-Once-We-Have-The-Number-Entered-By-The-User!

15

u/the_omega99 Dec 03 '15

Wow Perl. WTF? Single quotes I can understand (Haskell did it), but minus signs?

8

u/Sheepshow Dec 03 '15

I think you mean

variableWe'llBeAddingANumberToOnceWeHaveTheNumberEnteredByTheUser

Please don't separate words. I can'tReadWordsThatAren'tAllCrammedTogetherAndBesidesWhiteSpaceMakesYourCodeSlower,Plus,TitleCaseIsSoMuchEaseirToReadThanksInAdvance.

2

u/memeticmachine Dec 04 '15 edited Dec 04 '15
void give_me_an_integer (int& learn_to_use_references, int (*learn_to_use_function_pointers)(int)) {
    learn_to_use_references = learn_to_use_function_pointers(learn_to_use_references);
}

int I_will_add_five_to_it(int x) {
    return x + 5;
}

So much more clear:

give_me_an_integer (x, &I_will_add_five_to_it);

2

u/[deleted] Dec 05 '15

references

C 4 lyfe scrubs

4

u/memeticmachine Dec 05 '15
extern "C" ...

there! happy?

80

u/ryeguy Dec 03 '15

I think giveMeAnIntegerAndIllAddFiveToItis misleading because the name implies it modifies the integer in place, which it doesn't. I'd suggest giveMeAnIntegerAndIllGiveYouBackANewInteger5HigherThanTheIntegerYouGaveMe, it's much more succinct.

Naming your functions verbosely doesn't just help humans, it helps computers too. Your code will run faster since the compiler will be able to better understand the function and generate more efficient code for it.

54

u/canada_mike Dec 03 '15

Verbosity is the key to clarity. This is such an elegant piece of code I'm almost in tears. Well done

39

u/dcwj Dec 03 '15

giveMeARedditorAndIWillShowHimAPieceOfCodeSoElegantThatItWillBringHimAlmostToTears(canada_mike);

3

u/fluffyponyza Dec 07 '15

"canada_mike" plz, unless you're referencing the canada_mike constant

39

u/amazing_rando Dec 03 '15

Macros are the key to clarity.

#define now_equals_five_more_than_its_original_value += 5

21

u/symberke Dec 03 '15

is it bad that i kind of like this

14

u/Neebat Dec 03 '15

Yes. It's very cobolish.

6

u/shvelo Dec 03 '15

#define quite

3

u/pouja Dec 03 '15

reference error 'quit' unknown statement

46

u/Treas0n Dec 03 '15

I love this method. You clearly have learned a lot from objective-c

16

u/xkufix Dec 03 '15

stringByAppendingString ... somebody had to sit there and think "yes, that's the best way to name a method which concatenates strings".

8

u/ekolis Dec 03 '15

"We want this language to be accessible to junior high students developing iOS apps. How many of those kids will know what 'concatenate' means?"

5

u/stormcrowsx Dec 03 '15

I don't know about you but I never used the word append prior to coding either. "Sorry sir, you must append yourself to the end of line before I can help you"

6

u/ekolis Dec 03 '15

"'Enqueue'? Do you watch a lot of British TV? I swear I heard that word on Doctor Who or something once..."

3

u/Smooth_McDouglette Dec 03 '15

Bahaha my first thought as well.

Although to be fair it's a nice feature of objective c when you have methods with really complicated signatures.

-6

u/[deleted] Dec 03 '15

What do you mean? It's obviously java since the functions are returning an int.

16

u/Klogga Dec 03 '15

I forgot pointers were introduced in Java 13

-6

u/[deleted] Dec 03 '15

Are you fucking stupid? Java always had pointers. Also there is no Java 13. It's like this sub-reddit is for stupid people or something.

0

u/[deleted] Dec 03 '15

[deleted]

2

u/DarkSorcerer Dec 03 '15

Look what sub you're in...

0

u/[deleted] Dec 03 '15

Uh, you wanna give my posts another look?

21

u/judenjager Dec 03 '15

I suggest using an OOP approach to this like so:

class AbstractFunctionGeneratorFactoryGeneratorFactorySingleton { private: std::function<int(int)> myAdderFunctor;

public: AbstractFunctionGeneratorFactoryGeneratorFactorySingleton(std::function<int(int)> myAbstractFunction){ this->myAdderFunctor = myAbstractFunction; }

int operator()(int value){ return this->myAdderFunctor(value); } };

14

u/[deleted] Dec 03 '15

I feel like the ampersand is confusing. I recommend:

#define pointerToInteger &

15

u/Spire Dec 03 '15

No, it should be:

#define pointerToInteger(x) reinterpret_cast<int *>(&x)

6

u/[deleted] Dec 03 '15

Holy shit! You're absolutely correct

11

u/sutronice Dec 02 '15

Looks great. Could we wrap that last statement so that we only need to pass in x?

21

u/amazing_rando Dec 03 '15

giveMeAnIntegerAndIllAddFiveToIt would be perfect for that, but its name is already taken. Maybe giveMeAnIntegerAndIWillAddFiveToIt?

11

u/LondonNoodles Dec 03 '15

I would personally change it to :

 char * giveMeFive(int hopefullyFive)
 {
     return (hopefullyFive == 5 ? "yay!" : "dude...");
 }

It doesn't have much purpose, but it's the kind of function you'd want to call when you're having a long day.

7

u/yorgle Dec 03 '15

This doesn't scale well for future maintenance. You should use a more world-accepted language for computer sciences, like Latin for the function names.

4

u/ekolis Dec 03 '15

But what if I want to add 6 to something? I don't want to write a porno!

5

u/[deleted] Dec 03 '15

But what is x? Colour me confused.

5

u/ekolis Dec 03 '15

Oops. Should be

int aVariableThatWeAreAboutToAddFiveToOrMaybeWeAlreadyDidDependingOnWhereYouSetYourDebuggingBreakpoint;

4

u/PerfectionismTech Dec 03 '15

Personally, I think self-documentation is too hard to achieve. Instead, I add a comment with a link to a shared 4-page Google doc explaining the line of code.

4

u/bitfxxker Dec 03 '15

Where is the error handling? Anyways, FTFY.

if(!giveMeAPointerToAnIntegerAndIllAssignANewValueToItItBeingTheVariableNotThePointerAlsoPleaseProvideTheNewValueYouWishToAssign(&x, giveMeAnIntegerAndIllAddFiveToIt(x))) { errorHandlerInCaseTheointerToAnIntegerAndIllAssignANewValueToItItBeingTheVariableNotThePointerAlsoPleaseProvideTheNewValueYouWishToAssignDoesNotExistAndAlsoItIsAFallbackToASolutionInTheCloud("error"); }

3

u/db__ Dec 03 '15

Not quite redundant, I mean self-documenting, enough; maybe prepend some Hungarian Notation.

3

u/shvelo Dec 03 '15

Brilliant! You're hired! We're expecting you at Signal HQ by 4 AM Yesterday

2

u/Neebat Dec 03 '15

You would do well in Java EE.

4

u/CrystalButcher Dec 03 '15

Needs more factories and a user context.

2

u/HVAvenger Dec 03 '15

I think you are really onto something. I would schedule an appointment with google. Or better yet, just barge into one of their board meetings. Don't want some middle manager stealing credit for your brilliance.

2

u/Illidan1943 Dec 03 '15

Seems fine

2

u/[deleted] Dec 03 '15

Are you trying to give him an erection?

2

u/fazzah Dec 03 '15

Coming back from MS-Dos and Linux, I'm still used to * meaning "select all". I'd replace the asterisk in your code into some less confusing symbol. Like ΰ

2

u/[deleted] Dec 03 '15

Ok, ok. I get it. you're making fun of my coding style.

I name my functions "ReadRegister", "AllocateDmaBuffer", and member variables "buffer_size", "device_handle". While my coworkers name their functions "RdRg", "AlDBf", and variables "bfSz", "d".

Can't there be a middle ground? Sure, i've committed the crime of nesting namespaces and enums instead of using straightup #defines, ending up with monstrosities like "Controller::Registers::DmaStatus::offset", instead of "CTRLREGDMAOFF", but we could live in peace without you changing all my source code whenever we work on the same project, can't we?

2

u/ekolis Dec 03 '15

I think your first function should be called giveMeAnIntegerAndIllMakeACopyOfItAndThenAddFiveToTheCopyAndThenReturnItAndByItIMeanTheCopyWhichHasHadFiveAddedToItAndNotTheOriginal, for clarity.

1

u/[deleted] Dec 03 '15

hmmm 5? I think you should use 11 instead.

0

u/[deleted] Dec 03 '15

[deleted]

6

u/amazing_rando Dec 03 '15

You might have to change it to a string or array based BigInt in the future. Or a decorated integer that counts how many times its modified, or logs every value. You never know! Now it's subclass-ready, truly OOP approved. Native types are for short-signed novices.

4

u/[deleted] Dec 03 '15

[removed] — view removed comment

3

u/memeticmachine Dec 04 '15

latest java 9 news: we've introduced pointers because we figured garbage collection is not good enough