Tuesday, November 25, 2008

Crap code

I am not the most senior, nor experienced coder in the industry, but I am motivated to improve my coding skill by implementing good coding design via strong typing, interfaces, and proper code placement in response to high-level requirements.

That being said, I consider myself a decent coder. I look back on old projects, thinking about what would I have done differently if given the opportunity again. I have received compliments from colleagues and peers (that I both respect and don't respect in regards to their development skill) in regards to my coding style and coding decision making process.

I have taken over an old code base for the new project on which I have begun work. This code base sucks. It easily meets the definition of cruft.

Cruft - Computing jargon for code, data, or software of poor quality.

Poor technical managers often do not realize the importance of good developers. This statement is slightly self-serving, but there's a popular misconception among managers that anyone can do. Why do some managers think this train of thought? They think this train of thought because very few challenge the idea (managers, developers, and customers alike). Software projects get complete, one way or the other and code quality gets put on the back burner. Now, if projects are being completed and they are being sold and accepted by customers, then why should a manager care about code quality?

The reason to care about code quality is productivity. As a developer who has taken over various code bases of shit code, I have run into the following problems (as a note for nomenclature, I refer to Java):

* Improper package usage - Packages, just like file system directories exist for a reason. They offer an internal structure for organizing relating code. Packages, just like databases, can be normalized, to organize code in a more specific and intuitive fashion.

Example: In a recent web development project, there was a single package for all servlets/action classes: com.project.action. There were nearly 100 servlets in the same class. No, these were not all related. They could have been organized more neatly into additional sub-packages. This doesn't even address the issue of having 100 servlets. I'll get to that later.

* Convenience methods - Convenience methods can be used for great advantage. Most of time, they are completely unnecessary. Code each class as an individual interface. An API, if you will. If a single generic method can be created to meet the interface requirements, then create a single method.

Example: getDevice(), getDevice(String), getDevice(String[]). getDevice calls getDevice(String[]) internally passing an empty array of strings. getDevice(String) calls getDevice(String[]) internally passing a array of strings with length 1. getDevice(String[]) has the actual implementation. To not confuse the calling interface, it may be simpler to just stick with one method: getDevice(String[]). This covers all cases. Again, this doesn't cover the issue of passing a String. I'll get to that later.

* Code duplication - function() { { /* code block to do one thing */ } { /* code block to do second thing */ }; The two internal code blocks are reused in this method along with 100 others. Imagine if another method needs to also use the two code blocks. Yes, then that method will also have the two code blocks. Ok, maybe that's not so bad. How about if a bug occurs in one of the code blocks and it needs to be fixed? Yes, then all 101 methods will need to be revised to fix the bug. That's bad. REFACTOR. Move the code blocks into their own methods so if a bug is to occur, then it can be fixed in one place, rather than 101 places.

Example: The previous web project I mentioned has 100+ action classes/servlets. There are groups of them that have very similar functionality. Refactor! Refactoring duplicate code will allow for easier maintainance of existing code, plus making the lives of future developers more easy when they have to add new similar features! Now, fixing code duplication doesn't always have to be resolved with code factoring. There's another possibility - object oriented programming. Use it. Love it.

* Strong typing - Java has an object oriented structure to provide custom-crafting data types. A developer can roll their own from scratch or extend from an existing code base, either the core APIs that Sun provides, their own previous code base, or third-party APIs. On top of that, Java 1.5 (Java 5.0 - I hate marketing) introduced enums. Enums are short for enumerations. They are fantastic and should be used much more often than they are in practice. Yes, but why can't a developer use some of the standard APIs that I just mentioned above. For example, it is common to pass parameters as Strings or Integers.

The reason this is bad coding practice is that, rarely, a complex parameter can be most strictly defined as a String or Integer. A String or Integer is an object wrapper for internal primitive types that more procedural C programmers would be familiar with (char[] - an array of characters otherwise known as a string and int - a primitive integer). There are additional primitive wrappers (Long, Double, Float, Short, etc.) available as well. It sometimes makes good sense to use these simple wrappers. For example, if a parameter can only be most strictly defined as an arbitrary array of characters, then perhaps it makes sense to use String.

What if the arbitrary array of characters needs to be modified? Then it may not be as good of a choice since the primitive wrapper objects are immutable (they can't be modified after constructed). This may be an added benefit if you don't want to allow object mutability. It's considered good practice in many ways to restrict the mutability of your own custom-made classes.

Now, what if the string isn't arbitrary? For example, consider the method assignTransmissionType(String type). This works, but isn't as strict as it could be. It would make sense to make an enumeration of supported transmission types (Automatic, Manual) and more strongly type the parameter -> assignTransmissionType(TransmissionType transmissionType). This makes calling interfaces more intuitive, allows for easier extensibility, and has the great benefit of not allowing calling interfaces to utilize your API in ways that you do not support.

I have more, but I've run out of steam.



Friday, November 21, 2008

Thought of the day

A thought for the day and it was not offered by me:

"good luck wrangling with shitty coders' shitty code"

Sunday, November 9, 2008

Work perceptions

I had a long post about work perceptions in response to a work meeting that occurred in the past week. Some good things are just a little too good. I'll keep working on the pithy phrases.

Monday, November 3, 2008

Questions

Tomorrow is election day.

The Massachusetts state election is following the usual standard. Present a ballot to a voter. The voter then selects a candidate or candidate grouping that he or she feels best represents their interests, thoughts, or beliefs.

I am always interested in the ballot questions. This is where the state offers questions of public policy which possibly or eventually leads to reform or lack of reform.

With that, the questions...

1. State income tax

A YES VOTE would reduce the state personal income tax rate to 2.65% for the tax year beginning on January 1, 2009, and would eliminate the tax for all tax years beginning on or after January 1, 2010.

A NO VOTE would make no change in state income tax laws.

In favor argument: "41% waste in Massachusetts state government," reveals survey. Eliminating government waste is one reason to vote "Yes."
Your "Yes" vote cuts your state income taxes 50% starting this January 1st - and eliminates the last 50% next January 1st. For you and for 3,400,000 Massachusetts workers and taxpayers.
Your "Yes" vote gives back $3,700 each to 3,400,000 Massachusetts workers and taxpayers - including you - on average when we end the state income tax. $3,700. Each worker. Every year. [Me: Receiving more money is good, but the true question is how would removal of the State income tax affect government spending on crucial vital works as well as inappropriate spending on non-vital works? I'm willing to pay taxes if it means supporting these vital areas, but I don't like paying taxes to support excess or misappropriation of public funding. Another question to ask is that if the State were given a proper spanking as punishment for misspending, would bad habits improve or be eliminated in turn? What's realistic here?]

Your "Yes" vote will create hundreds of thousands of new Massachusetts jobs. [Me: Debatable.]

Your "Yes" vote will NOT raise your property taxes NOR any other taxes. [Me: Response to fear-mongering.]

Your "Yes" vote will NOT cut, NOR require cuts, of any essential government services. [Me: I realize there is a word-limit on these supplied responses, but it is unclear as to what government services are essential and non-essential.]

Your "Yes" vote rolls back state government spending 27% - $47.3 billion to $34.7 billion - more than state government spending in 1999.

3,400,000 Massachusetts workers, taxpayers and their families need your help. Please vote "Yes." [Me: Will someone please think of the ever-present middle class??? Will someone think of the children??? I need to do more reading about this topic.]

Against argument: This legally binding initiative would slash state revenues by more than $12 billion a year - nearly 40 percent of the state budget.

It would force dramatic cuts in state aid to cities and towns, driving up property taxes and reducing funding for vital local services. [Me: Define vital local services. This seems like possibility, but the argument is more made with fear-mongering in mind. I'm curious what non-vital services and spending waste would be reduced if there was no state income tax.]

It would mean a drastic reduction in state funding for local public schools - leading to teacher layoffs, school closings and other cutbacks that would harm our children's education. [Me: We already harm out children's education through improper emphasis on rewarding teachers with proper compensation. This, again, is possibility, but also reeks of fear-mongering.]

It would threaten public safety by cutting funds for police, fire protection and emergency medical services. [Me: Again, possibility, but how much would this threaten public safety depending on the cuts?]

It would prevent us from making badly needed repairs to the state's aging roads and bridges, or making other investments needed to attract businesses and create jobs.

And it could force the state to raise other taxes and fees that would hit moderate-income families hardest.

Times are tough enough. Let's not make them worse. Vote NO. [Me: This argument, overall, is pure fear-mongering. The argument points to the main works which I agree government should take part in (city/town aid, education, public safety, and infrastructure). However, how exactly would removal of the State income tax affect these areas, and, more importantly, affect true non-vital areas?]

2. Possession of marijuana

A YES VOTE would replace the criminal penalties for possession of one ounce or less of marijuana with a new system of civil penalties.

A NO VOTE would make no change in state criminal laws concerning possession of marijuana.

In favor argument: A YES vote removes the threat of arrest, jail, loss of student loans, loss of driver's licenses, and other sanctions for possession of an ounce or less of marijuana. Instead, a $100 fine, similar to a speeding ticket, would be imposed. Question 2 would end the creation of a permanent record (CORI) and barriers to housing and employment. Police would be freed up to focus on serious crimes, rather than arresting 7,500 people annually for marijuana possession. Taxpayers would save $30 million a year in arrest costs. All other marijuana-related crimes, like sales or DUIs, remain untouched. Stricter than current law, juveniles would have their parent(s) notified and must complete a drug awareness program and community service. Question 2 would not increase marijuana use. Eleven other states have similar laws and have shown no increase in marijuana use. Let the punishment fit the crime. Vote "YES" on Question 2. [Me: Despite my lack of support for marijuana usage in general, this argument, for the most part, makes sense to me. I don't have comments.]

Against argument: Marijuana decriminalization is an endorsement of substance abuse and dangerous criminal activity, and sends the wrong message to young people. Massachusetts law already requires our judges to dismiss charges and seal records of first-time offenders. Decriminalization emboldens and enables drug dealers and poses a threat to public health and safety. One ounce of marijuana - street value $600 - equates to approximately 56 individual sales. Marijuana contains nine times the mind-altering THC as 30 years ago, is twice as carcinogenic as tobacco, is a primary factor in juvenile hospital admissions, and its users are 10 times more likely to be involved in automobile crashes. It is more strongly associated with juvenile crime than alcohol. A large percentage of criminal arrestees (approximately 40%) test positive for marijuana. Decriminalization is opposed by law enforcement, educators, health care, business and community leaders. Massachusetts District Attorneys, Sheriffs and Police Chiefs urge your NO vote. [Me: Decriminalization is indeed an endorsement of substance abuse. However, we do this already for another chemical substance -- alcohol. Calling decriminalization an impetus for dangerous criminal activity is a backwards argument since selling marijuana is an act of criminal intent because selling marijuana is illegal. I am a human being because I am a human being. Citing the increased chemical consistency, carcinogenic effects, and safety effects is good, but don't we already have these problems with cigarettes and alcohol? I'm curious how much of a percentage of arrestees would test positive for marijuana if marijuana was decriminalized, much less legalized. My guess it would go up or remain about the same. I'm not a fan of marijuana usage, but I don't like the government stepping into areas of recreational usage. This doesn't make marijuana legal, but does reduce the penalties involved with recreation usage.]

3. Dog racing

A YES VOTE would prohibit dog races on which betting or wagering occurs, effective January 1, 2010.

A NO VOTE would make no change in the laws governing dog racing.

In favor argument: Dog racing is cruel and inhumane. Would you treat your dog this way?

  • Thousands of Massachusetts greyhounds endure lives of confinement, kept for 20 or more hours each day in cages barely large enough to stand up or turn around in. [Me: Out of the thousands of dogs that live in confinement, how many total racing dogs are licensed overall? This argument is slightly misleading, but a confined dog is a confined dog. Point taken.]

  • According to state records more than 800 Massachusetts racing greyhounds have been injured since 2002, including dogs who suffered broken legs, paralysis and even death from cardiac arrest. [Me: More than 800 racing dogs have been injured out of how many dogs in how many races? This argument is fair as an injured dog due to racing is the fault of owners racing the dogs, of which the dogs have no choice in doing. I am curious in the comparison of racing injury vs. normal domestication injury.]

  • According to the Massachusetts State Racing Commission greyhounds have recently died from a mysterious illness and tested positive for cocaine, an illegal stimulant. [Me: This statement is misleading as it is not stated that the racing commission reported the dogs were given stimulants to increase their performance, although this can be guessed at. The question is if a higher percentage of dogs who are raced are abused in comparison to domesticated dogs. I am also curious as to what would happen to all these racing dogs if the law was to pass. With no betting allowed, dog racing would, for all intents and purposes, be eliminated. Would the fate of a lot of these dogs be euthenasia or domestication?]

Against argument: Parimutuel dog racing has taken place in Massachusetts for over 70 years, now only at Wonderland dog track in Revere, and Raynham/Taunton in Raynham. The greyhounds are owned by caring dog owners, not tracks. There is no mistreatment of the dogs as claimed by animal activists. The State Racing Commission fully regulates the industry, has veterinarians on duty at each track, and maintains numerous programs for the welfare of the dogs during their racing careers, and for adoption when their careers are over. About 1,000 people will lose badly needed jobs if the proposal is enacted. The Commonwealth, Revere and Raynham will lose badly needed revenue. From 2000 to 2007, these tracks paid over $40 million to the Commonwealth in commissions and fees, as well as other taxes related to their racing activities. Finally enactment will likely subject the Commonwealth to suits by the tracks for taking their property. [Me: Despite the fact that racing is popular or has been around for a long time does not an argument make. Slavery was legal for a long time in the United States. That does not make it a moral act. Losing revenue is not a legitimate argument for acting immorally. The argument that no mistreatment is claimed by animal activists is weak, although no source or statistic is claimed nor cited.]