Cutting Clean Code

Status
Not open for further replies.

kappisto

Seniorius Lurkius
10
I'm a messy programmer. I'm also, as you might imagine, a fairly inexperienced one. I'm currently building an sql database app in php/jquery, and whilst I can generally get the results I need the problem I run into is that I don't know best-practice conventions to separate all my functionality into clean, neat files/structures. In my ambivalence end up coding necessary functionality in-place, which makes for messy, hard to follow (and non-recyclable!) code. Not cool, I'm sure you'll agree.

Keeping in mind that these kinds of questions don't necessarily have a "correct" answer, does anyone mind sharing how they break up & structure their code? What works for you? Is there anything else that irks you in terms of neatness that you see in other programmers, bad habits you wish you could've broken when they were neophytes?

Cheers,

Dave
 
Do you have the opportunity to get out of PHP? If so, I recommend moving to just about anything else; popular web frameworks that won't make you want to kill yourself like PHP does include Ruby on Rails, Play (on Java or Scala) or Django. You'll find that a lot of the ugly boilerplate you've got to write in vanilla PHP will be dramatically reduced in those frameworks, since they're designed for well segmented, intelligent web sites. The startup time is a bit slower (unlike PHP you've got some command line work you'll have to do, which can be daunting the first time but becomes much simpler down the line). If you don't have a choice WRT PHP, I'd recommend one of the MVC frameworks. I will ardently suggest you steer clear of CakePHP (the documentation is often out of of date and their design is a poor Rails imitation). Zend Framework is huge and bloated but otherwise not terribly designed. I've heard good things about Symfony and Yii but have never used them.

Regarding Javascript: There are two approaches. The first is that you're just using a little bit of JQuery for the occasional show/hide functionality and maybe a couple animations or something. If that's the case, then just have a central JQuery file that gets included on every page, and put page specific logic on a page specific JS file that gets included only on the one page it's needed for. That's a simple design but it scales fairly well and won't make you hate your life.

The other option is to go with full on Javascript MV*. This is a much more complex solution, but it's the future. Backbone.js (http://backbonejs.org/) is kind of the internet darling, but I think we're going to see more people moving to something like EmberJS (http://emberjs.com/) in the near future. I'm hoping to be able to put together a sample app with Ember in the next week or two to see how I like it. Seems like it has a lot of promise.
 

chocoruacal

Ars Tribunus Militum
2,173
Let's get this out of the way first: PHP isn't the problem, and switching to a different language won't make you a better programmer. Despite that, expect to get plenty of PHP haters in your thread. There is a healthy population of them here.

Your problem is that - as many new developers do - you're probably trying to "roll your own" on everything; most new developers I work with think that is the only way to learn. Stop. Point your browser to Codeigniter (or Cake, or Doo, or Yii, or whatever). Build something using one of these established frameworks. It'll take you a little bit longer to in the beginning (as you learn the language AND the framework), but you'll be better off in the long run. There's no such thing as the "perfect" framework, but that's okay. The point is to learn A convention, not THE convention. After you gain more experience, work with a few different frameworks, you'll eventually settle on patterns that you're comfortable working with. Then if you want to spend time reinventing the wheel, at least it won't come out square ;)
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
chocoruacal":321p22fe said:
Let's get this out of the way first: PHP isn't the problem, and switching to a different language won't make you a better programmer.
Being unable to sanely reason about your code is not a way to cultivate good programming practices; PHP actively does its best to fuck with you and keep you from adequately reasoning about it. Also unhelpful is knowing only one, bad, language (and I am guessing at this, perhaps incorrectly, based on the likelihood that he doesn't actually know JavaScript because he referred to jQuery instead of JavaScript).

Horizons. Broaden them. Away from particularly shitty languages.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
switching to a different language won't make you a better programmer

This is demonstrably false.

If I switched you (or I) to coding in assembly we would become 'worse programmers'. Our code would have more bugs, would take longer to write, work on fewer target platforms, be less comprehensible. I would argue that anything even remotely imperative without lexical scoping is significantly failing to allow a developer to use it powerfully as it introduces needless complexity (by coupling code which should be independent to each other)

There is definitely not be a *total* ordering on the power of different programming languages (taken in isolation, ignoring the available libraries/frameworks), possibly not even when considered in conjunction with the problem domain at hand (which certainly changes which is better quite radically sometimes as niche languages can excel in these areas whilst not being in general very usable) but there's a spectrum and you you put things roughly on it.

I say this as someone who's never had to write PHP (but cannot understand how in hell anyone thought not lexical scoping was a good thing except for the person writing the original interpreter), but it applies across the board (including languages I consider my 'go to' ones).
 
chocoruacal":1iukib3m said:
Let's get this out of the way first: PHP isn't the problem, and switching to a different language won't make you a better programmer.

When there's a 10,000 (ok, 9,737 -- I just counted) word blog post about the problems with a programming language that no one disagrees with, at least part of your problem is your programming language. I'm not saying you can't learn to program in PHP. You certainly can -- I did. But having come from PHP to working daily in Rails, there's absolutely no comparison between the two. Rails is fun. It's a job, but it's something I actively enjoy doing on a daily basis, and want to do more of when I finish my work for the day. PHP never felt like that. Java, Scala, C#, Python even my brief encounter with Clojure: They all felt like that sometimes. I was excited by what I was doing, I was enthralled with the language I was using because I felt like it was working to make what I personally wanted to do easier. PHP never felt like that.

And again, I strongly discourage people from using Cake. It's ugly and painful (in different ways from Zend, which is the other framework I've used, and is also ugly and painful).
 

btmlltt

Ars Legatus Legionis
15,156
Either we want this forum to be useful to folks working with PHP or we don't. It's become a pretty standard thing that when someone asks a question about PHP, instead of thoughtful feedback on their topic they get a bunch of arrogant d-bags telling them to not use PHP. Very helpful.

To the OP:
One thing my team has been focusing strongly on of late (and this is with code written in AS3, PHP, and Javascript) is focusing on keeping every method as simple as is reasonably possible. Have it do one thing that can be clearly unit tested. Extrapolating from there, each class should have one responsibility that, again, can be unit tested. You end up with many methods/classes but we've found it is of a tremendous amount of help as the codebase grows. 'Mega Methods' (especially ones with a zillion parameters) and 'Mega Classes' can be a huge pain in the ass to work with if there is a rare bug after much of the code has already been written.

For PHP, imo, you'll want to break up your back-end code from your display architecture. This will make driving your UI with Javascript/jQuery easier. With a lot modern asynchronous web apps, the backend is really just a localized API that the UI makes continuous calls to to get/process data.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Either we want this forum to be useful to folks working with PHP or we don't. It's become a pretty standard thing that when someone asks a question about PHP, instead of thoughtful feedback on their topic they get a bunch of arrogant d-bags telling them to not use PHP. Very helpful.

Instructions to use a framework are also not helpful in the content of code organisation!

The issue with using PHP for an example of how to organise code is that there are certain things it doesn't do (like lexical scope) that pretty much require you structure you code differently than you would in almost any other language code, since the OP appeared to be asking a more general question than just how to do it for PHP it's worth mentioning that.

Plus what most people (not the first repay I admit) were replying to was the post from chocoruacal, and your ++. Things g OT quite quickly here when people write silly stuff (even if they didn't intend it to be read that way)

The most important thing is "do the organisation used make sense to other[1] people reading the code".

Useful heuristics to achieve this are:

* If two pieces of code are closely coupled (in the sense that one is very dependent on the behaviour of the other) then they should be close together (normally in the same file if they are very rightly coupled).
* Expose only what you need (this very much depends on how visibility is implemented in your language of choice though) default to private unless absolutely necessary.

PHP is lacking so many of the tools used to do this (namespaces, lexical scope, and you can't _really_ do immutable fields nicely as the API exposure doesn't indicate 'no you can't set this' you're forced to ignore or throw)

Doubtless there are some conventions that help with this, hopefully people will pipe up with specifics.

1. this includes your future self.
 

btmlltt

Ars Legatus Legionis
15,156
ShuggyCoUk":g3nbj7zn said:
* Expose only what you need (this very much depends on how visibility is implemented in your language of choice though) default to private unless absolutely necessary.
This is a really good one. I was going through some code written by a recently fired co-worker and every damn method was public so it took me a ton of tracing the code paths to figure out what was being used somewhere else and was only being used within the class, etc. Might seem trivial, but just the mere private-ing of the shit that wasn't used elsewhere can be a huge help to other developers who are going to have to use your code.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
The issue with using PHP for an example of how to organise code is that there are certain things it doesn't do (like lexical scope) that pretty much require you structure you code differently than you would in almost any other language code, since the OP appeared to be asking a more general question than just how to do it for PHP it's worth mentioning that.
Scope differences are barely worth mentioning at this point - it's still an imperative, object-oriented, procedural programming language at the end of the day. MegaFunction() should still be broken into, say, ReadSomething(), TransformSaidThing(), and OutputNewThing(). That you might need to use 'global' or pass a hojillion parameters to each function or add 72 extra fields to your class or even just resigning yourself to the lack of immutable public fields is beside the point at hand, "How do you refactor existing functions into small units that make sense, or properly design programs to have appropriately-sized units to begin with?" (my translation, of course)

I don't have much to add on that subject, btmlltt and you both covered it well, except to say do whatever you're going to do sooner rather than later. As in, the moment you realize that ReallySmallFunction() actually needs to do two things, don't just add the functionality, back up and create ReallySmallFunctionOne() and ReallySmallFunctionTwo() (and revisit your design to see why you missed that during planning). I used to catch myself doing this often in "temporary" programs of the quick and dirty sort that tended to morph into critical business processes, causing more pain later. So I started enforcing the same methodology on my temp programs as my "official" programs and it prevents me from having to refactor later.

I will go ahead and agree with Blacken that it's not the best language to use to hone best practices, but I disagree that it's a show-stopper to all personal growth. If you're going to be stuck with it, it's not like you have a choice anyway.
Might seem trivial, but just the mere private-ing of the shit that wasn't used elsewhere can be a huge help to other developers who are going to have to use your code.
++ Been dealing with that a lot lately, thanks much, programmer[last_guy]!
 
D

Deleted member 43669

Guest
Avoid repeating code.

Have a function (or method) for each business logic operation (i.e., for this forum, stuff like "add post", "add comment to post", "list forum threads", "view user info", etc.), which takes correctly typed arguments (i.e. date objects, not strings that contain dates) and returns similarly well-typed information.

If a single web action can be decomposed into several business logic steps in a way that makes sense, do so.

Once you have that, write the HTTP-handling stuff (i.e. parsing of GET/POST parameters), which calls the business logic methods written above and use the output to generate HTML.

If your code follows that and it does not repeat itself a lot, you are 60% there, really.

And I'm on the "run away from PHP" camp, it will make all this easier.
 
btmlltt":1zrxu665 said:
Either we want this forum to be useful to folks working with PHP or we don't. It's become a pretty standard thing that when someone asks a question about PHP, instead of thoughtful feedback on their topic they get a bunch of arrogant d-bags telling them to not use PHP. Very helpful.

It's not arrogance, it's just the truth. As someone that's used PHP for about 7 years, I can firmly say it's bad -- starting with primitives all the way up. When you cannot even trust the equal operator, it's a language that cannot be defended.

http://me.veekun.com/blog/2012/04/09/ph ... ad-design/

Someone would only be a d-bag by not warning them.

----

OP: Your code should not look like code. It should look like an outline.

good rules of thumb:

- if a single line comment is more readable than a block of code, it should be in a function (even if its just a nested function)

- if the flow of the code doesn't fit on one page, it's should be refactored (see the rule above)

Unfortunately, PHP is BAD. Nested functions in PHP exist globally after execution and a second call to the parent will error out because it tries to redeclare the nested functions. Even if this wasn't the case, scope in PHP is terrible and makes encapsulation way more confusing than it should be.

Source files should be very small and very single purpose. It's the only real way to keep a piece of PHP code from becoming brittle. Once it becomes large, it becomes very difficult to track down issues -- even "simple" syntax issues.

Encapsulation in PHP is next to impossible, unless you're running v5 or above. The only mechanism is the class, but if you forget a "this->" prefix, your code will still look right but it will do funny, funny things. It's still better than nothing, so use it if you can.
 
Status
Not open for further replies.