Coded Smorgasbord: A Type of Insanity |
Types are fundamental to most programming languages. Even the loosest, duckiest type system is still a system of some kind. Its impossible to be a programmer if you dont at least have a vague understanding of what types are, what they mean, and how you use them.
Well, not impossible.
Kelly came across some C# code that needed to take the value in one variable (which may be null), and store it in the property in an object. Instead of writing the obvious statement:
someObj.SomeProperty = instanceOfAClass
Kellys predecessor wrote this:
someObj.SomeProperty = (AClass) null != null ? null : instanceOfAClass;
That conditional is a mystery: cast null to a class type, and if it somehow ceases to be null in this process, return null, otherwise return an instanceOfAClass.
That, of course, was just some copy-pasted code. Cara recently had to delve into the sewer- er, I mean plumbing- of an enterprise application. There, she found this pattern, copy-pasted everywhere:
String st_id = Integer.valueOf(rs.getString("student_id")).toString();
msgData.setSID(Integer.parseInt(st_id));
Hey, strings everybody! Strings. And integers.
We usually avoid running date-related code, because dates are the easiest thing to screw up. The venerable Falsehoods Programmers Believe About Time (Part 1, Part 2) remain a great reference for all of the ways people can screw it up. But dates are a data type, so they're on theme for this article.
My personal favorite bad-date code is when they obviously know enough to use the date-related operations and functions provided by their standard library, but still mysteriously feel the need to reinvent their own at the same time. It shows knowledge without understanding . Dominique stumbled across this:
now = datetime.now()
days_per_year = 365.24
for age in ages:
result['years'].append((now - timedelta(days=age*days_per_year)).year)
I like its attempt at handling leap years- they even recognize that the centennial years dont get leap years and drop 1/100 (of course, that only applies to centennial years divisible by 4, like 2000, but not 1900) . Of course, theyre already using the .year
property of the timedelta
object, which is a property also mirrored on date objects- they were so close, yet so far.
Комментировать | « Пред. запись — К дневнику — След. запись » | Страницы: [1] [Новые] |