http://www.basef.com.br/index.php?title=Especial:P%C3%A1ginas_novas&feed=atom&hideredirs=1&limit=50&offset=&namespace=0&username=&tagfilter=Basef - Páginas novas [pt-br]2024-03-29T09:55:41ZDe BasefMediaWiki 1.26alphahttp://www.basef.com.br/index.php/Functions_Should_Do_One_ThingFunctions Should Do One Thing2020-01-27T14:36:44Z<p>Admin: Criou página com 'FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY Category: Clean Code'</p>
<hr />
<div>FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL.<br />
THEY SHOULD DO IT ONLY<br />
<br />
[[Category: Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Functions_Should_Be_SmallFunctions Should Be Small2020-01-27T14:33:12Z<p>Admin: </p>
<hr />
<div>The first rule of functions is that they should be small. The second rule of functions is that<br />
they should be smaller than that. This is not an assertion that I can justify. I can’t provide<br />
any references to research that shows that very small functions are better. What I can tell<br />
you is that for nearly four decades I have written functions of all different sizes. I’ve written several nasty 3,000-line abominations. I’ve written scads of functions in the 100 to 300<br />
line range. And I’ve written '''functions that were 20 to 30 lines long'''. What this experience<br />
has taught me, through long trial and error, is that functions should be very small.<br />
<br />
In the eighties we used to say that a function should be no bigger than a screen-full.<br />
Of course we said that at a time when VT100 screens were 24 lines by 80 columns, and<br />
our editors used 4 lines for administrative purposes. Nowadays with a cranked-down font<br />
and a nice big monitor, you can fit 150 characters on a line and a 100 lines or more on a<br />
screen. Lines should not be 150 characters long. Functions should not be 100 lines long.<br />
Functions should hardly ever be 20 lines long.<br />
<br />
How short should a function be? In 1999 I went to visit Kent Beck at his home in Oregon. We sat down and did some programming together. At one point he showed me a cute<br />
little Java/Swing program that he called Sparkle. It produced a visual effect on the screen<br />
very similar to the magic wand of the fairy godmother in the movie Cinderella. As you<br />
moved the mouse, the sparkles would drip from the cursor with a satisfying scintillation,<br />
falling to the bottom of the window through a simulated gravitational field. When Kent<br />
showed me the code, I was struck by how small all the functions were. I was used to functions in Swing programs that took up miles of vertical space. Every function in this program was just two, or three, or four lines long. Each was transparently obvious. Each told<br />
a story. And each led you to the next in a compelling order. That’s how short your functions<br />
should be!<br />
<br />
== Blocks and Indenting ==<br />
This implies that the blocks within if statements, else statements, while statements, and<br />
so on should be one line long. Probably that line should be a function call. Not only does<br />
this keep the enclosing function small, but it also adds documentary value because the<br />
function called within the block can have a nicely descriptive name.<br />
This also implies that functions should not be large enough to hold nested structures.<br />
Therefore, '''the indent level of a function should not be greater than one or two'''. This, of<br />
course, makes the functions easier to read and understand.<br />
<br />
[[Category: Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Method_NamesMethod Names2020-01-27T14:25:08Z<p>Admin: Criou página com 'Methods should have verb or verb phrase names like postPayment, deletePage, or save. Accessors, mutators, and predicates should be named for their value and prefixed with get,...'</p>
<hr />
<div>Methods should have verb or verb phrase names like postPayment, deletePage, or save.<br />
Accessors, mutators, and predicates should be named for their value and prefixed with get,<br />
set, and is according to the javabean standard.<br />
<br />
<source lang="Java"><br />
string name = employee.getName();<br />
customer.setName("mike");<br />
if (paycheck.isPosted())...<br />
</source><br />
<br />
When constructors are overloaded, use static factory methods with names that<br />
describe the arguments. For example,<br />
<br />
<source lang="Java"><br />
Complex fulcrumPoint = Complex.FromRealNumber(23.0);<br />
</source><br />
<br />
is generally better than<br />
<br />
<source lang="Java"><br />
Complex fulcrumPoint = new Complex(23.0);<br />
</source><br />
<br />
Consider enforcing their use by making the corresponding constructors private.<br />
<br />
[[Category: Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Class_NamesClass Names2020-01-27T14:22:47Z<p>Admin: Criou página com 'Classes and objects should have noun or noun phrase names like '''Customer''', '''WikiPage''', '''Account''', and '''AddressParser'''. Avoid words like '''Manager''', '''Proce...'</p>
<hr />
<div>Classes and objects should have noun or noun phrase names like '''Customer''', '''WikiPage''',<br />
'''Account''', and '''AddressParser'''. Avoid words like '''Manager''', '''Processor''', '''Data''', or '''Info''' in the name<br />
of a class. A class name should not be a verb.<br />
<br />
[[Category:Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Interfaces_and_ImplementationsInterfaces and Implementations2020-01-27T14:19:04Z<p>Admin: </p>
<hr />
<div>These are sometimes a special case for encodings. For example, say you are building an<br />
ABSTRACT FACTORY for the creation of shapes. This factory will be an interface and will<br />
be implemented by a concrete class. What should you name them? '''IShapeFactory''' and<br />
'''ShapeFactory'''? I prefer to leave interfaces unadorned. The preceding I, so common in<br />
today’s legacy wads, is a distraction at best and too much information at worst. I don’t<br />
want my users knowing that I’m handing them an interface. I just want them to know that<br />
it’s a '''ShapeFactory'''. So if I must encode either the interface or the implementation, I choose<br />
the implementation. Calling it '''ShapeFactoryImp''', or even the hideous '''CShapeFactory''', is preferable to encoding the interface.<br />
<br />
[[Category:Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Don%27t_Use_Member_PrefixesDon't Use Member Prefixes2020-01-27T14:17:30Z<p>Admin: </p>
<hr />
<div>You also don’t need to prefix member variables with m_ anymore. Your classes and functions should be small enough that you don’t need them. And you should be using an editing environment that highlights or colorizes members to make them distinct.<br />
<br />
No:<br />
<source lang="Java"><br />
public class Part {<br />
private String m_dsc; // The textual description<br />
void setName(String name) {<br />
m_dsc = name;<br />
}<br />
}<br />
</source><br />
<br />
Ok:<br />
<br />
<source lang="Java"><br />
public class Part {<br />
String description;<br />
void setDescription(String description) {<br />
this.description = description;<br />
}<br />
}<br />
</source><br />
<br />
[[Source: Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Avoid_encodings:_Hungarian_NotationAvoid encodings: Hungarian Notation2020-01-27T14:09:45Z<p>Admin: </p>
<hr />
<div>Java programmers don’t need type encoding. Objects are strongly typed, and editing<br />
environments have advanced such that they detect a type error long before you can run a<br />
compile! So nowadays HN and other forms of type encoding are simply impediments.<br />
They make it harder to change the name or type of a variable, function, or class. They<br />
make it harder to read the code. And they create the possibility that the encoding system<br />
will mislead the reader.<br />
<br />
Examples of Hungarian Notation:<br />
<br />
* '''lAccountNum''' : variable is a long integer ("l");<br />
* '''arru8NumberList''' : variable is an array of unsigned 8-bit integers ("arru8");<br />
* '''bReadLine(bPort,&arru8NumberList)''' : function with a byte-value return code.<br />
* '''strName''' : Variable represents a string ("str") containing the name, but does not specify how that string is implemented.<br />
* '''rwPosition''' : variable represents a row ("rw");<br />
* '''usName''' : variable represents an unsafe string ("us"), which needs to be "sanitized" before it is used (e.g. see code injection and cross-site scripting for examples of attacks that can be caused by using raw user input)<br />
* '''szName''' : variable is a zero-terminated string ("sz"); this was one of Simonyi's original suggested prefixes.<br />
* '''pX''' is a pointer to another type X; this contains very little semantic information.<br />
* '''d''' is a prefix meaning difference between two values; for instance, dY might represent a distance along the Y-axis of a graph, while a variable just called y might be an absolute position. This is entirely semantic in nature.<br />
* '''sz''' is a null- or zero-terminated string. In C, this contains some semantic information because it is not clear whether a variable of type char* is a pointer to a single character, an array of characters or a zero-terminated string.<br />
* '''w''' marks a variable that is a word. This contains essentially no semantic information at all, and would probably be considered Systems Hungarian.<br />
* '''b''' marks a byte, which in contrast to w might have semantic information, because in C the only byte-sized data type is the char, so these are sometimes used to hold numeric values. This prefix might clear ambiguity between whether the variable is holding a value that should be treated as a character or a number.<br />
<br />
Examples related to type:<br />
<br />
* '''bBusy''' : boolean<br />
* '''chInitial''' : char<br />
* '''cApples''' : count of items<br />
* '''dwLightYears''' : double word (Systems)<br />
* '''fBusy''' : flag (or float)<br />
* '''nSize''' : integer (Systems) or count (Apps)<br />
* '''iSize''' : integer (Systems) or index (Apps)<br />
* '''fpPrice''': floating-point<br />
* '''dbPi''' : double (Systems)<br />
* '''pFoo''' : pointer<br />
* '''rgStudents''' : array, or range<br />
* '''szLastName''' : zero-terminated string<br />
* '''u16Identifier''' : unsigned 16-bit integer (Systems)<br />
* '''u32Identifier''' : unsigned 32-bit integer (Systems)<br />
* '''stTime''' : clock time structure<br />
* '''fnFunction''' : function name<br />
<br />
* '''pszOwner''' : pointer to zero-terminated string<br />
* '''rgfpBalances''' : array of floating-point values<br />
* '''aulColors''' : array of unsigned long (Systems)<br />
<br />
<br />
[[Category: Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Use_Searchable_NamesUse Searchable Names2020-01-27T13:52:11Z<p>Admin: Criou página com 'Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text. One might easily grep for MAX_CLASSES_PER_STUDE...'</p>
<hr />
<div>Single-letter names and numeric constants have a particular problem in that they are not<br />
easy to locate across a body of text.<br />
<br />
One might easily grep for MAX_CLASSES_PER_STUDENT, but the number 7 could be more<br />
troublesome. Searches may turn up the digit as part of file names, other constant definitions, and in various expressions where the value is used with different intent. It is even<br />
worse when a constant is a long number and someone might have transposed digits,<br />
thereby creating a bug while simultaneously evading the programmer’s search.<br />
<br />
Likewise, the name e is a poor choice for any variable for which a programmer might<br />
need to search. It is the most common letter in the English language and likely to show up<br />
in every passage of text in every program. In this regard, longer names trump shorter<br />
names, and any searchable name trumps a constant in code.<br />
<br />
My personal preference is that single-letter names can ONLY be used as local variables inside short methods. The length of a name should correspond to the size of its scope If a variable or constant might be seen or used in multiple places in a body of code,<br />
it is imperative to give it a search-friendly name. Once again compare:<br />
<br />
<source lang="Java"><br />
for (int j=0; j<34; j++) {<br />
s += (t[j]*4)/5;<br />
}<br />
</source><br />
<br />
To:<br />
<br />
<source lang="Java"><br />
int realDaysPerIdealDay = 4;<br />
const int WORK_DAYS_PER_WEEK = 5;<br />
int sum = 0;<br />
for (int j=0; j < NUMBER_OF_TASKS; j++) {<br />
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;<br />
int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);<br />
sum += realTaskWeeks;<br />
}<br />
</source><br />
<br />
<br />
[[Category: Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Use_Pronounceable_NamesUse Pronounceable Names2020-01-27T13:45:48Z<p>Admin: </p>
<hr />
<div>Humans are good at words. A significant part of our brains is dedicated to the concept of<br />
words. And words are, by definition, pronounceable. It would be a shame not to take<br />
advantage of that huge portion of our brains that has evolved to deal with spoken language. So make your names pronounceable.<br />
<br />
If you can’t pronounce it, you can’t discuss it without sounding like an idiot. “Well,<br />
over here on the bee cee arr three cee enn tee we have a pee ess zee kyew int, see?” This<br />
matters because programming is a social activity.<br />
<br />
A company I know has genymdhms (generation date, year, month, day, hour, minute,<br />
and second) so they walked around saying “gen why emm dee aich emm ess”. I have an<br />
annoying habit of pronouncing everything as written, so I started saying “gen-yah-muddahims.” It later was being called this by a host of designers and analysts, and we still<br />
sounded silly. But we were in on the joke, so it was fun. Fun or not, we were tolerating<br />
poor naming. New developers had to have the variables explained to them, and then they<br />
spoke about it in silly made-up words instead of using proper English terms. Compare:<br />
<br />
<source lang="Java"><br />
class DtaRcrd102 {<br />
private Date genymdhms;<br />
private Date modymdhms;<br />
private final String pszqint = "102";<br />
/* ... */<br />
};<br />
</source><br />
<br />
To:<br />
<br />
<source lang="Java"><br />
class Customer {<br />
private Date generationTimestamp;<br />
private Date modificationTimestamp;;<br />
private final String recordId = "102";<br />
/* ... */<br />
};<br />
</source><br />
<br />
Intelligent conversation is now possible: “Hey, Mikey, take a look at this record! The generation timestamp is set to tomorrow’s date! How can that be?”<br />
<br />
[[Category:Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Use_Intent_Revealing_NamesUse Intent Revealing Names2020-01-27T13:31:15Z<p>Admin: /* Avoid Disinformation */</p>
<hr />
<div>It is easy to say that names should reveal intent. What we want to impress upon you is that<br />
we are serious about this. Choosing good names takes time but saves more than it takes.<br />
<br />
So take care with your names and change them when you find better ones. Everyone who<br />
reads your code (including you) will be happier if you do.<br />
<br />
The name of a variable, function, or class, should answer all the big questions. It<br />
should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.<br />
<br />
<source lang="Java"><br />
int d; // elapsed time in days<br />
</source><br />
<br />
The name d reveals nothing. It does not evoke a sense of elapsed time, nor of days. We<br />
should choose a name that specifies what is being measured and the unit of that measurement:<br />
<br />
<source lang="Java"><br />
int elapsedTimeInDays;<br />
int daysSinceCreation;<br />
int daysSinceModification;<br />
int fileAgeInDays;<br />
</source><br />
<br />
Choosing names that reveal intent can make it much easier to understand and change<br />
code. What is the purpose of this code?<br />
<br />
<source lang="Java"><br />
public List<int[]> getThem() {<br />
List<int[]> list1 = new ArrayList<int[]>();<br />
for (int[] x : theList)<br />
if (x[0] == 4)<br />
list1.add(x);<br />
return list1;<br />
}<br />
</source><br />
<br />
Why is it hard to tell what this code is doing? There are no complex expressions.<br />
Spacing and indentation are reasonable. There are only three variables and two constants<br />
mentioned. There aren’t even any fancy classes or polymorphic methods, just a list of<br />
arrays (or so it seems).<br />
<br />
The problem isn’t the simplicity of the code but the implicity of the code (to coin a<br />
phrase): the degree to which the context is not explicit in the code itself. The code implicitly requires that we know the answers to questions such as:<br />
<br />
1. What kinds of things are in theList?<br />
<br />
2. What is the significance of the zeroth subscript of an item in theList?<br />
<br />
3. What is the significance of the value?<br />
<br />
4. How would I use the list being returned?<br />
<br />
== Avoid Disinformation ==<br />
<br />
The answers to these questions are not present in the code sample, but they could have<br />
been. Say that we’re working in a mine sweeper game. We find that the board is a list of<br />
cells called theList. Let’s rename that to gameBoard.<br />
<br />
Each cell on the board is represented by a simple array. We further find that the zeroth<br />
subscript is the location of a status value and that a status value of 4 means “flagged.” Just<br />
by giving these concepts names we can improve the code considerably:<br />
<br />
<source lang="Java"><br />
public List<int[]> getFlaggedCells() {<br />
List<int[]> flaggedCells = new ArrayList<int[]>();<br />
for (int[] cell : gameBoard)<br />
if (cell[STATUS_VALUE] == FLAGGED)<br />
flaggedCells.add(cell);<br />
return flaggedCells;<br />
}<br />
</source><br />
<br />
Notice that the simplicity of the code has not changed. It still has exactly the same number<br />
of operators and constants, with exactly the same number of nesting levels. But the code<br />
has become much more explicit.<br />
<br />
We can go further and write a simple class for cells instead of using an array of ints.<br />
It can include an intention-revealing function (call it isFlagged) to hide the magic numbers. It results in a new version of the function:<br />
<br />
<source lang="Java"><br />
public List<Cell> getFlaggedCells() {<br />
List<Cell> flaggedCells = new ArrayList<Cell>();<br />
for (Cell cell : gameBoard)<br />
if (cell.isFlagged())<br />
flaggedCells.add(cell);<br />
return flaggedCells;<br />
}<br />
</source><br />
<br />
With these simple name changes, it’s not difficult to understand what’s going on. This is<br />
the power of choosing good names.<br />
<br />
[[Category:Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/Clean_CodeClean Code2020-01-27T13:30:27Z<p>Admin: </p>
<hr />
<div>== General rules ==<br />
* Follow standard conventions.<br />
* Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.<br />
* Boy scout rule. Leave the campground cleaner than you found it.<br />
* Always find root cause. Always look for the root cause of a problem.<br />
<br />
== Design rules ==<br />
* Keep configurable data at high levels.<br />
* Prefer polymorphism to if/else or switch/case.<br />
* Separate multi-threading code.<br />
* Prevent over-configurability.<br />
* Use dependency injection.<br />
* Follow Law of Demeter. A class should know only its direct dependencies.<br />
<br />
== Understandability tips ==<br />
* Be consistent. If you do something a certain way, do all similar things in the same way.<br />
* Use explanatory variables.<br />
* Encapsulate boundary conditions. Boundary conditions are hard to keep track of. Put the processing for them in one place.<br />
* Prefer dedicated value objects to primitive type.<br />
* Avoid logical dependency. Don't write methods which works correctly depending on something else in the same class.<br />
* Avoid negative conditionals.<br />
<br />
== Meaningful Names ==<br />
* [[Use Intent Revealing Names]]<br />
* [[Use Pronounceable Names]]<br />
* [[Use Searchable Names]]<br />
* [[Avoid encodings: Hungarian Notation]]<br />
* [[Don't Use Member Prefixes]]<br />
* [[Interfaces and Implementations]]<br />
* [[Class Names]]<br />
* [[Method Names]]<br />
<br />
== Functions rules == <br />
* [[Functions Should Be Small]]<br />
* [[Functions Should Do One Thing]]<br />
* Use descriptive names.<br />
* Prefer fewer arguments.<br />
* Have no side effects.<br />
* Don't use flag arguments. Split method into several independent methods that can be called from the client without the flag.<br />
<br />
== Comments rules == <br />
* Always try to explain yourself in code.<br />
* Don't be redundant.<br />
* Don't add obvious noise.<br />
* Don't use closing brace comments.<br />
* Don't comment out code. Just remove.<br />
* Use as explanation of intent.<br />
* Use as clarification of code.<br />
* Use as warning of consequences.<br />
<br />
== Source code structure == <br />
* Separate concepts vertically.<br />
* Related code should appear vertically dense.<br />
* Declare variables close to their usage.<br />
* Dependent functions should be close.<br />
* Similar functions should be close.<br />
* Place functions in the downward direction.<br />
* Keep lines short.<br />
* Don't use horizontal alignment.<br />
* Use white space to associate related things and disassociate weakly related.<br />
* Don't break indentation.<br />
<br />
== Objects and data structures == <br />
* Hide internal structure.<br />
* Prefer data structures.<br />
* Avoid hybrids structures (half object and half data).<br />
* Should be small.<br />
* Do one thing.<br />
* Small number of instance variables.<br />
* Base class should know nothing about their derivatives.<br />
* Better to have many functions than to pass some code into a function to select a behavior.<br />
* Prefer non-static methods to static methods.<br />
<br />
== Tests == <br />
* One assert per test.<br />
* Readable.<br />
* Fast.<br />
* Independent.<br />
* Repeatable.<br />
<br />
== Code smells == <br />
* Rigidity. The software is difficult to change. A small change causes a cascade of subsequent changes.<br />
* Fragility. The software breaks in many places due to a single change.<br />
* Immobility. You cannot reuse parts of the code in other projects because of involved risks and high effort.<br />
* Needless Complexity.<br />
* Needless Repetition.<br />
* Opacity. The code is hard to understand.<br />
<br />
[[Category:Clean Code]]</div>Adminhttp://www.basef.com.br/index.php/AngularAngular2020-01-27T12:41:15Z<p>Admin: Criou página com '* Creating a new class * Creating a new component * Creating a new directive * Creating a new project * Creating a new project with Sass * Creating a new...'</p>
<hr />
<div>* [[Creating a new class]]<br />
* [[Creating a new component]]<br />
* [[Creating a new directive]]<br />
* [[Creating a new project]]<br />
* [[Creating a new project with Sass]]<br />
* [[Creating a new service]]<br />
* [[Creating a new router]]<br />
* [[Custom validator in Angular2]]<br />
* [[Data binding]]<br />
* [[Disabled input in Angular2]]<br />
* [[Example of Http Interceptor for login authentication]]<br />
* [[Example of CanLoad and CanActivate for login authentication]]<br />
* [[Installing Angular Cli]]<br />
* [[Installing Angular Material]]<br />
* [[Installing Sinon]]<br />
* [[Model Driven Forms (Reactive forms) in Angular2]]<br />
* [[Unit testing with default Angular installation]]<br />
* [[Validation in Model Driven Forms in Angular2]]<br />
* [[Validating Date from and Date to]]<br />
<br />
[[Category:Angular]]</div>Admin