r/shittyprogramming • u/[deleted] • 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?
193
u/Gera- Dec 02 '15
Hmm. x? That's a little vague. Maybe call it variableWellBeAddingANumberToOnceWeHaveTheNumberEnteredByTheUser
21
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'llBeAddingANumberToOnceWeHaveTheNumberEnteredByTheUserPlease 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
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
39
u/amazing_rando Dec 03 '15
Macros are the key to clarity.
#define now_equals_five_more_than_its_original_value += 5
21
6
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
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
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
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
Dec 03 '15
I feel like the ampersand is confusing. I recommend:
#define pointerToInteger &15
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
giveMeAnIntegerAndIllAddFiveToItwould be perfect for that, but its name is already taken. MaybegiveMeAnIntegerAndIWillAddFiveToIt?
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
5
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
2
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
2
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
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
0
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
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
4
u/madhousechild Dec 03 '15
I like how you said "please" but can you also work in "thank you" and "you're welcome"?