четверг, 7 января 2016 г.

15 rules of writing quality code


There are millions of ways to write bad code. Fortunately, to rise to the level of quality code, just follow the 15 rules. Their observance will not make you the master, but will allow convincingly simulate it.
● Rule 1: Follow the programming style.
Every programming language has its own programming style that tells how to indent, where to put the spaces and brackets as name objects, how to comment code etc.
For example, this piece of code in accordance with the standard error have 12:
for (i = 0; i <10; i ++) {
Study the standard of care, learn the basics by heart, follow the rules as the commandments, and your program will be better than most written graduates.
Many organizations will adapt standards to suit your specific needs. For example, Google has developed standards for more than 12 programming languages. They are well thought out, so read them, if you need help in programming at Google. Standards even include configuration editor that will help you to comply with the style and special tools, your code is verified for compliance with this style. Use them.
● Rule 2: Let's descriptive names.
Restricted slow, clumsy teletypes, programmers used in antiquity contracts for variable names and procedures to save time, knocking on the keys, ink and paper. This culture is present in some communities for the sake of backward compatibility. Take, for example, break the language function C wcscspn (wide character string complement span). But this approach is not applicable in the present code.
Use long descriptive names like complementSpanLength, to help themselves and colleagues to understand your code in the future. Exceptions are a few important variables used in the method body, such as iterators cycles, parameters, time values, or the results of execution.
More importantly, you have to think long and hard before something called. Is the exact name? Did you due highestPrice instead bestPrice? Is there enough specific name in order to avoid its use in other contexts for similar within the meaning of the objects? Is not it better to call a method getBestPrice instead getBest? Is it better than other similar names? If you have a method ReadEventLog, you should not call other NetErrorLogRead. If you call the function, whether its name describes the return value?
In conclusion, a few simple rules for naming. Class names and types must be nouns. The name of the method should contain a verb. If the method determines whether any information about the object is true or false, the name must begin with «is». Methods that return the properties of objects, must begin with «get», and set property values ​​- «set».
● Rule 3. Comment and document.
Start each method and the procedure described in the comments that the method or process does, parameters, return values ​​and possible errors and exceptions. Describe the role of each in the comments of the file and the class content of each class of the field, and the basic steps of a complex code. Write comments as code development. If you believe that then write them, you are cheating yourself.
In addition, make sure that your application or library, there is a guide that explains what your code does, determines its dependencies and provides instructions for assembling, testing, installation and use. The document must be short and easy; a README-file often enough.
● Rule 4: Do not repeat.
Never copy and paste code. Instead, select a common part to a method or a class (or a macro, if necessary), and use it with the appropriate parameters. Avoid using these and similar pieces of code. Also, use the following techniques:
Creating API reference of the comments using Javadoc and Doxygen.
Automatic generation of test Unit-based annotations and naming conventions.
Generate PDF and HTML markup from one source.
Getting the class structure of the database (or vice versa).
● Rule 5. Check for errors and respond to them.
Methods can return the signs of bugs or throw exceptions. Treat them. Do not rely on the fact that the drive is never full, your configuration file will always be in place, your application will run with all the necessary rights, requests for memory allocation will always be successfully fulfilled, or that the connection is never cut short. My Computer - Best Public! Yes, a good error handling difficult to write, and it makes the code is longer and harder to read. But ignoring the errors just sweeps the problem under the carpet, where the unsuspecting user once it detects.
● Rule 6. Separate the code into short, separate parts.
Each method, function, or code block must fit in the normal display window (lines 25-50). If you get a long, divide into smaller pieces. Even within the method of separating the long code blocks, the essence of which can be described in the comment at the beginning of each block.
Moreover, each class, module, file, or process should perform a certain kind of tasks. If a piece of code performs a completely diverse tasks, then divide it accordingly.
● Rule 7 uses an API frameworks and third-party libraries.
Learn what features are available using the API of your framework. and that they can do advanced third-party libraries. If libraries are supported by your system package manager, they are likely to be a good choice. Use the code that holds the desire to reinvent the wheel (though useless square shape).
● Rule 8. Do not go overboard with the design.
Design only what matters now. Your code can be done quite generalized, that it supports the further development, but only if it does not become too complicated. Do not create parameterized classes, factories, deep hierarchies and hidden interfaces to solve problems that did not exist - you can not guess what will happen tomorrow. On the other hand, when the structure of the code does not fit the problem, do not hesitate to refactor it.
● Rule 9. Be consistent.
Do the same thing in the same way. If you develop a method which is similar to the functionality of existing functionality, use a similar name, like the order parameters and a similar body structure. The same applies to classes. Create similar fields and methods, make them similar interfaces, and compares the new names already exist in similar classes.
Your code must match your framework agreements. For example, it is good practice to make half-open ranges: closed (including) to the left (at the beginning of the range) and open (exclusive) to the right (at the end). If a specific case there is no agreement, then make a choice and stick to it fanatically.
● Rule 10. Avoid security issues.
Modern code rarely works in isolation. It is an inevitable risk of becoming the target of attacks. They do not necessarily have to come from the Internet; attack can occur through the input of your application. Depending on your programming language and subject area, you may want to worry about buffer overflows, cross-site scripts, SQL-injections and other similar problems. Read these problems and avoid them in the code. It is not difficult.
● Rule 11. Use efficient data structures and algorithms.
Simple code is often easier to maintain than the same, but modified for the sake of efficiency. Fortunately, you can combine the maintainability and efficiency, using data structures and algorithms that enables your framework. Use the map, set, vector and algorithms that work with them. In this way your code will be cleaner, faster, more scalable and more economical memory. For example, if you save thousands of values ​​in a sorted set, then the intersection operation will find elements in common with the other set for the same number of operations, and not for a million comparisons.
● Rule 12. Use Unit-tests.
The complexity of modern software makes installation more expensive and more difficult to test. Productive approach would be to support every piece of code tests that verify the correctness of his work. This approach simplifies debugging because it allows you to detect errors earlier. Unit-testing is necessary when you are programming in dynamically typed languages ​​like Python and JavaScript, because they catch any errors only at the stage of execution, whereas statically typed languages ​​such as Java, C #, and C ++ can catch some of them in compile time. Unit-testing also allows you to refactor the code with confidence. You can use XUnit to simplify writing tests and automate their start.
● Rule 13. Keep the code portable.
If you have no particular reason, do not use the functionality that is available only on a specific platform. Do not rely on the fact that certain data types (such as integer, indexes and timestamp) will have a particular length (eg, 32 bits), because this parameter is different on different platforms. Keep the messages of the program separately from the code, and to sew up the parameters corresponding to the particular culture (eg, fractional dividers and the whole or part of the date format). Agreement need to code can be run in different countries, so do the localization as painless as possible.
● Rule 14. Make your code going.
Simple team must collect your code into a form that is ready for distribution. The team should allow you to quickly assemble and run the necessary tests. To achieve this, use the automated build tools such as Make, Apache Maven, and Ant. Ideally, you should set an integration system that will scan, collect and test your code with any change.
● Rule 15. Place everything in the version control system.
All of your items - code, documentation, source code tools, build scripts, test data - should be in the version control system. Git and GitHub make this task a cheap and hassle-free. But you are also available, and many other powerful tools and services. You should be able to assemble and test your program on the configured system, just download it from the repository.
Conclusion.
With these 15 rules a part of your daily practice, you will eventually create code that is easier to read, which is well-tested, are more likely to start up correctly, and that it will be much easier to change when the time comes. You also will protect yourself and your users from a large number of headaches.

понедельник, 21 декабря 2015 г.

Using face creams has led to the prolongation of life and weight loss



The ingredients that make up most of the cream, have not only anti-aging effect, but also lead to a decrease in consumption of high-calorie food. This is the conclusion scientists published an article in the journal Aging Cell. This site EurekAlert! He said on Thursday, December 17th.

Scientists have studied the nematode treated included in anti-aging creams compounds such as allantoin, rapamycin and trichostatin A LY-294002. After receiving the drugs the average life span of worms grown by about 20 percent. In addition, they experienced fewer health problems.

As shown by test mutant worm (Caenorhabditis elegans), animals began to eat much less food, resulting in reduced calorie their diet.

Scientists are going to continue their studies. In particular, they are interested in experiments with mammals (which include person), and the molecular mechanisms by which allantoin and other compounds are able to prolong the life of.

What is needed on the plane this small hole in a window?


It turns out that the inside of the "window" is only for noise and heat insulation, creating an air gap between them and the outside "glazed", it is not designed for heavy loads. The internal part of the "glass" made from cheaper plexiglass and therefore they are not so strong. Accordingly, there is a risk that due to the large pressure difference in the air gap between the glass windows in the cabin, the interior "window" may burst. To avoid this, and need is the smallest hole, which helps to normalize pressure, removing excess air.

суббота, 12 декабря 2015 г.

The most original way to heat the house in winter



The couple from Sweden and Charles Marie Granmar Sasilotto dreamed to build a new, low-energy house, but the realization of this idea would require too much financial investment, and threatened the construction delayed for too long.

And then young people have turned to creative architect Bengt Warne, who offered an unusual solution: cover existing house a huge greenhouse.

So there was the metal structure and 4-mm glass, which is used for the construction of greenhouses. As a result, even in winter, there reigns a mild Mediterranean climate.

The couple can even be grown near the house atypical for Scandinavia products - figs, tomatoes and cucumbers. In addition, many home owners save on electricity.

вторник, 8 декабря 2015 г.

Scientists have discovered in Europe, a new deadly infection

The risk of infection is able to withstand even the most powerful drugs.

According to doctors, one person in Denmark contracted the deadly infection. Dangerous bacteria were found in chicken meat imported into the country. When checking the contaminated product revealed that it contained a virus mutated gene that makes it resistant to all known drugs.

Now Danish doctors are working to develop new drugs that can stop the progression of the disease. In the worst case, the virus could kill millions of people worldwide.

In November 2015 Scientists have discovered a new sexually transmitted disease. Infection with Mycoplasma genitalium (MG) is rarely manifested through symptoms. It can cause pelvic inflammatory disease, an inflammation of the urethra and cervix and can potentially lead to infertility in women.

суббота, 5 декабря 2015 г.

10 interesting facts that you should know about black holes


Imagine matter, packed so tightly that nothing could leave its limits. No moon, no planet, not even light. Those black holes - the point at which the gravitational force is so great that it is a danger to all that accidentally enters a fateful line near the black hole. We often talk about where are the black holes are and why they are so important. Below you will find ten facts about black holes - brush up on your knowledge of these beautiful objects.

1. You can not see a black hole directly.
Because a black hole is truly black - light can not escape its limits - it can not be seen directly, using our tools, regardless of what type of electromagnetic radiation, you see (visible light, X-rays, or whatever). But we can see the effects that the black hole has on the immediate environment. For example, the star was too close to the black hole. The black hole naturally attracts the star and breaks it apart. When the matter of the star begins to be absorbed by the black hole, it is accelerated, it becomes hot and glows brightly in X-ray spectrum.

2. In the Milky Way, most likely, there is a black hole.
Clearly, many are concerned the question of how a black hole is dangerous and threatens the world though there is any possibility to be absorbed by the object? The answer is no, astronomers say, although there is a certain probability that the enormous supermassive black hole hidden at the center of our galaxy. Fortunately, we are quite far from the monster - roughly two-thirds of our galaxy from the center - but its effects can be observed from a distance. The European Space Agency says that the black hole in the center of the Milky Way is a million times more massive than our Sun, and is surrounded by amazingly hot gas.

3. Dying stars create a stellar black holes.
Let's say you have a star 20 times as massive of our sun. Our Sun slowly fade; When nuclear fuel is over, the sun slowly become a white dwarf. But with more massive stars does not. When they run out of fuel, gravity suppresses the natural pressure of the star and pushes it inside. When the pressure of nuclear reactions collapses, the gravitation severely squeezes into the core of the star, its outer layers fly in space. This is called a supernova. The remaining core collapses into a singularity - a point of infinite density and zero volume almost. Singularity - the heart of a black hole.

4. Black holes come in different sizes.
There are at least three different types of black holes, NASA claims, ranging from relatively small to those located in galaxies. Primordial black holes - the smallest, their sizes are from a single atom to the whole mountain. Stellar black holes, the most common type, up to 20 times more massive than our sun. And there are monsters in the centers of galaxies - supermassive black holes. They reach millions of solar masses and more. How do these monsters are formed, it is still not really clear.

5. around black holes, strange things happen.
This is best illustrated by the following example. One man (we'll call him a loser) falls into a black hole, while the other person (Lucky) - looks. From the perspective of the lucky watch Jonah will tick slower and slower. This is because according to Einstein's general theory of relativity, time depends on how fast you are moving when you pick up to extreme near-light speed. The black hole distorts space and time so that the time of Jonah is slower. However, in his view the clock runs normally, but at the Lucky - in a hurry.

6. The first black hole found only with the advent of X-ray astronomy.
Cygnus X-1 was first discovered during a flight in a balloon in 1960, but ten years this place has been identified as a black hole. According to NASA, this black hole is 10 times more massive than the sun. Next to it is a blue supergiant star about 20 times more massive than the sun. A black hole sucks in the star, and she glows brightly in X-ray spectrum.

7. Considers that the nearest black hole - 1,600 light-years.
Erroneous measurement V4641 Sagitarii led to the news that the nearest black hole to us is too close to Earth, only 1,600 light-years. Not close enough to be dangerous, but it is much closer than you think. Further investigation showed that the black hole is much further. Looking at the rotation of its companion star, as well as other factors, the scientists in 2014 provided more accurate results - 20 000 light-years.

8. We do not know whether there are wormholes.
A popular topic for a science fiction story - this is when someone falls into a black hole. Some people believe that these objects are a kind of wormhole wormhole standards in other parts of the universe, allowing to travel faster than the speed of light. But the truth is that we still do not know how to describe them in terms of physics. "We have no theory that would unite general relativity with quantum mechanics, we do not know the whole zoo of possible structures of space-time, which could accommodate wormholes" - says Avi Loeb, a physicist at the Harvard-Smithsonian Center for Astrophysics.

9. The black holes are dangerous, but if you find yourself too close.
As people at the zoo, we can observe black holes only if you are outside the event horizon - you can imagine it as a planet's gravitational field. This area is a point of no return, if you get too close, you have no chance to escape. But outside of this area of ​​the black hole can be safely observed. In a broader sense, it means that the black hole is unlikely to absorb the entire universe (unless, of course, in our understanding of the physics of the cosmos does not happen a serious revolution).

10. Black Holes - pets of science fiction.
Taken as many films with the participation of black holes, it is impossible to list them all. Of the latter, it may be noted "Interstellar" by Christopher Nolan - it people travel through the universe to look at the black hole. "Event Horizon" explores the phenomenon of artificial black holes - something like that discussed in the "Star Trek." Obviously, these mysterious objects that distort our perception of reality and simply do not fit into the average person's head, popular with writers, writers and directors - also, in general, not ordinary people.

среда, 2 декабря 2015 г.

The Chinese have declared their readiness to clone humans

Chinese scientists from the project recently the world's largest "factory of clones", declared their readiness to clone humans. The only obstacle to this, according to the Chinese - the public reaction.
According to Agence France-Presse, a large-scale plans in the field of cloning said the executive director of the factory of the future Xu Xiaochun. As previously reported Naked Science, the largest enterprise in the world to clone a Chinese company to build Boyalife Group in collaboration with the South Korean Sooam Biotech Research Foundation and Chinese Academy of Sciences in North China Tianjin.
It is planned that the company will begin work in the next seven months. The volume of production of cloned cows by 2020 will amount to one million per year. The term "Clone Factory" also intends to be engaged in the production of horses for races and police dogs with special abilities (increased sense of smell and search).
Another area of ​​interest is the cloning of primates enterprise for medical experiments. Therefore, the application guide future factory about readiness to move from primates to humans was logical. "The technology is already there. If it is officially allowed, I do not think anyone will cope with this better than Boyalife », - he told reporters Xu Xiaochun. He pointed out that so far no experiments in human cloning enterprise carries.