What are "code units"?

Asked

Viewed 329 times

12

I want to know what units of code mean?

I saw that term in a reply here at Sopt and I was in doubt.

Code units shall be short and have only one responsibility.

Link to the question I saw the term >> What defines a clean code?

  • I edited it. I want to know what is "code units", which was commented on in the other post;

  • I believe the subject falls here too: What are modules in programming?

  • 1

    I think it would be interesting if you put a comment on the answer itself that is there with the link to here.

3 answers

14


The word unity derives from the Latin term Unites and designates the quality of what is unique or indivisible. Has as meaning what is considered individually and not plural.

The physical limits of a unit of code are abstract concepts and vary according to the context. It can be a line of code, it can be a group of code, a function, a class or an entire project. There is no way to define exactly where a unit of code starts and ends. But what was said in the quoted answer is that each unit of code must have one, and only one, responsibility. Unity is said, in the concept of indivisible, as I mentioned above, because the implemented logic, regardless of the number of lines of code, performs only a very well defined task.

By way of example it is possible to consider a class implementation. You can have methods get/set properties as well as validation methods of values. It would be possible to implement validation logic within the method set, however, if within any other method you need to validate the value again, you will need to replicate the validation logic or use the method set. Not always the second option is indicated, because it can leave the code little semantic (to understand: you need to validate a value, but use its respective setter). The ideal is to have the method only for validation and, within the method set, invoke it to validate the value. Division of responsibilities for different code units (in this case, the methods).

10

There it was purposely left vacant.

Probably the smallest unit of code is the function, but I have doubts without any exceptions, who knows a lambda which is practically a function.

It is also a structure, a class, a module, a source file. Each with its level of influence and with what should be its responsibility. In general one goes inside the other.

function -> class -> module or source file

10

Code units are the ways instructions can be grouped. This helps in the organization and distribution/integration of a project. Some examples are functions, 'modules', classes.

The term indicates the granularity of a 'code chunk', as well as (we classify) the units measures: km, m, cm and mm. The software has the respectively.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.