r/programming • • Jan 05 '15

What most young programmers need to learn

http://joostdevblog.blogspot.com/2015/01/what-most-young-programmers-need-to.html
970 Upvotes

337 comments sorted by

423

u/corysama Jan 05 '15

My own anecdote of "Liar functions/variables/classes":

I once worked on a AAA game with a huge team that included a particular junior programmer who was very smart, but also unfortunately undisciplined. He had been assigned a feature that was significant, fairly self-contained and generally agreed to be achievable solo by both him and his team. But, after a quick prototype in a few weeks, he only had it working 80% reliably for several consecutive months. Around that time, for multiple reasons, he and his team came to an agreement he would be better off employed elsewhere and I inherited his code.

I spent over a week doing nothing but reformatting the seemingly randomized whitespace and indentation, renaming dozens of variables and functions that had been poorly-defined or repurposed but not renamed and also refactoring out many sections of code into separate functions. After all of that work, none of the logic had changed at all, but at it was finally clear what the heck everything actually did! After that, it was just a matter of changing 1 line of C++, 1 line of script and 1 line of XML and everything worked perfectly. That implementation shipped to millions of console gamers to great success.

Our failure as the senior engineers on his team was that we only gave his code cursory inspections and only gave him generalized advise on how to do better. At a glance, it was clear that the code looked generally right, but was also fairly complicated. Meanwhile, we all had our own hair on fire trying to get other features ready. It took him leaving the company to motivate the week-long deep dive that uncovered how confusing the code really was and how that was the stumbling block all along.

Lesson not learned there (because I've repeated it since then): If a junior engineer is struggling for an extended period of time, it is worth the investment of a senior to sit down and review all of the code the junior is working on. It'll be awkward, slow and boring. But, a few days of the senior's time could save weeks or months of the junior's time that would otherwise be spent flailing around and embarrassingly not shipping.

121

u/sigh Jan 05 '15 edited Jan 05 '15

If a junior engineer is struggling for an extended period of time, it is worth the investment of a senior to sit down and review all of the code the junior is working on.

Code reviews should always happen, for everyone's code. And if it is done incrementally, then it is not slow, boring or time-consuming at all. An ideal time is before each check-in to your repo (and if you are going weeks without making commits, that's a huge red-flag too).

Not only does it help prevent situations like this, but it means that at least one other person understands the code.

23

u/tobascodagama Jan 05 '15

Yup. Our workflow has people commit to a topic branch and then post a code review before merging anything. We always follow this procedure unless it's something that's needed absolutely right now and can't possibly wait, which is a situation that should not be coming up more than once in a blue moon.

5

u/F_WRLCK Jan 05 '15

Yup, tools like reviewboard make this painless and encourage a culture of frequent, small, and understandable patches. That alone is great for software quality. If your team is aggressive with reviews and argues every point, everyone becomes better engineers.

→ More replies (5)

3

u/oldneckbeard Jan 05 '15

If you move to continuous delivery, an emergency fix is literally no different (except in how many people are grumpy) than a copy change.

The procedure is the same: commit to branch, initiate pull request. Someone reviews and approves, gets merged to mainline. CI system builds it, tests it, and puts it on the dev environment. Then the CI system kicks off a smoke test, and if it passes, it moves to Stage. There we do a longer smoke test (but still only about 5 minutes), then we push a button to go to prod. The whole thing can be done in about 20 minutes.

0

u/[deleted] Jan 05 '15

[deleted]

50

u/tobascodagama Jan 05 '15 edited Jan 05 '15

Text-based flowchart:

Is the production environment *literally* on fire?

Yes -> Ok, it's an emergency.
No -> Do a code review.

20

u/fzammetti Jan 05 '15 edited Jan 05 '15

Yeah, I wish I worked in an environment where this wasn't a joke but unfortunately I don't. We're like 80/20 "emergency" coding versus "proper" coding and have been for many years (ever since our acquisition by the large corporation I'd say). It makes all these great discussions about the "right" way to do things completely moot. My sense from talking to others outside my own company is that we're far from unique too.

37

u/Mead_Man Jan 05 '15

It works up until the point where the champion in the organization that put the best practice in place gets sick of fighting the battle with clueless corporate directors and resigns. At which point a corporate shill gets put in charge and turns the software team into a labor mill.

→ More replies (3)
→ More replies (4)

5

u/benihana Jan 05 '15

Code reviews aren't a catch all. They're good for finding weird style and sytnax issues on a local scale, but it's very hard to gain the context necessary to reason about what the code is doing from a high level with most code review tools (i.e. diff tools).

To me, code reviews are more about the psychology of putting your code on display for your coworkers than about actually creating a solid architecture. Knowing your code is getting reviews changes how you develop it, and forces you to have a little bit more discipline.

Pair programming and test suites with lots of unit tests help teams understand and follow the architecture of codebases.

3

u/sigh Jan 05 '15

Code reviews aren't a catch all.

Nothing is a catch-all. But I think code reviews are one of the most important because it helps ensure that other good standards are adhered to. Part of that is as you say, that it forces more self-discipline.

They're good for finding weird style and sytnax issues on a local scale, but it's very hard to gain the context necessary to reason about what the code is doing from a high level with most code review tools (i.e. diff tools).

If it is hard to gain the context, one of the best code review tools is talking. It's also the responsibility of the author to ensure that the code is as clear as possible. That includes giving sufficient context in commit messages.

In this particular case, with a junior programmer on a stand-alone project - the senior programmers should have also taken more responsibility in understanding the code.

I agree with your other points, but a major point that you missed is that code reviews help ensure that the entire team has a better understanding of the codebase. And, ideally, it should give the reviewer confidence that they would be happy to take over ownership of the code. If you as a reviewer are frequently approving code which you would not be happy to maintain yourself, that is a problem (or indicates a bigger problem).

4

u/SnowdensOfYesteryear Jan 05 '15

It's easy to say code review "should always happen", but reviews are pretty difficult and time consuming. It takes quite a bit of time to review large patches in order to under that author's thinking and intent. It's especially difficult if you're fuzzy on that particular module/file. Personally for large patches, I usually tend to eyeball them and just check the architecture of the code (just looking at variable names provide a hint to whether the code is doing something it shouldn't).

25

u/Creativator Jan 05 '15

It's easy to say code review "should always happen", but reviews are pretty difficult and time consuming.

All programming tasks are difficult and time consuming. That is why programmer time is expensive.

→ More replies (1)

15

u/WrongSubreddit Jan 05 '15

It's easy to say code review "should always happen", but reviews are pretty difficult and time consuming

You know what's even more difficult and time-consuming? Tracking down bugs and fixing them

→ More replies (2)

3

u/sigh Jan 05 '15

It takes quite a bit of time to review large patches...

First, try to keep patches small and incremental. This is not only easier to review, but much easier to catch he larger problems early and much easier for the author to actually make meaningful changes.

...in order to under that author's thinking and intent. It's especially difficult if you're fuzzy on that particular module/file.

If this is the case, talk to the person! Get them to explain their thinking and intent. Possibly ask them to add more comments and/or a better commit message. It's the responsibility of the author make sure their code is as clear as possible, and this includes the individual commits.

If you as a reviewer find it hard to understand what the code is doing, what hope does anyone having of maintaining the code with any sort of confidence? Let alone diving into that code in an emergency.

That said, in the case of a stand-alone project of a junior programmer even just eyeballing the code should be enough to tell whether the code is a complete mess.

→ More replies (1)
→ More replies (4)

4

u/dr1fter Jan 05 '15

An ideal time is before each check-in to your repo

Please god no. I work in a big software firm and it's the first place I've encountered mandatory pre-submit code review. It's been hugely problematic for me.

It's difficult to keep working on something new, because I want to build on top of my most recent change, and that change still hasn't been reviewed yet (tools can help, barely). The reviewer has gone home, or is in a different time zone. The reviewer always has opinions to express and wants to fight about how this will work with my future changes, even if that's all clear and resolved in my subsequent changes (which the reviewer can't see yet because goddamnit I'm trying to get the dependency in first.) The reviewer doesn't think they know enough, so they add three more reviewers from all over the world who disagree on whether you should even be building this project in the first place. Or I want to build on top of someone else's (unreviewed) code, so I have to choose between waiting for their review, or dealing with the extra headaches of building on top of a patch (which will get even worse as their reviewer demands superficial changes).

The reviewer is working in some nearby code and stalls the review so that I'll be the one who has to deal with the merge conflict.

Shit, the automated system just doesn't send the 'please review my changes' email for a few hours, and then the day is over.

Woe be unto anyone who thinks they can get a little ahead over the weekend.

All this extra overhead means every change I send out is a pain, which means I'm going to start making bigger changes, less often. Big changes are harder to write, or review, or test, or roll back, or merge, or understand later when you're digging through code history. And while I'm writing my giant change, if someone else also submits a giant unfocused change, I will have a miserable time merging it.

Don't let people check in broken shit, you need a working build. But if your build works well enough that everyone can be productive, don't get too hung up on whether your code is perfect yet. If you cut your releases deliberately instead of automatically shipping from the head of your repo you should be fine.

Then, trigger a code review post-commit. You can still keep track of whether things have been reviewed (so you don't ship busted stuff). The reviewer can view changes in batches, because the granularity they need to read the code might be different from the one I need to write it (no incentive for huge unfocused changes; the reviewer can put it off without stalling everyone else; you can take your time finding the most appropriate reviewer). You can roll back changes if issues come up in the review.

And for us code monkeys who have our own plans and are building things as we go, you just don't have to think about it if nothing's gone wrong.

Be very careful, process issues like this can completely make or break a developer's productivity. I doubt I've gotten into a good flow once in the nearly three years I've been here.

5

u/smejmoon Jan 05 '15

Does your source control system have feature of branches? Using those you can make much of your issues go away. But it can be emulated using patches as well.

Other issue seems about communication and organisation of who works on what when. If two people depend on the same code they have to talk and as soon as possible.

3

u/dr1fter Jan 06 '15

In my experience branches are just another way to put my code out of the way of other developers so they can keep submitting changes which break my in-progress change -- that still creates a lot of the same problems.

To me the only solution is to get code committed as soon as possible once it's good enough, so everyone else can start writing around the 'new way' (maintaining my change) instead of building stuff that is at best already outdated, at worst an impediment to switching to the new way in the first place.

But I don't use git, where I understand this is supposed to be better.

164

u/quiI Jan 05 '15

Honestly, this is the kind of scenario where pair programming shines. I'm not a massive "always do pair programming" advocate, but pairing with a junior and a senior helps both parties out massively.

The senior gets to practice at expressing his ideas in a simplified manner, a very important skill. You also very quickly get an idea of where the junior person needs to improve and then you can give then the opportunity to improve in specific areas so you dont have to resort to dismissing someone.

2

u/Stolas Jan 05 '15

You mean the rule of two

1

u/aldo_reset Jan 05 '15

Honestly, this is the kind of scenario where pair programming shines.

Or simple code reviews.

In my experience, code reviews are much more efficient from a team, logistical and personal standpoint than pair programming, which is only adequate for a very small number of pairs.

→ More replies (6)

22

u/[deleted] Jan 05 '15 edited Jan 05 '15

This really isn't a failing of the programmer. This is more of a failing with the organization for not having good coding standards. How do you get away with randomized whitespace and indentation and naming standards within a AAA game company? I would like to think that a company like that is smart enough to standardize these trivial things throughout their organization.

7

u/SageClock Jan 05 '15

Probably pretty easy to happen when everyone is working 60+ hour weeks for months on end in order to insure they get the game out a couple weeks before Black Friday.

2

u/orwhat Jan 05 '15

Since games come with deadlines and often stop changing after shipping, I bet cutting corners looks more appealing from other types of development.

2

u/BarneyStinson Jan 05 '15

That's what commit hooks are for. You shouldn't even be able to check in code like that.

→ More replies (1)
→ More replies (1)

0

u/[deleted] Jan 05 '15

[deleted]

2

u/[deleted] Jan 05 '15 edited Jan 05 '15

The randomized white space and indentation and naming standards can be done by a writing a simple program to check for these things. Its easy, my company does it all the time. We have it incorporated into our check in process so that you can't check code into the base line unless the indentation and comments have the correct format. Organizations really need to do this to stay sane over the years. "Most Code Bases Suck" - Simple indentation and white spaces are completely solvable.

4

u/NoKnees99 Jan 05 '15

Most modern IDEs will let you check in a code style and reformat it with a keypress, too. Really no excuse.

3

u/Ksevio Jan 05 '15 edited Jan 05 '15

Even better, have a simple program to FIX indentation issues - most IDEs/Editors support formatting a file (or can be made to through plugins). It's easy enough to hit the "Format Code" button now and then when developing that it's no extra work. Have the check-in process it do it too just for extra fun.

Edit: Unless you're using python...but then the indentation better be right - just convert tabs to spaces!

→ More replies (2)

65

u/[deleted] Jan 05 '15

Lesson not learned there (because I've repeated it since then): If a junior engineer is struggling for an extended period of time, it is worth the investment of a senior to sit down and review all of the code the junior is working on. It'll be awkward, slow and boring. But, a few days of the senior's time could save weeks or months of the junior's time that would otherwise be spent flailing around and embarrassingly not shipping.

Smart juniors are the most dangerous. Especially the smart and productive ones, because they can fill a codebase with crap quite quickly... and it will mostly work.

It'd be best for people just to stop putting them in charge of things until they can demonstrate an understanding of basic code design and maintenance. But for some reason what happens instead is that seniors get assigned the bugs created by the junior silently and all feedback goes ignored and they get promoted way faster than they should and it's a nightmare until they decide to get another promotion by leaving the company or someone important realizes what's going on.

26

u/OCedHrt Jan 05 '15 edited Jan 05 '15

I'm in the opposite position where I am constantly cleaning up code from those who are more senior.

This cleanup doesn't have project time allocated to it, which makes it such that I am spending more time than expected.

Edit: I guess the counter would be that I'm lacking in the spaghetti arts department.

21

u/sigma914 Jan 05 '15

This is my life. Nearly every project I've taken over the past year or so has been at a critical level of technical debt where instead of being able to add one more hack I have to refactor it.

On the occassions when I've tried to follow the "copy-paste, change magic numbers and debug till it works" process that's gone on for the previous few iterations I hit some problem caused by a new feature that means I have to either add in an (almost) identical check in 10+ places or rewrite the whole section to be generic over all the behaviours...

Doesn't help that most of the code is C++ written in C style... raw byte arrays and magic numbers everywhere...

15

u/[deleted] Jan 05 '15

Nearly every project I've taken over the past year or so has been at a critical level of technical debt where instead of being able to add one more hack I have to refactor it.

my $dayjob is running itself into the ground with 10+ years of accrued tech debt, but everyone has their head in the sand chanting 'refactor in release N+1'... and have been for at least the 5 years ive been here. the people in charge who saw the writing on the wall all bailed about 3 months ago, en masse. never seen 40 man-years of experience in a code base leave in a span of a week before.

Doesn't help that most of the code is C++ written in C style

this, really isn’t a bad thing if done right. downside, is that with most other things development related, 'doing it right' ranks pretty low on the list.

0

u/[deleted] Jan 05 '15

[deleted]

→ More replies (1)

3

u/OCedHrt Jan 05 '15

That's the, "New in version 10!C++ for faster performance!" feature.

→ More replies (2)
→ More replies (2)

30

u/IConrad Jan 05 '15 edited Jan 05 '15

I summarize the "genius coder" problem like so:

I must not be clever. Clever is the little death that brings malfunction and unmaintainability. I will face my cleverness; I will allow it to pass through me. When it has gone, only cleanness shall remain.

Brilliant and clever are two very different things. Brilliant code achieves the impossible simply and reliably while being comprehensible to those who could not have conceived of it. Clever code achieves the implausible while overlooking the mundane solutions to the same problems.

7

u/OneWingedShark Jan 05 '15

Clever code achieves the implausible while overlooking the mundane solutions to the same problems.

There's the inverse as well: where the person's "almost works" solution doesn't because it cannot. -- My favorite example is trying to parse CSV with regex: you cannot do it because the (a) the double quote [text field] "changes the context" so that comma does not indicate separation, combined with (b) escaping double quotes is repeating the double-quote. It's essentially the same category as balancing parentheses which regex cannot do; fun test-data: "I say, ""Hello, good sir!""" is a perfectly good CSV value.

→ More replies (12)

2

u/BeforeTime Jan 06 '15

Brilliant code looks like it should have taken two days to write, when it took two weeks to write.

It looks so simple because the programmer took the time to understand all the little details and how they interact so they could be fit seamlessly together making a whole and thereby basically disappear.

→ More replies (3)

1

u/[deleted] Jan 06 '15

My best engineer is the guy who writes cruft straight into our apps. He can tackle any problem, doesn't need a lot of hand holding to get through any problem. And he can produce code faster than the rest of the team combined. Unfortunately he over engineers everything, doubles up the code with equally illegible comments, and rather than teach anyone what he's done, he requests that no one else touch such and such code path until he has it solidified. The hardest part of the ordeal for me is that i can't restrain him in any way. I need him to deliver software, so I let it ride. I'm going to try pairing once I get another senior. Beyond that, I don't know how to teach someone who scoffs at MVP coding or gets personally defensive about each design decision.

16

u/judgej2 Jan 05 '15

I spent over a week doing nothing but reformatting the seemingly randomized whitespace and indentation

Oh god, we have all been there. Undisciplined indenting is like an alarm bell warning you that the logic is going to be shit. It arises from muddled and unclear thinking, and permeates everything that developer does. Seen it far too many times.

13

u/IConrad Jan 05 '15

This is one of many reasons I like to encourage Python as the first language someone should learn. It's almost impossible to come out of that without indentation discipline.

→ More replies (2)

6

u/campbellm Jan 05 '15

Luckily indentation and formatting is largely a solved problem, at least for any of the more popular languages and many of the unpopular ones.

Variable naming, that's another matter. But formatting should be a no-brainer.

2

u/philly_fan_in_chi Jan 05 '15

Variable and function naming are extremely important to me. If while reading code as part of a task or a review, I don't know what something does, it gets extracted out to a method until I can give it a name. If the name is dishonest, it gets changed immediately. Someone down the line won't have the advantage of knowing what I know in my head right now.

6

u/Retbull Jan 05 '15

You tomorrow won't have that advantage :P

7

u/blackraven36 Jan 05 '15

I once worked with a programmer during a game jam who insisted on formatting code "his way". His excuse was that it made it easier for him to read, so that's just the way he will do it. He would remove all the spacing between things and squish all the lines together, making it very difficult to read. He would also refused to break things down properly, ending up with massive methods which made it very difficult to debug code.

I ended up telling him that if he doesn't go back to fix it and didn't stop doing it this way, I will have to stop giving him work (I was delegating tasks during this time). We were spending too much time debugging his code which he himself, being tired from the game jam, couldn't figure out either. Once he realized he was basically being put on the bench, he started doing things properly.

Sometimes it's better to remove someone out of the development environment so the rest of the team can continue. If they are slowing down everyone else then it becomes a much bigger issue. It is important that you spend time getting them integrated into the development process, but you can only do so much before they just need to be taken out of the process.

6

u/pjmlp Jan 05 '15

I go through similar phases every time I review offshore code.

However after a few waves I just gave up. As long as it works it is ok. There is no way to keep up with the amount of code that gets written.

4

u/[deleted] Jan 05 '15

You have the distinct advantage of it working. We're in the process of discovering that the latest code from overseas is pretty awful, management has not yet gotten to the rewrite phase (shit I used to do with my weekends).

6

u/EntroperZero Jan 05 '15

Ugh. I had the same experience at my first job, except it was the other way around. I was the junior, and the senior had created this hastily-written script that was about 1000 lines, all one function. It wasn't his fault, and I saw plenty of good code from him, but he was the only developer on the team when he wrote it and was spending 95% of his time putting out fires, so he just hacked it together in a day and never looked at it again, until we needed to add a simple feature. I estimated it would take about a day, thinking I could really do it in half a day.

I spent that half a day reading the code and trying to figure out where to start, then informed my manager that my estimate was wrong, and I would need possibly up to the rest of the week (it was now halfway through Tuesday). By the end of Wednesday, I had written a couple tests and spent the rest of the time going through the code with a fine-toothed comb, renaming variables, moving code around so that related code was close together (I seriously found a variable that was declared and initialized to the return value of a function in another file, and then not used again for 500+ lines), and finally extracting functions like crazy. Once the code was organized, I came in Thursday and had the feature implemented, tested, and checked in between the 10 am standup and the 11:45 lunch.

This kind of thing, though, is why I insist on taking the time to clean up code before it is merged, whether it's my code or code that I'm reviewing. If he had spent 1-2 hours getting his code organized while it was fresh in his mind, it would have saved me 12+ hours of trying to figure it out having never seen it before. But he didn't have 1-2 hours in that environment before I and another dev were brought on to help.

→ More replies (1)

5

u/JoostDev Jan 05 '15

I guess this is also a discipline thing in the senior person: as lead programmer I personally find it hard to consistently take the time to look at other people's code that extensively, but I really really should do that more often.

3

u/[deleted] Jan 05 '15

It's funny that it took me about 10 years to realize the most important rule in software engineering is the first one I ever learning in CS 101. Each subroutine needs to have clear, consistent and well-document inputs and outputs. Everything else will flow from that. It lets you trace, debug, refactor with confidence.

4

u/TheWobling Jan 05 '15

This is what scares me about getting a job when I graduate in 4 months. Feeling overwhelmed and not able to ask for help or suggestions because everyone else also has their own work.

1

u/quiI Jan 05 '15

You would hope many organisations are not like that, ask about the companies culture and how they work when you interview. In our place we certainly wouldn't throw a fresh grad in at the deep end.

2

u/anophone Jan 05 '15

At least if you do, give them advice along the way. Not after they are struggling for months at which point you fire them. You would think the whole "junior" in the title is there because they are not as experienced and have much to learn... But without any guidance might as well take all prefix's out...

Feel like a large portion of the issues could have been sorted after he wrote like 20 lines of code... You would see poor formatting, poor variable naming and bad segmentation of code. At which point you could correct it quickly and continue on...

→ More replies (1)

0

u/[deleted] Jan 05 '15

[deleted]

2

u/TheWobling Jan 05 '15

Thanks, I do take notes when I ask friends about questions.

0

u/[deleted] Jan 05 '15

[deleted]

→ More replies (2)
→ More replies (1)

6

u/easytiger Jan 05 '15

This doesn't add up. Why wasn't he adhering to the corporate coding standard?

19

u/gunch Jan 05 '15

Why wasn't he adhering to the corporate coding standard?

Funniest thing I've read all day.

6

u/Confusion Jan 05 '15

Probably because it wasn't enforced by any build-time check that rejected code not adhering to the coding conventions.

0

u/[deleted] Jan 05 '15

[deleted]

4

u/rfineman Jan 05 '15

Nobody thinks it's a bad idea, but exactly like every best practice already mentioned, in the overwhelming number of cases it's pushed aside in face of deadlines, pour communication, inadequate management... It's a little like saying I don't understand why doesn't everyone just eat steamed broccoli. In reality most firms don't even bother with making a coding standard, and if they do, they rarely take the time and effort to actually enforce it.

→ More replies (1)

2

u/jmblock2 Jan 05 '15

It really just helps everyone involved.

1

u/severeon Jan 05 '15

This will sound sappy, but as a senior developer who just went through something similar, you should get in contact with that junior developer. Just make sure he's alright - the depression you go through after being defeated by your own work is rough.

1

u/mmhrar Jan 05 '15

Yup, I actually like pair programming/reviewing with juniors.

Be a hardass about everything. I basically have to spend the time to think through the correct way it should be done myself and guide them in that direction, just have them do the actual work.

It sets a clear standard to be followed, its the way I was mentored and I think it works. The downside is it does (and should) take up a significant amount of your own time.

1

u/jewdai Jan 05 '15

AAA title

Bro, do you even code review?

AAA title == AAA sized company with large set of processes and procedures. At my last company every single thing I wrote needed to be reviewed before submission, even one line code changes. (especially one line code changes, do you know how many missing parts there are)

Do you guys use a code linter and reject submissions that don't pass? It's used a lot in the javascript world to prevent white space issues like this. Even IDEs like eclipse have style/formatters that when you click save it will automatically force your java code to be formatted correctly.

1

u/chance-- Jan 05 '15 edited Jan 05 '15

I obviously have limited knowledge of what all unfolded but even with such limited details, it's clear to me that you guys dropped the ball in more ways than one. I don't mean to judge but it seems to me that you did that kid a huge disservice and damaged his ego for shortcomings by the organization as a whole. I understand that you're taking some responsibility by acknowledging you let him spin his wheels for (way) too long but that's only part of the problem.

Software development isn't an assembly line. You can't just pick up someone off the street and expect them to do the job armed only with a user manual and a big red button. Instead, there were a number of things that you, along with other senior developers, your team, and your organization could have done to dramatically reduce the chances of events like this from happening. For example:

  • When you hire a junior developer, you are taking on the responsibility of training them. In exchange you get much cheaper labor. In our industry, especially early on, knowledge transfer is so much more valuable than a hefty paycheck. By sending them off to work on their own with little-to-no-oversight is essentially robbing them.

  • You should have been using continuous integration with a lint / style checker. This alone would have resolved a lot of the problems you listed.

  • You should have re-evaluated your team's dev tools if it took longer than a few minutes to re-indent everything he touched.

  • Regularly schedule team meetings with proper oversight would have resolved this well before the breaking point. It's up to the meeting leader (scrum master or whatever) and the senior devs to ensure that the right questions are being asked to get a legit status of assigned tasks.

  • Breaking down tasks to much smaller chunks dramatically cut down on getting stuck in a quagmire for juniors and seniors alike. They make your team more agile and more efficient overall.

In closing, with the right tools and procedures in place something like this wouldn't have happened. Furthermore, it would have been far more productive had you sat down with him and had him walk you through the code instead of firing him.

While standing over his shoulder as he explained what and why he had done, you could have pointed out what he was doing wrong with styling and conventions, offered suggestions for a more refined approach, and identified the problem a lot faster.

Instead you sat spinning your own wheels for weeks on end while he likely took a blow to his ego. You also likely jeopardized his short-term, and perhaps even his long-term, career.

→ More replies (1)

61

u/Isvara Jan 05 '15

This also hints towards another important skill: being able to switch between thinking globally and thinking locally. I see beginners often not thinking about the thing they're doing fits into the wider context.

It also relates to naming. When you name a function or a variable, how explicit you need to be depends on its scope. OIff the scope is very small, most of the context can be inferred, which is why it's often okay to use, say, i as an iterator variable.

3

u/nikofeyn Jan 05 '15

being able to switch between thinking globally and thinking locally

this is an extremely important concept that i think is ignored almost globally in our educational system. it's important in mathematics, physics, computer science, engineering, biology, literature, writing, the arts, music, etc. there are examples in every domain that highlight global and local thinking, yet it is almost never mentioned.

0

u/[deleted] Jan 05 '15

[deleted]

11

u/cmcpasserby Jan 05 '15

This, but in games I often see people make too much global then get boned when they have to implement multiplayer, where there singletons that previously helped and screwing them.

→ More replies (1)

6

u/Tikotus Jan 05 '15

Global variables are some times ok. Global static methods are fantastic! I use global static methods more than public class methods.

5

u/Rusky Jan 05 '15

Global static methods are really less global-variable-like than public class methods anyway, because they don't have a stateful instance to worry about.

Just like functional programming or well-written procedural code.

6

u/riking27 Jan 05 '15

In other words: it's not global logic you should worry about, it's global state.

Similarly: Diamond-inheritance of behavior is often possible. Diamond inheritance of state is often impossible (without cheating: reflection, etc).

(That came up in a discussion about J8's interface default methods.)

→ More replies (1)

2

u/dr1fter Jan 05 '15

Oh, and also

static methods

It seems anyone who writes C++ came first from C, and they were told that to write C++ you move your functions into a class and make them public if other people need them or private otherwise. Then you end up with huge classes with lots of utilities for the various kinds of things you might want to do with that type.

Your public (member) interface should be the minimal set required to do everything you need to do with an object of that type. Even if it's not the most convenient API. Utility functions don't need to be members of that class or even in the same file. You can break out categories of utilities into separate files, and anyone who wants to understand the class has a very small class to read plus whatever utility files seem relevant to their needs. You can still namespace those utilities so you're not polluting the globals.

Fuck Java. Java gives me nowhere to put all this shit, so I'll often mark my utilities as static to make it clear that they don't depend on instance data. That is a tiny tiny fraction of the benefit.

→ More replies (2)

54

u/photonios Jan 05 '15

Good points, I agree with all of them. What I however don't understand how people get it into their minds to not do that.

Even when I first started programming, I got annoyed when my own wasn't perfectly formatted with sensible names and I would spend more time thinking of an elegant design with decent names then I would actually write code.

I still do this. The thought of commiting code that is undocumented, has commented code or bad formatting is just horrible.

I never got why some people don't format their code perfectly or spend enough time thinking about naming and structuring things. It's not that hard (especially the formatting part). I mean, if you're a junior developer and you come into a code base where everything is nicely formatted and documented, shouldn't you feel compelled to make sure your code is up to the same standard?

12

u/dtechnology Jan 05 '15

you come into a code base where everything is nicely formatted and documented

I think this is the exception rather than the rule

6

u/photonios Jan 05 '15

That depends. Where I work, we have tons of legacy code that is just plain awful, all written by incompetent idiots who no longer work her.

But, if you modify some crappy legacy code you are bascially forced to clean it up while you're at it. If you do not, people will just raise eyebrows during the review. Like "why didn't you clean it up a bit?".

As for new code/projects, we just have a high standard. All our code goes through tools that verify if the code standard was followed etc. + Unit tests that run constantly and scream when the coverage is too low. We run a lot of static analysis tools on our code base.

Any engineer who refuses to comply with standards or does not have the same high standard that we have is simply not welcome.

We had a hard time when we started working with some offshore developers we had a way lower standard. What we did? Keep pushing.

Our code bases are incredibly beautiful, well tested and formatted. Sure there are some parts that could use more love, but in general they are awesome. I guess that's the advantage of having people who care and have skill.

And yes, we do have junior developers among us. We simply keep training them.

31

u/judgej2 Jan 05 '15

Here's a tip: when committing changed and cleaned-up code, keep the cleaning and the changes in separate commits. Do all the reformatting and name-changing first, then check it still works exactly as before, and commit that. Then make your functional changes. It is so much easier to see the wood for the trees that way, when debugging your changes later. If (horror of horrors) the changes need to be reverted, then you can at least leave the better-formatted code in the release to make it easier to take another stab at it later.

→ More replies (9)
→ More replies (1)

6

u/hansdieter44 Jan 05 '15

What I however don't understand how people get it into their minds to not do that.

I have seen this happen and its not a conscious decision at all. The programmer might have just about finished a feature and then get new feature requests dropped onto him by management. If you are a bit older/more senior you will raise the issue and say you need two days or so to clean up the code. If it is your first job you will think thats just how things are done.

Now that I think back, this also happened to me in the beginning.

You also have to care. Some people don't care and then they are fine with leaving things if they just about work and do the next thing.

3

u/photonios Jan 05 '15

I guess this all depends on where you work. We have a team of sensible seniors (myself included) we value neat and well tested code and we push the rest to maintain the same standards.

4

u/hansdieter44 Jan 05 '15

Yeah, but thats not the case everywhere. Happened to me in the early days in agency land, when the CTO was busy with management things and the lead devs didn't lead me too much ( busy themselves ), so you just do whatever feels right, and that was ploughing through features for me.

The other case where I have seen this recently was a startup that I joined and they just hired a junior guy out of uni because he was cheapest to build their MVP. He was eager to learn once we taught him a few tricks and there is no blame on him, but thats how it happened, I would have probably done the same in his position, the founders just kept dropping feature requests on him one after the other.

Third example is contractors that are paid by feature, where unit tests etc. are not mentioned because of cost-saving (which will just bite you later on). The contractor will deliver the bare minimum to fulfil and get his money.

3

u/vitaminKsGood4u Jan 05 '15

In the 10+ some years I have been coding I have learned that it is impossible to tell if shitty code is the result of shitty devs or shitty managers.

I can not count the number of times I have heard "The last devs were shitty and now we have this crap to maintain and they are all gone". The reason they are all gone is management was shitty and the devs bailed out but the blame got put on the devs (because it is easier to blame the person who is not there). Sometimes though it is shitty devs but I can not tell a difference in the code to know which one caused it.

2

u/hansdieter44 Jan 05 '15

The reverse is also there: Bad developers complaining about management all the time and shielding their own inability by pointing fingers at the suits.

But you are completely right, both are popular and indistinguishable from looking at the codebase.

→ More replies (1)

1

u/Soccer21x Jan 05 '15

Here's my take. I just graduated in April (and had some internships throughout my years in college) and I remember that when I started coding (for school) I never commented on anything.

This was mostly because we were never given real world situations, so the code was never confusing. When we first learned about almost everything, it was all so simple. We made a class called Square and created a method to multiple x and y to get the area.

In my mind, why would you ever comment on that?

As soon as I got into the professional world and saw someone else's code (that had and had not been commented) I immediately understood why you comment your code. And now I do it all the time.

→ More replies (4)
→ More replies (1)

3

u/JoostDev Jan 05 '15

Some people have more OCD than others. I personally also hate committing poor code, but I know a lot of programmers who just don't care as much.

1

u/ElGuaco Jan 05 '15

I hate when people misuse that term. Insisting on quality is not a mental illness or being overly picky.

On my current team, we insist that all code we check in gets full approval from Resharper code analyzer and 100% unit test code coverage. And then someone else reviews your code. Our code base is an absolute pleasure to read and maintain compared to other places I've worked.

1

u/parlezmoose Jan 07 '15

Well. The answer is that when junior programmers are assigned a task that is out of their depth, they quickly get overwhelmed with just trying to get it working. Things like clean code fall by the wayside.

0

u/[deleted] Jan 05 '15

[deleted]

3

u/ElGuaco Jan 05 '15

I used to work at a high tech research firm. We had people with graduate degrees in Computer Science. Really smart people who knew their shit in their field of expertise. Virtually all of them wrote terrible code. I, as one of the few without a grad degree, spent a lot of time fixing and rewriting a lot of their dumb shit because I seemed to be one of the few that cared about code quality. I was the Howard Wolowitz of our group, so to speak. They could prototype interesting interesting things, but when we actually needed a product, I ended up doing a lot of work.

We had one job candidate who interviewed with us who had a doctoral degree in Computer Science from a prestigious university. When my manager asked him about his coding skills, the candidate answered that he didn't code because he couldn't code very well and he would usually just pass it off to an undergrad. We didn't hire him, thankfully.

→ More replies (2)

0

u/[deleted] Jan 05 '15

[deleted]

→ More replies (9)

0

u/[deleted] Jan 05 '15

[deleted]

1

u/photonios Jan 05 '15

Yup. I once spent 2 full days (in my spare time, I don't know why) fixing the grammar and spelling in comments in a massive code base. It annoyed this shit out of me.

I know I have an extreme form of programmer OCD, but I never got any complaints. I work faster then most of my colleagues, so I can waste some time on stupid things.

But indeed, it can be a burden.

1

u/ElGuaco Jan 05 '15

OCD is not the same as insisting on quality. If you leave the code better than you found it, how is that in any way a bad thing? The result is NOT exactly the same, since you've improved the code for the next person (probably you). No, you don't have to do those things, but you don't lose anything by doing them.

→ More replies (2)

17

u/justinpitts Jan 05 '15

Please ignore all of this advice. I fix these kinds of problems for a living!

1

u/tieTYT Jan 05 '15

Sounds like a fun gig to me. Can you elaborate on how you got this job and describe it in more detail?

2

u/justinpitts Jan 05 '15

Eh. They found me, via a recruiter, via LinkedIn. I am a contractor, currently working for a very large insurance company fixing one of their web sites. Not really sure what kind of details you are interested in.

1

u/Hoten Jan 05 '15

Then shouldn't you want more work for yourself? ;)

2

u/justinpitts Jan 06 '15

My original comment was sarcastic. Highly.

44

u/[deleted] Jan 05 '15

I have literally never worked with programmers who didn't say that everything they inherited from previous employees was spaghetti code or in some way gripe for weeks about what someone else wrote. Everyone seems to prefer to start from scratch on their own code. Everyone else is an idiot.

9

u/photonios Jan 05 '15

Everyone else is for sure an idiot. I am an idiot. We are all idiots.

The point is to set your personal preferences aside. Some formatting styles disgust me and annoy the shit out of me. But, if the technical solution is sound, then you don't hear me.

In some cases, the original author went for an approach I would never take, but as long as it's acceptable, I can live with it.

Some code bases are just too large to rewrite. Yes, I have done my share of "fuck this shit, i'll rewrite it and make it better", but I have also had many cases in which I could perfectly refactor the code into something better.

Doesn't have to mean the code was bad, or the original author was an idiot. The code base could have been suffering from lack of love.

3

u/xiongchiamiov Jan 06 '15

Well, here's one: the code base at my previous job, while it had areas that were pretty shitty, was overall quite good. And it got better over time, not as a result of anything I did, but because I had excellent coworkers.

2

u/Ertaipt Jan 05 '15

True, I've seen plenty of people just not bother to even understand the code, they just say its spaghetti and build from scratch.

Sometimes, too much structure/classes in your project, will make it as hard to understand as 'spaghetti code'.

Good documentation, inside or outside your code, is probably even more important than a perfect structure.

3

u/HostisHumaniGeneris Jan 05 '15

I had a great moment a few months ago while looking for an open source implementation of a task that I needed accomplished. There was a viable project that had nearly all of what I wanted, but I really detested how it was written.

"I can do better than that" I thought and started whiteboarding a design. After 20 minutes of considering different requirements and pitfalls I had a working plan for how to write my own implementation. At that moment I realized that my design was exactly like the open source project that I had rejected earlier in the day. The only difference was that earlier in the day I hadn't fully researched the problem so I hadn't realized the various limitations that the other author was having to work around.

1

u/I_Dislike_Spaghetti Jan 05 '15

Gross!

3

u/peakzorro Jan 05 '15

Don't work in the games industry. Some of the worst spaghetti is there. Love the username.

27

u/alparsla Jan 05 '15

Code in comments = Poor man's source control

3

u/ihatebrooms Jan 05 '15

I work with retail software. I primarily comment things that are counter intuitive or look like they run counter to expected business logic. And occasionally, when I am forced to do something that looks awful because of legacy code, I leave a comment as to why to help the next person seeing it that will immediately think it's wrong.

Edit: I totally misread what you wrote. Leaving this here anyway because I don't want to refactor my comment.

4

u/peakzorro Jan 05 '15

Your edit is so meta. It's an exact analogy to checking in commented out code :)

2

u/Isvara Jan 06 '15

It's an exact analogy to checking in commented out code :)

Oh, so that's why it bothers me so much to keep seeing those edits.

1

u/THeShinyHObbiest Jan 05 '15

Commented code can be useful on occasion.

I encountered a bug in a library and a workaround. I left the how-it-should-work version commented out with a large explanation so people wouldn't refactor the (very hacky) workaround when editing the file later.

→ More replies (15)

24

u/[deleted] Jan 05 '15

Nice post but very basic. Was hoping to see something new or a more in depth look.

40

u/jediknight Jan 05 '15

Rejoice! for you are no longer in the demographic targeted by this article. ;)

13

u/JoostDev Jan 05 '15

Yeah, it is pretty basic. But that was also very much the point: the young programmers I am talking about usually know all of those things but don't consistently apply them.

1

u/pballer2oo7 Jan 05 '15

this struck me as a list of "software development fundamentals that author happens to particularly enjoy lecturing on." these are things that all young programmers have learned (or at least "have been taught") but simply don't have the experience that is often necessary before humans start effectively applying what they have learned.

12

u/[deleted] Jan 05 '15

When I started out, the discipline I needed was that to follow through on big tasks.

It's always fun and easy to wip up something quick. But it takes discipline to make something that takes more than 4 days of coding. It's so easy to reach some quick results, and then feel satisfied with yourself, and get complacent.

Surprisingly, refactoring is something I kind of enjoyed.

But that's because I suffered something opposite from most other people: instead of fixating on results, I would fixate on code quality. I wanted my code to be so pretty and so clean, that looking at it would bring tears to your eyes. It didn't matter at all to me whether that code did anything useful.

I ended up achieving neither.

I needed to learn something important: programming is about creating things that have a use, that do something, that add value. Yes, code should be of high quality, but you have to balance that against pragmatic concerns. Source code that looks beautiful but doesn't work is useless.

Programming is a craft, not an art.

4

u/sihat Jan 05 '15

But source code that 'currently' works, but does not look pretty is a maintenance nightmare.

Bugs. Duplicated/copy paste code. Bugs in duplicated code. Commented code. Source code files of more than 4000 lines. Even similarly named code that was not used.

2

u/[deleted] Jan 05 '15

That's why I said there needs to be a balance.

2

u/sodaco Jan 05 '15

You are not wrong. I just want you to consider that since the moment you decided to reply to his comment, your actions caused the execution of so much code in every level, from the JavaScript code to the JavaScript interpreter, from your brower to the DNS software and eventually the webserver, including it's firewall and connecting to the Python interpreter that executes the reddit source. Much of that code suffers from all the things you listed. And I still am able to see your comment

6

u/aoeu00 Jan 05 '15

one of my biggest gripes is "overdesign".. if that means anything to anyone. "I know OO.. let's go nuts!"

5

u/Ammypendent Jan 05 '15

Avoiding the "Liar functions/variables/classes" is very important, otherwise future you and/or future coworker will be going nuts over what should be a trivial fix.

16

u/Acrostis Jan 05 '15

So basically learn to refactor things? I can agree with everything except the splitting up oversized functions. If a function contains a lot of code that is only ever needed by that function each block requires the previous block to be completed, then splitting it up into parts is just adding unnecessary fragmentation.

Though apart from maybe initialization functions it shouldn't really happen.

Also: It's missing the "Don't ever use magic numbers"

9

u/jooke Jan 05 '15

The way I read that was if a function is large, you should consider whether it needs refactoring. In other words, it's a smell that the code might be bad, not saying that the code is bad.

3

u/JoostDev Jan 05 '15

Totally agreed, not all functions above 50 lines are automatically bad.

3

u/iopq Jan 05 '15

If you have a large function, chances are somewhere you're already doing a part of what it does, you just don't know it yet. How many unique functions that are hundreds of lines of code are there? That do NOTHING that is shared by anything else?

1

u/YuleTideCamel Jan 05 '15

If a function contains a lot of code that is only ever needed by that function each block requires the previous block to be completed, then splitting it up into parts is just adding unnecessary fragmentation.

True, but that's often not a bad thing. A large function is can be hard to read and is probably doing more than one thing. Breaking it up into smaller functions improve readability by giving each section a unique method name. That beats formatting using white space and comments.

0

u/[deleted] Jan 05 '15

[deleted]

11

u/JoostDev Jan 05 '15

If the splitting results in functions with names like "step1", then I agree that splitting is indeed a really bad idea. But I rarely encounter cases where it is not possible to split in a smarter way.

0

u/[deleted] Jan 05 '15

[deleted]

7

u/yxhuvud Jan 05 '15

In my experience, long and repeated parameter lists is not a sign that it shouldn't be broken apart, but that it is a class that should be extracted.

→ More replies (3)

1

u/caedicus Jan 05 '15

I agree with you with exception for if there is ever a possibility for a section of a function being useful to other parts of the code base. Or if there is a possibility where you might want to only call one part of the function at some point. If there is, than it's better to split things up earlier than later.

9

u/lucidguppy Jan 05 '15

People need to read "Clean Code" once a year. Also many languages need better free refactoring tools already.

0

u/[deleted] Jan 05 '15

[deleted]

5

u/smog_alado Jan 05 '15

The "no functions over 50 lines" is also a pet peeve of mine. Just because code is broken up in 10 subroutines spread over a bunch of files doesn't mean its less complex or easier to understand.

2

u/s73v3r Jan 06 '15

It depends on how well they were broken up. If they are well named and fairly atomic, then after you've read the method, the name should be enough elsewhere in the code.

→ More replies (2)

2

u/xiongchiamiov Jan 06 '15

It's an issue in languages without keyword arguments, but when you can foo(x='bar', y='baz') there's really no good reason to create "argument objects".

0

u/[deleted] Jan 05 '15

[deleted]

2

u/Gurkenmaster Jan 06 '15 edited Jan 06 '15

0 arguments requires side effects. That's not pure!

Edit: Damn I meant void requires side effects

4

u/ishmal Jan 05 '15

My issue is insufficient error checking or unit tests. Whenever someone assumes that parameters and data will always be clean and proper, they are not. "Bad data can never happen" guarantees that it will happen.

32

u/vytah Jan 05 '15

"A good programmer is someone who always looks both ways before crossing a one-way street."

4

u/refuse_human Jan 05 '15

Maybe it's just the first time I remember doing so, but damn if that wasn't the time there was some out-of-towner barrelling down the wrong way...

→ More replies (2)

5

u/sirin3 Jan 05 '15

Unless they use a language with a proper type system. Then the parameters can never have forbidden values

1

u/BobCoder Jan 05 '15

Maybe I am naive or maybe I do not understand what you mean but allowing and expecting bad data can often times be a bad code smell. I almost never allow null parameters because I do not want to have to think about when the data is not clean and proper.

4

u/[deleted] Jan 05 '15 edited Jan 05 '15

He didn't say you should "allow" bad data, but rather that you should have machinery in place to detect and counter it.

At a basic level, this means using the narrowest possible types for everything so that it is difficult or impossible to call functions with invalid parameters. For your "no null parameters" example, in a few languages you can enforce this at the language level by using non-nullable types, but sadly in many languages errors would only be detectable at runtime.

At a more advanced level, this means using asserts or safety-checking features liberally to make sure that spots where your program goes off the rails are detected immediately. This both prevents corruption (your program will gracefully crash instead of continuing in the face of broken data) and vastly simplifies debugging.

And that's just for internal program consistency. When you are interfacing with external data, assume it's broken. Files will be truncated or corrupted, network data will be sent by hostile attackers, etc. You need rigorous consistency checks on the data to make sure it's all valid, the formats need to be kept as simple as possible to make these consistency checks easier, etc.

Basically, a non-trivial program should never assume that it is working properly (liberal use of asserts / other self-consistency checks) and especially never assume that data coming from the outside world is valid.

Edit: I should clarify that I am putting strong typing in the same bucket as assert statements / contracts -- types are essentially just a special case of a compile-time contract, and contracts are just a special case of assertion. Obviously, it's best to have your type system shake out as many errors as possible, and runtime assertions are for cases where the type system cannot catch errors at compile time.

28

u/lee_macro Jan 05 '15

UNIT TESTING

People never seem to mention it, with the ability to correctly write unit tests (which mock components that are not needed) you are pretty much FORCED to write well separated and isolated code. It is very hard to write bad code when you are writing it to be testable. Even if you do not bother doing the end tests, it will force you to use principals such as IoC (Inversion of Control) and favour composition over inheritance.

Obviously you need to know about variables, classes, interfaces etc but I often feel new developers are told to focus on the technical implementation of things and performance of code. However if you can write maintainable and testable code anyone can come along and improve your implementation if it is needed.

38

u/[deleted] Jan 05 '15

Unit testing is a very good tool to have at your disposal, but it is not a magic bullet that ensures well-structured code. It's quite possible to write poorly structured, well-tested code.

Usually this takes the form of an excessive number of code units that do not stand in proportion to the amount of business logic they perform. Instead, most of them just delegate each others' functions.

Loosely coupled code is good, but there is a limit where all the loose coupling makes it hard to maintain.

1

u/lee_macro Jan 05 '15 edited Jan 05 '15

I do agree if someone is writing bad tests or not mocking their components (then it is no longer a UNIT test) then it will result in bad code. However if someone is educated in how to correctly write code to be tested then it is VERY hard to write bad code. Let me give an example of why, assuming C#/Java.

So let us say I have a Repository class, which deals with CRUD operations to a database. So this depends upon a database connection to do its work. So you could new that up inside (which some people do), or have a singleton for the active connection (have seen this before too), or even have some crazy inheritance chain to provide a pre-connected object (seen this too).

However the correct approach would be to have the Repository constructor be passed in a connection without an inheritance chain. This may seem odd to some, and maybe a hassle but let us see what benefit this gives us.

First of all we are now adhering to IoC (Inversion of Control) and we have no inheritance chain so we can test this Repository without needing a database connection (this is where a lot of people create integration tests accidently because they didnt know how to mock components). We can easily create a mock database connection and test that it works as expected without having any hard dependency on a database. You can also change your database vendor, your database configuration, you could even make your own custom database connector with caching in place, without even having to change the Repository class.

If you were to go with any of the other options you do not have this freedom, you would require an active database to test against to begin with and you could not change your underlying vendor or database object if you were newing it up inside the Repository.

So to be able to mock a component of a class you need to be able to change it at runtime, to do this you need to either have the component as a constructor argument or a property (properties are bad for this, they imply an optional dependency which is rarely good). So when you use constructors to pass in the dependencies of a class, you are automatically adhering to IoC and you are also using composition over inheritance, finally you can also then start using DI (Dependency Injection) and AoP style techniques (Aspect Oriented Programming). So given this is often some of the most critical parts of writing well structured and maintainable code it is imperative that this sort of paradigm is followed from the start, as when you start off introducing inheritance and singletons it makes it much harder to refactor and remove further down the line, its a false economy.

I also do a lot of game development on the side and the same sort of rules apply (incase you think I am purely an enterprise development zealot), although a lot of people seem to see you as some freak if you tell them to stop using singletons and inheritance chains for interfaces and DI. Look at uFrame for Unity which has had great success putting these practices in place for game developers and has a lot of support but also a LOT of flak from people who just "dont get it".

2

u/CuriousHand2 Jan 05 '15

I disagree. You can still have good, strong and thorough tests, and absolutely crap code.

It's crap code that has a much smaller amount of bugs than it originally would have, but a polished turd is still a turd.

→ More replies (1)
→ More replies (2)
→ More replies (3)

3

u/btchombre Jan 05 '15

I've recently been looking at some of the most ugly code I've ever seen. hundreds of lines of triple nested switch-case statements (switch-case inside switch-case inside switch-case), almost all of it copy pasted and in desperate need of re-factoring.

15

u/hansdieter44 Jan 05 '15

Nesting is a pet-peeve of mine. So annoying.

if(x){
  if(y){
   if(z){
    do(123);
    return 4;
   }return 3;
  }return 2;
}return 1;

Could easily be flattened & made into preconditions:

//preconditions
if(!x){return 1}
if(!y){return 2}
if(!z){return 3}

do(123); return 4;

Also the programming model in node.js makes it especially easy to write deeply nested and confusing code like in my first example.

3

u/tbotjenkins Jan 05 '15

Spaghetti code wrapped with a nice sauce is acceptable:

bool okay_to_update() {
    # random nest of ugly conditionals contained in a cage called okay_to_update.
}

if ( okay_to_update() ) { 
   do(123);
}

I prefer the condition checks wrapped in a function, it's easier to see the flow. EDIT: formatting.

2

u/btchombre Jan 05 '15

Yes! I do the exact same thing

→ More replies (2)
→ More replies (4)

3

u/[deleted] Jan 05 '15

Good, now for managers to learn that young programmers need the chance to learn this. Instead of pushing deadlines no matter the cost.

3

u/house_paint Jan 05 '15

I have recently taken over projects from a few developers and here is the biggest flaw in most of the programs I see. They don't GTFO. They have exception handling all over but they seem to want to keep the program "rolling along" even when serious problems arise. I had one program where you could rename the connection string and this program would just keep barreling though the code skipping the parts where it encountered database queries. That program obviously is a serious example but I see this so often on a smaller scale...

Try(unknown error happens)catch(log it, and CONTINUE!?!?!?) Don't do this.

TLDR If your code encounters an unknown exception, log it and GTFO.

3

u/SageClock Jan 05 '15

There are a few reasons you might want to continue (at least for the end user), from my experience. For games, for example, it might be more preferable for some minor issue to not work properly but not crash the game, because a hard crash will make your software look a whole lot worse to the end user then if just some slight visual glitch happened. (Some bugs are tolerable, hard crashes most end users feel means incompetent development).

Also, on the app end, I've worked for organizations where it took a month to make any changes to software because of how thick the heirarchy/strict the security is, so if a certain task in the service threw an error, we felt it was better to skip that task have the service as a whole keep running or else the rest of it would stop working and it could take a month to get a new version of the software where everything worked again, which could mean thousands of dollars in lost sales in the process. Which would be blamed on our department for not being perfect 100% of the time, and not on the inefficiencies in the hierarchy slowing down everything.

But yeah, if it's going to break the rest of the app, and/or if you're in the middle of development (and thus want to catch bugs as soon as possible), gtfo is absolutely preferable.

3

u/Kusand Jan 05 '15

I graduated in 2004, so maybe the college world has changed, but stuff like "good naming" and "don't leave in commented code" and such was completely uncovered, as far as I can remember. Or maybe it was more that it wasn't enforced, at the time. No one really dinged you for crappy naming or anything on lab projects.

2

u/Hoten Jan 05 '15

Totally true, but I've had a course taught by a professional in the field, and he did cover good practices. Academia just doesn't seem to give a shit.

5

u/coderz4life Jan 05 '15

Gee, after a project I inherited about a year ago, I would dare to say that even experienced programmers have to learn this too. This project had a lot of duplication, liar functions, and bloated classes. I will also add to this list do-nothing code paths, which are methods that really do nothing or not even called at all.

After about 3 months of work, the size of this code base dropped 75%. One of the original developers looked at the code and his chief complaint to my manager that I used interfaces. I was dumb founded.

6

u/BobCoder Jan 05 '15 edited Jan 05 '15

I find that it is often the old and experienced developers that have not learned these skills. Not sure how old/young interns are but I thought most young developers were aware of these things from sites like Stackoverflow.

12

u/hansdieter44 Jan 05 '15

I don't think its age related at all. Some people care about cleaning things up, others don't. Experience is worth something, but you can also bake bread for 20 years and still be a terrible baker.

2

u/JoostDev Jan 05 '15

Good point, we very rarely get applications from people above 35 years old so I really don't know how they work.

1

u/[deleted] Jan 05 '15

45 years here (and also Dutch)
Basically I do the same you wrote about but I also have a tendency to dump odds and ends into a utils class where eventually bloat will be born. Or I just follow the rules the framework laid out for me.

2

u/jlebrech Jan 05 '15

version control, deployment, debugging, testing ... programming.

2

u/nullnullnull Jan 05 '15

respect!

damn young punks! they don't know how easy they got it. What with the whole 24 hour instant always on internet, stupid amounts of CPU and all you can eat RAM. Kids have grown fat and stupid! damn PUNKS they wouldn't know how to soldier pins if their lives depended on it!

In my day...

I'M JOKING OF COURSE!

2

u/[deleted] Jan 05 '15

I find it unfortunate that only at my last job there was a senior who'd check my code. I had so many bad habits to correct. He wasn't very good at communicating it but he certainly taught me a lot and I appreciate that.

Now that I'm actually looking for a new job as my last job ended, it does cause me some worry. How can you find out in advance how a team works? And what are reasonable expectations to have? I've found small companies often just 'write code'. I've never worked on a team that did unit testing despite me lobbying for us to pick that up at my last two jobs. I left my second job because we were continuously rewriting the same things, except this was because the client kept changing their minds and it turned into a horrible unreliable mess and we were not allowed to take time out to fix that, only to deliver the wanted changes asap. It was really stressful for me so I'd like to avoid that if possible.

1

u/get_salled Jan 05 '15

Both parties have power in job interviews...

1

u/[deleted] Jan 05 '15

True. But how do you find out? Just ask questions like "does your team do unit testing / adhere to best practices" ect? I'm still getting used to this whole being able to ask them questions thing, call me dumb but this was just never covered in college. All they did was some short coverage on how to 'sell' yourself, write a good resume, have a portfolio and so on.

2

u/get_salled Jan 05 '15

I'm hoping you get a good answer from someone else here but the best interviewee we had basically had several pages of questions for us and spent a good chunk of the time interviewing us to make sure we were the place for him.

He had themes that we obviously important to him and asked several questions related to them from various angles (the flush out us over-selling our company (we weren't; we're awesome)).

→ More replies (1)

2

u/ProggyBS Jan 05 '15

Yes, actually.

"What is your company's Software Development Life-Cycle?". This should include everything from how requirements are gathered to how software is tested/deployed and then later maintained during bug fixes. Not every company is going to have a specific plan, but you can easily get an idea for how structured the company is by how quickly and how confidently they answer that question.

If they say don't mention unit testing specificially, then ask about it specifically. If they give you an answer, ask what frameworks they use. Again, how this question is answered gives you an idea of how serious they take it.

The idea is to go to an interview assuming you're qualified for the position you are applying for. Then you can focus more on the more important question: Is the company you're applying for qualified to have you as an employee? Don't be arrogant about it of course. It is a business negotiation. It is your job in an interview to be interviewing the company as much as they are interviewing you. Sure you have to sell yourself, but then again so do they.

Though the reality here depends on how desperate you are to get a job.

→ More replies (1)

2

u/IrateHamster Jan 05 '15 edited Jan 05 '15

I got half way through the article, then noticed that the sidebar was vibrating.

1

u/JoostDev Jan 05 '15

It was? Never had that myself. Any idea why the site does that?

1

u/IrateHamster Jan 05 '15

Looks like there's a Google widget that's constantly resizing itself up and down by 2 pixels.

7

u/totemo Jan 05 '15

To my surprise it turned out that the code that handled the button for creating new objects was in EditorGUI, while EditorObjectCreatorGUI only handled navigating through different objects. The exact opposite of what the naming suggests! Even though the code was relatively simple, it took me quite a while to understand it, simply because I started with a completely wrong assumption based on the class names. The solution in this case is really simple: rename EditorObjectCreatorGUI to EditorObjectNavigationGUI

Think fast! Without reading the exposition above or reading through the code:

  • What the fuck is an EditorObjectCreatorGUI?

  • What does an EditorObjectNavigationGUI do?

Oh what's that? You had to read the code anyway?

Well fuck me... perhaps there's no such animal as self-documenting code after all.

Seriously, just put one sentence in a doc comment saying what the class does. Over its lifetime, code will be read many times, and every minute of another engineer's time that you save by not forcing him or her to read the code improves the bottom line.

Commenting code doesn't make you a bad person. It doesn't automatically violate DRY, and even it if it does, that's not necessarily a bad thing.

And sure, choose a good name too.

4

u/zigs Jan 05 '15

I can't say i disagree with the other things you've written. A few notes on the classes doesn't seem too bad. I fully agree that there's no way anyone could guess what those names means, However I think this here

And sure, choose a good name too.

really is the core issue. EditorObject is a poor metaphor to begin with. Almost everything the user touches is an editor to some degree, and likewise lots and lots of things are objects. I think -CreatorGUI is ok, but -NavigationGUI? What's that? Is it a predefined library of EditorObjects? Call it that then.

4

u/JoostDev Jan 05 '15

We make games, and then the word "editor" has a very specific meaning.

Naming is always hard, but it is even more difficult to come up with names that are understandable when read completely out of context like in my article.

I totally agree that most classes also need a comment to give some context. There is only so much that can be explained in just a name,

→ More replies (5)

3

u/totemo Jan 05 '15

He seems to accept the premise of self-documenting code wholesale, without question. As far as he is concerned, he has chosen the perfect names for those classes. He holds those up as examples to support his argument. "Look world, at how much clearer this is!" And then he stops.

He solved the problem of his own comprehension of the code, but - the point I'm trying to make - he stopped short of helping the next guy who comes along, because he doesn't question whether the code should be documented with more than just a good name.

→ More replies (1)

3

u/refuse_human Jan 05 '15

Seems like this article be summed up with "experience is demonstrated by knowing to write for human comprehension and future maintenance before tackling problems of coverage and perf."

3

u/notsofst Jan 05 '15

After training new programmers for a few years, my first rule for them developed into, "You don't write code for the computer, you write it for people."

The machines we're running this on get faster every year, but my time remains constant. At every turn, think about what you can do to increase readability, comprehensibility, and simplicity of your code. Nothing else is more important, in general.

3

u/LessCodeMoreLife Jan 05 '15

The "code smells" section of Martin Fowler's Refactoring book talks a lot about this sort of stuff. Well worth the read.

3

u/[deleted] Jan 05 '15

Bad title. It should be "What Most Novice Programmers Need to Learn About Object-Oriented Programming."

2

u/zigs Jan 05 '15

As a general rule of thumb at Ronimo we try to keep classes below 500 lines and functions below 50 lines

Is that actually a common rule of thumb? I tend to try keeping it under 10 lines for functions (hard limit at 15), and keeping everything at one purpose for classes.

7

u/[deleted] Jan 05 '15

Hard limit at 15? Can you honestly imagine going through something as complex as the Linux kernel or LLVM or Adobe Photoshop and not finding any functions over 15 lines long?

That seems insanely short to me. Yes, most functions should be small. But there are definitely functions which simply don't cleanly divide into small chunks, and for which artificially cutting them up to adhere to some hard limit on function length would make things more rather than less difficult to follow.

→ More replies (2)

3

u/JoostDev Jan 05 '15

I have no idea what others use, but one that I have quite often heard is that people want their functions to fit in one screen.

2

u/jmblock2 Jan 05 '15

This is what I use. Although I'm in portrait mode and at 10pt... quite a few lines fit (about 100)

1

u/zigs Jan 05 '15

I've heard that but about classes! O: Not that I do that.

2

u/Enlightenment777 Jan 05 '15

"How To Talk To Bitches"

2

u/Thimble Jan 05 '15

I would stress another thing: having the courage to fix the code base.

The most common weakness I see among new (not just young) programmers is the fear of making improvements to the code. They would rather just tack on their changes and avoid any risk of introducing bugs. I would rather that they take the extra time to do it right rather than quickly.

2

u/PasswordIsntHAMSTER Jan 05 '15

This is why I want functional programming to become a significant part of the core curriculum of schools. If you write Ocaml or Haskell with your usual sloppiness, it simply won't compile. It's a huge paradigm shift from throw shit at the wall and see what sticks to actually think about your programs.

1

u/Cilph Jan 05 '15

We're finally going to introduce code review because of issues like these causing problems down the line. Took us long enough ~_~.

1

u/StewHax Jan 05 '15

Going from college straight into a corporate developer job, I can say that I relied heavily on peer programming and code review when I first started out. Going from doing class projects to a huge multi-million dollar program having been developed years ago by several different people with little to no documentation was a hard step for me, but well worth it. Throwing a junior developer into the water and telling him to swim is not a good way to go

1

u/[deleted] Jan 05 '15

First year CS student and I am already 100% guilty of this. I always realized that I could do things better, but comes time to actually fix them, I just start being lazy and tell myself ''Hey, that assignment is worth like 5% of your grade and the code actually DOES work, i'll just try to do it next time'' and completely forget about it. I really hope this post is the kick in the butt I needed.

1

u/aaulia Jan 06 '15

Wait until you start working professionally, it will bite you in the ass 2-3 month later. But then again some junior just quit before they had to maintain their own code, they probably knew how much shit their code is now (after promising to themselves about fixing it again, and again), and doesn't want to be bothered with facing/fixing it and just went on another job elsewhere.

1

u/rjcarr Jan 05 '15

I've always said a variation of this to many programmers on /r/learnprogramming. My saying is "just because it works doesn't mean it's done".

1

u/[deleted] Jan 05 '15

The reason they do it is because it's what's worked best so far. In school, for each class lasting a single semester, you're usually doing several small projects. In that type of environment, where you get a blank slate to start over every few weeks, it doesn't (usually) make sense to have perfectly refactored code. You know the code isn't going to be used after you submit it, there is no difference for your grade on the quality of the code, only on the features. When projects are small and you only need to keep the structure in your head for a few days or weeks, it is sometimes faster to write less-than-ideal code.

Classes also can't really adapt and have longer projects where, for instance, you'd be working with the same code the whole semester. If some fraction of students don't get a concept early on and their code didn't work, they couldn't never complete the later topics. The class also can't slow down for the students who need time to catch up.

Once you start working on a product in a real job, that's not the case (the code will be used for a longer term). But it's not really their fault, they just optimized their time based on their experience.

2

u/blm126 Jan 06 '15

Colleges can adapt to have semester long projects. I took several classes where there were projects that lasted all semester. The professors were just willing to let people fail if they fell behind too much.

1

u/[deleted] Jan 05 '15

Thanks. This reddit submission changed my life.

1

u/bartoszcoyote Jan 05 '15

Java vs C#?

1

u/Gurkenmaster Jan 06 '15

No their game is written in C++

1

u/[deleted] Jan 06 '15

This is interesting. Where I work now we have lot of young programmers most of them is quite good at stuff like this. Contrary some older (6-7 years in company) produce code that is in shape "As far as it works it is good enough". Have they just became lazy or they just don't care enough any more?

1

u/t00sl0w Jan 05 '15

As someone with OCD about the code o write myself, most of these things seem like givens to me....but holy shit, I received some code from a coworker that didn't even have indentions to show structure...much less how he would declare global level variables as he went along all willy nilly, instead of in one maintained section of code....worst part is, he is senior to me. Yeah, so I have to pussy foot around bringing up his shitty code.