"Beauty will save the world"
Fyodor Dostoyevsky

"Beauty will save programming"
Michael Zuskin (LinkedIn)

The ideas, described in this site, dramatically decrease code complexity and make the code clearer, more understandable and less confusing. That results in quicker development and easier maintenance/enhancement. And less bugs. And easier bugs investigation and fixing.

Should our code be elegant?

Code elegance... Sounds nice, but is it really so important? Does it simplify the developer's work? Can it define a project's success? Can a lack of it contribute to a project's failure? All these questions have the same answer - yes. I believe that the most important component of business applications creators' work is understanding of the business, expertise in organizing and processing data and ability to explore and understand enterprise systems (which includes knowledge of OOP on the level of feeling). But code writing style is important as well - in fact, each aspect of the programmer's work (including code writing professionalism) plays a critical role. Even though coding style mistakes are looking insignificant, they are accumulating over time and, finally, quantity turns into quality. Even a small needle can blow up a big balloon!

I have seen programmers which came to development from the business sector. Usually, they wrote code in a very straightforward way, without too much thinking (or even knowing?) about good coding practices. Unfortunately, I've also seen many bad coders with Computer Science / Software Engineering background. And that is not surprising at all! I myself never heard about elegant coding style in the nice days of college. OK, we learned some stuff like the advice to avoid code duplication, but it was buried between million other things, most of which were much less important. Fortunately, when I was a junior developer, I had very severe teachers - technical leads with zero tolerance to stupid things in my code. Later, working with complicated software, I always remembered these people with gratitude: they forced me to always think about optimal code organizing, and constantly use simple, but very useful tricks. Thanks to these people, I know that even complex systems can be written in a simple way.

Only 3.5 developers were occupied in one of the most large-scale projects I worked in (the PM, one other developer and me + sometimes fourth guy joined us to help before deadlines). The main reason for so high effectiveness was the use of a good framework library (so we thought mostly about "what" to develop - not "how", in other words - wrote minimum of technical code concentrating on business issues). And the second reason - the application was written using many rules described in this site. All applications in that company had elegant code, controlled by very strict and even ruthless code reviewers. On the other hand, I participated in enhancement of legacy applications which were much-much simpler from the user's perspective, but with much-much more people involved. Whole IT departments were struggling with tons of mixty-maxty, hopelessly labyrinthine code. Every year those companies spent huge amounts to pay salaries to extra workers only because the initial development was based on copypaste and long functions rather than smart refactoring of code, and without utilizing defensive programming - writing code which automatically raises alarms in case problems (to prevent bugs, which would be hard to detect and investigate, as early as possible), and so ensures foolproofing during the whole app life - from initial unit testing to future changes. This was especially insulting because correct coding does not require a great mind - it only requires knowledge of (and adherence to) a few simple principles!

From the book "Clean Code":

If you have been a programmer for longer than two or three years, you have probably been slowed down by messy code. The degree of the slowdown can be significant. Over the span of a year or two, teams that were moving very fast at the beginning of a project can find themselves moving at a snail's pace. Every change they make to the code breaks two or three other parts of the code. No change is trivial. Every addition or modification to the system requires that the tangles, twists, and knots be "understood" so that more tangles, twists, and knots can be added. Over time the mess becomes so big and so deep and so tall, they can not clean it up. There is no way at all.

As the mess builds, the productivity of the team continues to decrease, asymptotically approaching zero. As productivity decreases, management does the only thing they can; they add more staff to the project in hopes of increasing productivity. But that new staff is not versed in the design of the system. They don't know the difference between a change that matches the design intent and a change that thwarts the design intent. Furthermore, they, and everyone else on the team, are under horrific pressure to increase productivity. So they all make more and more messes, driving the productivity ever further toward zero.

Elegant code adopts aesthetics to achieve high maintainability

People who have programmed with me know that I put a lot of effort in my coding style. I indeed consider programming a creative act, which necessarily involves aesthetics. And then, some people consider aesthetics the enemy of the pragmatic: "don't spend time writing beautiful code when you can write effective code". However, I argue that my sense of beauty serves pragmatism much better, because it leads to more concise and maintainable code, and is thereby far more effective.

Recognizing the creative aspect makes programming more than meeting functionality

Computer scientists are taught to program properly, just like linguists are taught how to write literary texts. However, not all computer scientists are programmers, just like not all linguists are writers, although most of us program regularly. For some reason, many programmers seem to think their role is to write code that only makes things work. It's not. Your job is to solve a problem with code in the most elegant way, such that your solution is easy to adapt, modify and reuse. Just like "the grass is green and the sky blue" is not literature, although it might perfectly describe the environment, coding something that just works is not programming. It's fiddling.

Code is read more than written

One programmer writes "poems", another likes to write really boring "prose", but in the end of the day, both chunks of code do the same. They don't. The first law of programming: code is read more than written. Functionality is only one of the many aspects of code. Robustness and maintainability, to name a few. Your code is not a black box, as it will be read and modified in the future - by yourself or by other people. By coding without paying attention to rules of elegant coding, you essentially make your code a black box, undecipherable for anybody (including yourself).

The root of all evil

People writing bad code are often really good at defending it, sometimes with an attitude of pride that they don't belong to a group of hippies who think code should be beautiful. "But... coding in style takes more time!" Oh, does it? Tell me what takes more time: sitting back to think and write beautiful code, or quickly writing something that just works and then having to fix bugs? After all, the number of bugs in code is proportional to the number of lines, so expressing ideas clearly and elegantly is important for code quality.

Programmers are functional artists

Elegant code reads like well-written book. Programming is an art and therefore, we are artists. However, we're not the kind of artists that create purely for beauty. We are functional artists. We have a functional task as well as the duty to write beautiful code, because it is effective and thus lasts. Writing elegant code is our job. In a sense, this makes us similar to magazine lay-outers. Their job is to make articles readable, yet in the most pleasing way. This helps people find their way to the contents of those articles, just like great code helps people find their way to places they need to enhance.

Don't pat yourself on the back because you can write complicated code. It's likely you're doing it wrong. Programming is understanding a problem well enough to be able to explain it as simple as possible to a machine. Defending sloppy code by claiming effectiveness is trying to hide what you don't understand: the problem.

Think defensively!

Resilient code is code that is designed to last, and to be safely reused by others. Code that is not susceptible to being broken by unexpected use cases. Defensive programming is producing of resilient code that robustly and gracefully handles cases of unintended use, and is resilient to future changes.

Many developers stop work as soon as their code passes a few basic tests to confirm that it produces the "right result" in a given use case. They do not consider the other possible ways in which the code might be used in the future. How their code will respond to common change, such as a table column switched from required to nullable, or introduction of a new customer status? In the short-term, this approach is attractive; those developers get things done faster. However, if the code is designed to be used for more than just a few months, then it is very likely that such changes can and will occur, and the inevitable result is broken code or, even worse, code that silently starts to behave differently, or produce different results. When this happens, the data integrity is threatened, as is the validity of the reports on which critical business decisions are often based. At this point, years later (long after the original developer has forgotten what she/he was doing, or even left the company), begins the painstaking process of troubleshooting and fixing the problem.

Would it not be easier to prevent all this troubleshooting from happening? Would it not be better to spend a little more time and effort during original development, to save considerably more time on troubleshooting, bug fixing, retesting, and redeploying? After all, many of the problems that cause our code to break are very common; they repeat over and over again in different teams and on different projects. This is what defensive programming is all about: we learn what can go wrong with our code, and we proactively identify and eliminate potential vulnerabilities during development rather than after the event when the problems have already occurred.

Why am I writing about devensive programming in a site, dedicated to elegant code? Because code, which is vulnerable, is not looking elegant to me. In most cases, code elegance has nothing to do with cosmetic look. For more details, please read the topic Defensive programming. Defuse time bombs!.

Write code as if you had to support it for the rest of your life

That's it. If you accept this notion, many wonderful things will happen. If you were to accept that any of your previous or current employers had the right to call you in the middle of the night, asking you to explain the choices you made while writing the fooBar method, you would gradually improve toward becoming an expert programmer. You would naturally want to come up with better variable and method names. You would stay away from blocks of code comprising hundreds of lines. You would write comments and refactor continually. Supporting all the code you'd ever written for the rest of your life should also be a scalable endeavor. You would therefore have no choice but to become better, smarter, and more efficient.

Michael Feathers, author of "Working Effectively with Legacy Code": I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought about by the code's author, and if you try to imagine improvements, you're led back to where you are, sitting in appreciation of the code someone left for you - code left by someone who cares deeply about the craft. One word: care. That's really the topic of this site. Elegant code is code that has been taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.

Now, let's go from theory to practice!

Dealing with tons of code written by others (while enhancing and changing existing systems), I noticed that programmers usually make the same typical mistakes. Even though some of the mistakes are pretty severe, the good news is that the list of them is quite short. So, if somebody will decide to facilitate their life by improving the coding style, that will require pretty small efforts.

The ideas are illustrated with multiple code examples in Java and PowerBuilder (abbreviated as PB), sometimes in PL/SQL and T-SQL. But they will be clear and easily understood by developers, using any programming language:

• The Art of Naming:

Give exact names which clearly reveal intent <<< IMPORTANT!!!
Names consistency
Abbreviations in names

• Code Writing Style:

Over-indenting is the enemy number one <<< IMPORTANT!!!
Store returned values in variables; avoid complex nested expressions <<< IMPORTANT!!!
Defensive programming. Defuse time bombs! <<< IMPORTANT!!!
Application codes <<< IMPORTANT!!!
No loop condition duplicating
/* Comments */
Private and public affairs in instance variables
Write RETURN in the end of void methods

• Managing Functions:

Keep functions simple <<< IMPORTANT!!!
Code blocks must be short <<< IMPORTANT!!!
Code after validations <<< IMPORTANT!!!
Refactor to prevent duplication <<< IMPORTANT!!!
Private and public affairs in functions
Law of Demeter (or Principle of Least Knowledge)

• Intriguing World of Logic:

Boolean flags naming
Positive wording in Boolean names
Positive comparison in Boolean expressions
Comparing ONE value with MANY others
Short conditions in IFs <<< IMPORTANT!!!
Boolean functions
Populating Boolean variables
Don't return null from Boolean functions
De Morgan's Laws
Short-circuit evaluation

• Ocean of Databases:

Only surrogate primary keys <<< IMPORTANT!!!
Simple SQL <<< IMPORTANT!!!
WHERE clause
Mention fields names in INSERT statement (SQL Server)
Temp table in stored proc (SQL Server)
Existence checking
Avoid client-side SQL - call stored procedures instead <<< IMPORTANT!!!
Debugging T-SQL stored procedures without debugger

The rest of the stuff is for PowerBuider developers only:

• PowerBuider Tips and Tricks:

DataWindow Spy <<< IMPORTANT!!!
Power Building with Exceptions <<< IMPORTANT!!!
Access inter-objects parameters by name
Passing parameters between objects
iin() + global functions overloading
Avoid row-by-row scanning
Don't implement functionality in built-in events
Copy data between DWs/DSs
Check if column/row has REALLY been modified
Use constants always
Oracle packaged procedure as DW data source
How to overcome long-circuit evaluation
Convert DW to... zebra!
Save DataStore from debugger
uf_ds_from_sql() to create DataStore by dynamic SELECT <<< IMPORTANT!!!
uf_in_clause_from_array() to build SQL's IN clause dynamically
uf_ds_from_array() to convert array to DataStore
uf_protect_col() for smart column protection
uf_row_exist() to replace Find()
uf_filter() to replace Filter()
uf_show_columns() to show only certain columns in DW
uf_set_row_status() to replace SetItemStatus()
uf_lookup_display() to obtain DropDown's display value
uf_value_exists_in_array() to check if array has a value
uf_display_in_center() to group buttons in the middle
uf_destroy() to POST objects' Destroy
uf_get_pb_version() to report PowerBuilder's version
uf_replace_all() to replace all occurrences of substring
CHOOSE CASE TRUE for a series of validations
Indentation in CHOOSE CASE
Change objects' default names
Technical code vs. business code
Return policy
Local Variables Declaration
Use REF keyword
Constants used all over the application
Constants serving local needs
Null constants
Make DYNAMIC calls safer
Change default access level of class members
Don't DESTROY objects
No global variables and functions
Avoid SQL
Don't duplicate conditions in Boolean expressions
Populate a DrpDownListBox with years

From the book "97 Things Every Programmer Should Know":

You Gotta Care About the Code

It doesn't take Sherlock Holmes to work out that good programmers write good code. Bad programmers - don't. They produce monstrosities that the rest of us have to clean up. You want to write the good stuff, right? You want to be a good programmer.

Good code doesn't pop out of thin air. It isn't something that happens by luck when the planets align. To get good code, you have to work at it. And you'll only get good code if you actually care about good code.

Good programming is not born from mere technical competence. I've seen highly intellectual programmers who can produce intense and impressive algorithms, who know their language standard by heart, but who write the most awful code. It's painful to read, painful to use, and painful to modify. I've seen more humble programmers who stick to very simple code, but who write elegant and expressive programs that are a joy to work with.

Based on my years of experience in the software factory, I've concluded that the real difference between adequate programmers and great programmers is this: attitude. Good programming lies in taking a professional approach, and wanting to write the best software you can, within the real-world constraints and pressures of the software factory.

The code to hell is paved with good intentions. To be an excellent programmer, you have to rise above good intentions, and actually care about the code - foster positive perspectives and develop healthy attitudes. Great code is carefully crafted by master artisans, not thoughtlessly hacked out by sloppy programmers or erected mysteriously by self-professed coding gurus.

You want to write good code. You want to be a good programmer. So, you care about the code:

1. You write code that is discoverable (that other programmers can easily pick up and understand), that is maintainable (that you, or other programmers, will be easily able to modify in the future), and that is correct (you take all steps possible to determine that you have solved the problem, not just made it look like the program works).

2. You work well alongside other programmers. No programmer is an island. Few programmers work alone; most work in a team of programmers, either in a company environment or on an open source project. You consider other programmers and construct code that others can read. You want the team to write the best software possible, rather than to make yourself look clever.

Fortunately, you're reading this collection of advice because you do care about code. It interests you. It's your passion. Have fun programming. Enjoy cutting code to solve tricky problems. Produce software that makes you proud.

It is currently 17 Jul 2019, 23:34

  • Java
    11 Topics
    12 Posts
    Last post by Ursego View the latest post
    20 May 2019, 09:34

Login  •  Register

Who is online

In total there are 3 users online :: 0 registered, 0 hidden and 3 guests (based on users active over the past 5 minutes)
Most users ever online was 93 on 10 Jul 2019, 13:20

Registered users: No registered users
Legend: Administrators, Global moderators


Total posts 158 • Total topics 111 • Total members 94 • Our newest member jagonzo62

Professional code inspectors at work:

Information from Programming is an Art was used.

IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:

free counters

eXTReMe Tracker