Jump to content
Nytro

Yes, your code does need comments.

Recommended Posts

Posted

[h=1]Yes, your code does need comments.[/h]

I imagine that this post is going to draw the ire of some. It seems like every time I mention this on Twitter or anywhere else there is always some pushback from people who think that putting comments in your code is a waste of time.

I think your code needs comments, but so we have a mutual understanding, lets qualify that.

def somefunction(a, :
#add a to b
c = a + b
#return the result of a + b
return c

I understand this is a contrived example but this is the comment trap that new developers get caught in. These types of comments really aren't useful to anyone. Peppering the code that you just wrote with excessive comments, especially when it is abundantly clear what the code is doing, is the least useful type of comment you can write.

"Code is far better describing what code does than English, so just write clear code"

This is usually the blowback you get from comments like the ones above. I don't disagree, programming languages are definitely more precise than English. What I don't agree with is the idea that if the code is clear and understandable that comments are unneeded or don't have a place in modern software development.

So knowing this, what kind of comments am I advocating for? I'm advocating for comments as documentation. Comments that explain what a complex piece of code does, and most importantly what an entire function or Class does and why they exist in the first place.

So what is a good example of the kind of documentation I am talking about? I think Zed Shaw's Lamson is a fantastic example of this. Here is a code excerpt from that:

class Relay(object):
"""
Used to talk to your "relay server" or smart host, this is probably the most
important class in the handlers next to the lamson.routing.Router.
It supports a few simple operations for sending mail, replying, and can
log the protocol it uses to stderr if you set debug=1 on __init__.
"""
def __init__(self, host='127.0.0.1', port=25, username=None, password=None,
ssl=False, starttls=False, debug=0):
"""
The hostname and port we're connecting to, and the debug level (default to 0).
Optional username and password for smtp authentication.
If ssl is True smtplib.SMTP_SSL will be used.
If starttls is True (and ssl False), smtp connection will be put in TLS mode.
It does the hard work of delivering messages to the relay host.
"""
self.hostname = host
self.port = port
self.debug = debug
self.username = username
self.password = password
self.ssl = ssl
self.starttls = starttls

...

This code snippet is from https://github.com/zedshaw/lamson/blob/master/lamson/server.py. You can poke around the lamson code and see some good looking Python code but also some usefully documented code.

[h=2]So hold on. Why are we writing comments?[/h] Why are we writing comments, if you write clean, understandable code? Why do we need to explain what classes and functions do if the code is "clear" and easy to understand.

In my opinion, we write comments to capture intent. Comments are the only way to capture the intent of the code at the time of writing.

Looking at a block of code only allows you to understand the intent of that particular code at that moment in time which may be very different then the intent of the code at time of its original writing.

[h=2]Writing comments captures intent.[/h] Writing comments captures the original meaning of the code. Python has docstrings for this, other languages have comparable options. What is so good about docstring type comments? In conjunction with unambiguous class and function names they can easily describe the original intent of your code.

Why is capturing the original intent of your code important?

  • It allows a developer, at a glance, to look at a piece of code and know why it exists.
  • It reduces situations where a piece of codes original intent isn't clear then gets modified and leads to unintended regressions.
  • It reduces the amount of context a developer must hold his/her mind to solve any particular problem that may be contained in a piece of code.

Writing comments to capture intent is like writing tests to prove that your software does what is expected.

[h=2]Where do we go from here?[/h] The first step is to realize that the documentation/comments accompanying a piece of code can be just important as the code itself and need to be maintained as such. Just like code can become stale if you don't keep it updated so do comments. If you update some code you must update the accompanying comments/documentation or they become useless and can lead to more developer error then not having comments at all. So we have to treat comments and documentation as first class citizens.

Next we have to agree on what is important to comment on in your code, and how to structure your code to make your use of comments most effective. Most of this relies on your own judgement but we can cover most issues with some steadfast rules.

  1. Never name your classes and functions ambiguously.
  2. Always use inline comments on code blocks that are complicated or may appear unclear.
  3. Always use descriptive variable names.
  4. Always write comments describing the intent or reason why a piece of code exists.
  5. Always keep comments up to date when editing commented code.

As you can see from the points above code as documentation and comments as documentation are not mutually exclusive. Both are necessary to create readable code that is easily maintained by you and future maintainers.

Sursa: Yes, your code does need comments. - Mike Grouchy

Posted

hai sa fim seriosi ...,daca esti in romania si esti developer de websiteuri nu ai timp nici bani sa scrii documentatie la codul tau ...""

eu unu personal am inceput sa scriu documentatie odata ce am iesit din romania .... !!!!

Posted

Daca nu scrieti cod ca robotii o sa vedeti ca aveti timp si de documentatie. Eu nu pot sa sufar programatorii care merg pe conceptul "code first, think later". Recunosc, cateodata poate sa fie mai rapid. Dar de cele mai multe ori ajungi in situatia de a implementa un lucru de 10 ori: code, code, code, compile, test, recode, recode, recode, compile, test etc...

Dar daca incepi cu un mic design, iti aranjezi putin structura(descri functii, proprietati etc), scri documentatie care sa evidentieze functionalitatea si apoi te apuci de implementarea propriuzisa o sa ai surpriza ca in final sa ai ceea ce se numeste "beautifull code".

Si inca ceva: puteti ca ma tarziu sa ajungeti intr-o companie in care dati peste un besmetic ca mine care are tot dreptul sa va dea revert la codul la care ati muncit o zi intreaga intr-o secunda, doar pentru faptul ca nu e documentat sau ca nu se intelege. >:)

Posted

Ar trebui sa existe peste tot, sau fiecare sa isi impuna daca lucreaza singur, ceea ce se cheama "coding style", care include si comentariile. De exemplu orice functie sa aiba deasupra comentariu care sa explice ce face si ce reprezinta fiecare parametru, pe scurt. Da, poate ziceti ca nu e nevoie pentru functii simple, dar cand dati de o functie cu 15 parametri trebuie sa stiti ce face fiecare ca sa nu pierdeti 2 ore sa intelegeti functia.

Iar comentariile in primul rand va ajuta pe voi, cand recititi codul, cel putin pe mine ma ajuta mult si chiar as zice ca scriu cam multe comentarii, insa nu cred ca strica.

Exemplu:

///////////////////////////////////////////////////////////////////////////
/// @brief Functia asta face ceva smecher
/// @retval Si returneaza numarul magic
/// @param [in] nNumar Un numar oarecare
/// @param [out] pcoutBuffer Un buffer de dimensiune X
///////////////////////////////////////////////////////////////////////////
int Functie(int p_nNumar, char *p_pcoutBuffer)
{
...
}

Cam acesta e stilul doxygen care poate genera documentatie HTML superba. :)

Posted

In productie, un cod necomentat este un cod slab si nici nu o sa treaca de validari.

Poate ca acum lucrati pe proiectul X dar poate peste cateva luni/ani firma se decide ca vrea sa aduca modificari softului scris de voi.

Daca acel cod nu e documentat se va pierde o cantitate enorma de timp pentru ca dezvoltatorii sa isi dea seama ce ati facut voi acolo. Nici macar voi care l-ati scris nu o sa mai stiti ce ati facut acolo.

La proiecte mici (personale) si proiecte de scoala poate nu sunt asa necesare comentariile dar intr-un cod de productie este absolut obligatoriu sa ai comentarii.

In mod normal codul trebuie sa fie asa de bine scris incat sa se citeasca ca si o poveste dar nu toata lumea are inspiratia de a da nume variabilelor si claselor cat mai clare. Asa ca la nivel de companie se introduce nevoia aceasta de a scrie documentatii si comentarii pentru a se putea face o mentenanta asupra codului.

Posted

La facultate asta ne bag? pe gât: commenturii, specifica?ii, documenta?ie, func?ii de test.

?i m? cam enerveaz? a?a un pic, probabil din cauz? c? trebuie s? facem asta ?i la buc??i de cod banale, care nu-s mare filosofie.

La fiecare laborator predat, trebuie s? facem documenta?ie pe foaie. În cod, avem de scris pentru fiecare func?ie specifica?iile, adic? descriere, parametri de intrare/ie?ire, precondi?ie, postcondi?ie. Cam a?a:

    def update(self,id,st):
"""
Update student in the repository
id - string, the id of the student to be updated
st - Student, the updated student
raise ValueError if there is no student with the given id
"""
#remove the old student (this will raise exception if there is no student
self.remove(id)
#store the student
self.store(st)

Acu` facem C ?i avem o problem? ce trebuie rezolvat? în 3 s?pt?mâni. Urm?toarele teme o s? se rezolve tot pe codul care-l scriem acum. Umbl? zvonul c? proful vrea ca dup? astea 3 s?pt?mâni, temele urm?toare s? le rezolv?m pe codul altui coleg, nu pe codul scris de noi la prima tem?. Ideea e foarte bun? ?i util?, dar preferam s? fii f?cut asta când am f?cut Python, c? C-ul mi-e cam peste îndemân?. :D

Posted

Comentarea fiecarei functii dintr-un cod e oarecum o necesitate. Niciodata nu stii cine va lucra pe acel cod dupa tine. Sau, poate chiar tu peste mai mult timp.

E obositor sa incerci sa faci modificari asupra unui cod in care trebuie mai intai sa intelegi ce face fiecare functie. E vorba de timp pierdut si nervi macinati.

Obisnuiam (si inca obisnuiesc) sa comentez orice linii de cod pe care ma gandesc ca nu le-as intelege la prima citire dupa mai mult timp. Niciodata nu stiu cand o sa-mi foloseasca.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...