7 rules of simple and maintainable code
TRANSCRIPT
7 GOLDEN RULES OFSCRUMT CODE
Simple, Clean, Readable, Understanable, Maintainable(Testable) Code
Slides by , presentedby Sumit Chhetri.
Geshan Manandhar
WHY WRITE CLEAN CODE
Code for humans not machinesThink that the next person who reads your code is a chainsaw
maniac
If you don't write clean code, you know your fate.
Rule 1: Follow a consistent codingstandard
If you are doing PHP follow Other languages like Java, Python, Javascript also havecoding standardsUse a linter or CS fixer to follow the standard. Integratebuild tools in Sublime or use default PHPStrom coderefactor, to automate thisMakes it easy for everyone - including yourself - in theteam, to read the code
PSR-2
Rule 2: Name things properly, longvariable and function/method names
are allowedStick to one convention. ($someVariable or$SomeVariable or $some_variable)Don't use abbreviations, may not be understandableto the person, who reads your codeNaming is difficult, do it well. Name classes, variablesand methods that make senseDo not be redundant.Example
Rule 3: Be expressive, write code as youspeak and be optimally verbose
Focus on API rather than patterns.First, write down the API for perfect scenario, observehow it feels, then jump to coding and make it work.Tell, don't ask.Example
Rule 4: Max indent per method shouldbe 2, in case of exceptions 3
Avoid the use of else.Extract the logic to other readable method.Return earlyThrow exceptionExample
6 levels of indentation (in our public code) source
public function settingsAction() { //0 if ($_POST) { //1 try { //2 ... } else { ... //3 if ($reportingOrgNew != $reportingOrgOld) { //4 if ($save == "ok") { ... //5 if ($activityPublish) { //6
Rule 5: Avoid creating andlong methods
god object
One class should do one thing not everything likeStatusChanger or StatusManager not StatusGodAvoid using and in method names likevalidateAndSave, one method needs to do onething and one thing wellKeep methods small, a 50 line method is a problemKeep classes small, a 1000 line class is a painKeep the instance variables to as low as 6 or 7.
Rule 6: Keep the method in one place,inject the class and call it, DRY
In MVC keep controllers slim, business logic belongs toservices or repositories, check for controller 5-10-20If you access property of a property a->b->c->d() thereis something wrong, you can use a wrapper or proxyfunction.Use language constructs like interfaces, traits to makecode more expressive and reusableIf you find yourself copying the same code severaltimes, extract that code into its own method.Refactor your code, every once in a while.
symfony best practice
Example
Rule 7: Avoid in-line comments(comment with code), put comments in
the method docComment is a code smell (anti pattern), like If you need to write comments to explain your code,means you need to put it in a new method.
here
Example
public function addActivity($data , $default){ $this->defaults = $default; $identity = Zend_Auth::getInstance()->getIdentity(); //var_dump($data);exit; $model = $this->model; $modelActivity = new Model_Activity();
$activitiesId = $model->getIdByField('iati_activities', 'account_id', $identity->account_id);
//Create activity and its defaults $iatiIdentifier['activity_identifier'] = $data['identifier'];
Other considerationsAvoid working with just arrays for large data sets, useclass and type hintRather than starting to write something on your ownspend 5 minutes to read the framework/librarydocumentation to know if its already providedExtract out methods and rename variables asnecessaryRead about cyclomatic complexity and N-Pathcomplexity, here
Recap 1Rule 1: Follow a consistent coding standardRule 2: Name things properly, long variable andfunction names are allowedRule 3: Be expressive, write code as you speak and beoptimally verboseRule 4: Max indent per method should be 2, in case ofexceptions 3
Recap 2Rule 5: Avoid creating and long methodsRule 6: Keep the method in one place, inject the classand call it, Rule 7: Avoid in-line comments (comment with code),put comments in the method docDont forget the consideration and reading
god object
DRY
PS: you can print the recap slides and mug them up.
ReferencesMost code examples are taken from YIPL open sourcecode on Github.Rules for simpler code - laracastMaintainable CodeReadable CodeObject CalisthenicsYour code sucks - let fix it
ThanksHope we can step by step minimize code complexity and
write SCRUMT code.
Remember, simple, understandable, readable and eventuallymaintainable code is greater than any pattern ever invented
(be practical).