راهنمای نوشتن کدهای تمیزتر در برنامه نویسی

مارتین فولر ( متخصص طراحی و آنالیز برنامه‌نویسی شیءگرا ) جمله ای داره به این شرح که فکر کنم همین یه جمله حق مطلب رو به خوبی در این زمینه ادا میکنه!

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.Martin Fowler

برای شما

نوشتن کدهای تمیز یکی از سخت‌ترین کارای برنامه نویسیه که قطعا باعث میشه وقت بیشتری هم صرف کد زدن کنیم، ولی یه برنامه نویس خوب برنامه نویسیه که به این کار عادت کرده باشه و اگه از اون مهمتر توی پروژه های تیمی داره کار میکنه به سبب احترام به همکارهایی که باید کدها رو بعدا بررسی کنن و همچنین وجدان کاری از یک سری اصول و قواعد برای بهتر نوشتن کدهاش پیروی کنه و در آخر یک کد و پروژه تمیز تحویل کارفرما بده تا آینده هزینه ی کمتری صرف تحلیل و بررسی کدها بشه.

کد تمیز چیست و چرا بهش نیاز داریم؟

رابرت مارتین مهندس نرم افزار آمریکایی در جایی از کتاب “Clean Code” دیاگرامی برای سنجش کدهای خوب (تصویر پایین) منتشر کرده با این توضیح که معتبرترین پارامتر در سنجش یک کد خوب تعداد “این دیگه چه کوفتی” – WTF هایی هستش که موقع بررسی کدها میگیم!

نمونه های بی شماری از کدهای بد که شرکت ها را تا آستانه ورشکستگی پایین آورده و یا باعث یک فاجعه شده وجود داره. برخی نمونه های معروف و (به نسبت جدی) شامل موشک های فضایی هستند که به دلیل یک فرمول ضعیف رونویسی شده مورد استفاده قرار گرفته ( و تنها به دلیل وجود نداشتن یک خط کد، موشک باید 293 ثانیه پس از راه اندازی سقوط کند و در نهایت حدود 20 میلیون دلار هزینه به شرکت وارد شود). اشکال در دستگاههای پزشکی که باعث مرگ افراد می شود، و نمونه مرگ 3 نفر هنگامی که آنها در معرض دوزهای تابشی کشنده قرار گرفتند و این دست اتفاقها نتیجه کدهای کثیف می باشد…

کیفیت کد به طور مستقیم با قابلیت نگهداری محصول ارتباط دارد. بهره وری برنامه نویسی با زمان هماهنگی دارد
کیفیت کد به طور مستقیم با قابلیت نگهداری محصول ارتباط دارد. بهره وری برنامه نویسی با زمان هماهنگی دارد

توصیه هایی برای نوشتن کدهای تمیزتر و خواناتر

1. Variable and method name

1.1. Use intention-revealing name

This is bad:

protected $d; // elapsed time in days

This is good:

protected $elapsedTimeInDays;
protected $daysSinceCreation;
protected $daysSinceModification;
protected $fileAgeInDays;

1.2. Use pronounceable name

This is bad:

public $genymdhms;
public $modymdhms;

This is good:

public $generationTimestamp;
public $modificationTimestamp;

1.3. Use namespaces instead of prefixing names

Most modern programming languages (including PHP and Python) support namespaces.

This is bad:

class Part {

private $m_dsc;

}

This is good:

class Part {

private $description;

}

1.4. Don’t be cute

This is bad:

$program->whack();

This is good:

$program->kill();

1.5. Use one word per concept

Be consistent. For example, don’t use get and fetch to do the same thing in different classes

1.6. Use solution domain names

People reading your code will be other programmers so they understand solution domain terminology, so make the most of it. – For example, jobQueue is better than jobs

1.7. Use verbs for function names and nouns for classes and attributes

class Product {

private $price;

public function increasePrice($dollarsToAddToPrice)

{

$this->price += $dollarsToAddToPrice;

}

}

2. Better Functions

2.1. The smaller the better

2.2. A function should only do one thing

2.3. No nested control structure

2.4. Less arguments are better

More than three arguments are evil. For example:

Circle makeCircle(Point center, double radius);

Is better than

Circle makeCircle(double x, double y, double radius);

2.5. No side effects

Functions must only do what the name suggests and nothing else.

2.6. Avoid output arguments

If returning something is not enough then your function is probably doing more than one thing.

For example

email.addSignature();

Is better than

addSignature(email);

2.7. Error Handling is one thing

Throwing exceptions is better than returning different codes dependent on errors.

Asking for forgiveness is easier than requesting permission. Use try/catch instead of conditions if possible

2.8. Don’t repeat yourself

Functions must be atomic

3. Comments

3.1. Don’t comment bad code, rewrite it

3.2. If code is readable you don’t need comments

This is bad:

// Check to see if the employee is eligible for full benefits

if ($employee->flags && self::HOURLY_FLAG && $employee->age > 65)

This is good:

if ($employee->isEligibleForFullBenefits())

3.3. Explain your intention in comments

For example:

// if we sort the array here the logic becomes simpler in calculatePayment() method

3.4. Warn of consequences in comments

For example:

// this script will take a very long time to run

3.5. Emphasis important points in comments

For example:

// the trim function is very important, in most cases the username has a trailing space

3.6. Always have your PHPDoc comments

Most IDEs do this automatically, just select the shortcut.

Having doc comments are especially important in PHP because methods don’t have argument and return types. Having doc comments lets us specify argument and return types for functions.

If your function name is clear, you don’t need a description of what the method is doing in the doc comment.

For example:

/**
* Return a customer based on id
* @param int $id
* @return Customer
*/
Public function getCustomerById($id)

3.7. Any comments other than the above should be avoided

3.8. Noise comments are bad

For example:

/** The day of the month. */
private $dayOfMonth;

3.9. Never leave code commented

Perhaps this is the most important point in this whole article. With modern source control software such as Git you can always investigate and revert back to historical code. It is ok to comment code when debugging or programming, but you should never ever check in commented code.

4. Other code smells and heuristics

There are a lot more that you can do to identify and avoid bad code. Below is a list of some code smells and anti-patterns to avoid. Refer to the sources of this blog for more information.

  • Dead code
  • Speculative Generality – no need “what if?”
  • Large classes
  • God object
  • Multiple languages in one file
  • Framework core modifications
  • Overuse of static (especially when coding in Joomla!)
  • Magic numbers – replace with const or var
  • Long if conditions – replace with function
  • Call super’s overwritten methods
  • Circular dependency
  • Circular references
  • Sequential coupling
  • Hard-coding
  • Too much inheritance – composition is better than inheritance

این مقاله خلاصه و ترجمه ای بود از مقاله:

https://www.butterfly.com.au/blog/website-development/clean-high-quality-code-a-guide-on-how-to-become-a-better-programmer

لینکهای مفید:

https://www.red-gate.com/simple-talk/blogs/what-is-maintainable-code/

https://www.codeschool.com/blog/2015/09/29/10-ways-to-write-cleaner-code/

https://www.thecodingdelight.com/write-clean-code/

تعریف مهندسی نرم افزار

نویسنده مطلب: Mohsen

منبع مطلب

به فکر سرمایه‌گذاری هستی؟

با هر سطحی از دانش در سریع‌ترین زمان با آموزش گام به گام، سرمایه گذاری را تجربه کن. همین الان میتونی با لینک زیر ثبت نام کنی و ۱۰ درصد تخفیف در کارمزد معاملاتی داشته باشی

ثبت نام و دریافت جایزه
ممکن است شما بپسندید
نظر شما درباره این مطلب

آدرس ایمیل شما منتشر نخواهد شد.