[программизм] о некоторых аспектах мэйнстримового программистского мышления
прочёл вот новейшее творение Спольского, не знаю уж зачем.
как обычно: здравая общая идея и полная ферня в частностях.
перескажу одну частность.
товарищ приводит следующий пример для маленьких читателей: некая уеб-аппликация. читает строки, вводимые пользователем, сохраняет их как есть в базе данных, печатает в заискейпленном виде в HTML, the works. проблема в том, что надо как-то отличать строки, полученные от пользователя, от других строк, поскольку иди его знай, этого гадского пользователя, какого злого буратинского жабаскрипта он туда может напихать.
так вот: тривиальная, казалось бы, мысль о том, что свойство “этой строке мы доверяем” можно миллионом способов отразить в типе объекта, в мудрую голову Спольского не пришла. то есть, вообще. вместо этого мужик предлагает использовать coding conventions, диктующие определённым образом обзывать переменные.
я конечно всё понимаю, это только пример, сама статья не вполне об этом.
но тем не менее: ну Ё же ТМ, дветыщипятый год на дворе.
Оно, конечно, грустно. Но ведь мэйнстримовое мышление не сомневается, что этот тип — строка! Класс такой, public final, надо заметить.
В других тусовках static type checks гораздо моднее, и введение десятка интерфейсов только для этого никого не удивляет.
С третьей стороны, есть скриптовые языки, где вообще типы динамические…
(http://livejournal.com/users/9000)
Проверка типов - мой девиз
Имен подборка - мой каприз.
(http://livejournal.com/users/trurle)
> С третьей стороны, есть скриптовые языки, где вообще типы динамические…
в динамических типах тоже ничего ужасного нету, собственно.
важно, чтобы они хоть где-то проверялись.
то есть чтобы был хоть какой-то способ свалить эту заботу на компьютер, а не на человека.
собственно все методологии так или иначе живут не столько в инструментах, сколько у людей в голове. настоящий программист может писать на Фортране на любом языке, как известно. :)
так же и с типированием данных: это в большой степени state of mind, и на самом деле даже самые глупые языки не так уж и фатально ставят палки в колёса — лишь бы были хоть какие-то способы создавать новые абстракции.
(http://livejournal.com/users/cmm)
точно-точно.
(выпью-ка и я чего-нибудь…)
(http://livejournal.com/users/cmm)
Шаман!
Ты знал!
(http://livejournal.com/users/trurle)
бином Ньютона, прости господи. :)
(http://livejournal.com/users/cmm)
C programmers are so pathetic. They seem to still live 2 centuries before present times.
(http://livejournal.com/users/ivan_ghandhi)
настоящий программист может писать на Фортране на любом языке
Как-то двусмысленно звучит
(http://livejournal.com/users/michk)
в оригинале ¨a real programmer can write Fortran in any language”.
так лучше, видимо.
(http://livejournal.com/users/cmm)
as a C programmer (nominally), I beg to differ. :)
(http://livejournal.com/users/cmm)
О, блин. Я даже не связал. Так действительно лучше.
(http://livejournal.com/users/michk)
http://www.livejournal.com/~omerm/55178.html
Almost any feature in almost any programming lanugage embodies a compromise taken some day.
I recall having a tough week of implementing a class hierarchy in python while being thinking of it as though it was Java - and assuming that I will be able to build-up the program on top of class hierarchy. Stupid me.
(http://livejournal.com/users/omerm)
well, the writing of Fortran does need to take into account the actual underlying language. it's the patterns that make Fortran what it is, not this or that language feature.
(I lack the Python knowledge to understand your anecdote, BTW. what exactly didn't work?)
(http://livejournal.com/users/cmm)
вообще, одно другому не мешает. мне легче читать программу которая использует разумную нотацию. я был бы рад если бы все так делали. но да, надеятся только на неё неправильно.
(http://livejournal.com/users/dmierkin)
Spolsky discusses the cross-site scripting vulnerability which is a known security breach in scripting languages such as ASP, JSP and the like.
These languages do not support OOD very well. Examples used throughout the article look like ASP code, you really can not differentiate “safe” and “unsafe” strings by their property, since the string object itself does not have such property.
In order to deliver information from page to page you normally use either the Form object or Cookies. Both use the string data type which you can not change (there is no inheritance in “server-page” languages)
(http://livejournal.com/users/lake_of_fire)
The most of server-side scripting languages lack many of the features that we, as C++ programmers know and love. These would include most of the OOD practice, in particular derivation and inheritance.
Spolsky discusses the known vulnerability of the server scripting technology - the XSS. This is a very heavy issue, web-companies spend great deal of their efforts to find and eliminate such breaches in their websites.
The reason that “мысль о том, что свойство “этой строке мы доверяем” можно миллионом способов отразить в типе объекта, в мудрую голову Спольского не пришла” is simply becuase there is no such way to implement this idea in ASP / JSP (which look like the source of most of the examples given in the article).
Actually what Spolsky suggests is being recommended as best policy by most application-level security specialists (** the reason that I know all this is because a friend of mine works for a company like this).
(http://livejournal.com/users/lake_of_fire)
sorry, posted twice by error.
Gluchit moy zhzhe ne po decki :-(
(http://livejournal.com/users/lake_of_fire)
don't those pathetic languages have structs? bah.
well, if not, then structs can always be fudged by using a stringy representation (where you encode your structs in strings and use special functions to access and modify those objects), but I'll agree it's a stretch. oh wait, do those pathetic languages at least have functions?
inheritance is certainly not mandatory, anyways.
(boy, again and again I'm so glad I'm not a web programmer…)
(http://livejournal.com/users/cmm)
don't those pathetic languages have structs? bah.
Well, they do have structs and they even have “objects” (which are really nothing more than structs) but it really doesn't help much. You see, the entire ASP engine is nothing more than a few objects supported by the IIS and that have an interface for you as a programmer. Think about “java script for the server” (or a - strashno podumat'! - visual basic script, in case of ASP). So, no matter what you do, you must use the ASP “standard” objects, such as the “Request” or “Response” collections (that allow you to read/ write to and from HTML pages). You really can't use any other type but the normal string because you are dealing with two-stage operation: 1) send a page to the user and 2) receive a page from the user. There is nothing in the middle except the ASP itself.
well, if not, then structs can always be fudged by using a stringy representation (where you encode your structs in strings and use special functions to access and modify those objects), but I'll agree it's a stretch.
Yes, so can objects :-)
oh wait, do those pathetic languages at least have functions?
:-))))))))
Well, the ASP has “Subs” :-)
inheritance is certainly not mandatory, anyways.
(boy, again and again I'm so glad I'm not a web programmer…)
Me too. But I can write a decent web application if I have to :-)
(http://livejournal.com/users/lake_of_fire)
> there is no such way to implement this idea in ASP / JSP
you can express types (semantic types, that is, not physical types) in any language which lets you define functions.
this is the conceptual leap most modern programmers just never make, for some reason: a type doesn't have to encode only physical properties (i.e. stuff like “this here thingy looks in memory like an array of bytes terminated by a null byte”); types can (and should) encode semantic properties — stuff you know about your objects but cannot express on the “physical” level, like “unsafe object” or “HTML-escaped string”. and in a language that doesn't let you define your own physical data structures, you can enforce your own type discipline by encoding stuff in strings/int arrays/whatever and check the types at runtime. all you need is discipline and a habit of thinking in a language which is more expressive than the one you have to use. lack of compile-time typechecking is not at all a big deal: just witness the hordes of happy Perl and Python programmers.
I'm not sure where the popular and quite irrelevant obsession with derivation and inheritance comes from. must be C++. :)
(http://livejournal.com/users/cmm)
> You really can't use any other type but the normal string because you are dealing with two-stage operation: 1) send a page to the user and 2) receive a page from the user. There is nothing in the middle except the ASP itself.
but the ASP is your code, is it not? if so, what prevents you from separating your application logic from the actual input/output in any way you see fit?
(but I really know nothing whatsoever about this ASP stuff, so quite possibly I'm talking crap…)
(http://livejournal.com/users/cmm)
never mind, comments don't seem to arrive by email lately anyway :)
(http://livejournal.com/users/cmm)
but the ASP is your code, is it not?
Zeu, she lo.
As I said before, the ASP is a set of internal server objects which I call in my code.
if so, what prevents you from separating your application logic from the actual input/output in any way you see fit?
:-)))))
In asp/jsp separating logic from input/output is impossible. Not difficult, not quirky, just impossible :-)
Regards
(http://livejournal.com/users/lake_of_fire)
oh well, the so-called “frameworks” are a problem.
when the revolution comes, those who publish functionality as a “framework” where a library would suffice will be the first against the wall!
(http://livejournal.com/users/cmm)
now that I think about it: if you have to work by calling predefined server-side stuff, then presumably there no room for the variable-naming convention games either, now is there?
(http://livejournal.com/users/cmm)
this is the conceptual leap most modern programmers just never make, for some reason: a type doesn't have to encode only physical properties (i.e. stuff like “this here thingy looks in memory like an array of bytes terminated by a null byte”); types can (and should) encode semantic properties — stuff you know about your objects but cannot express on the “physical” level, like “unsafe object” or “HTML-escaped string”.
Eeee… I don't think that you are right. If that was so, nobody would have used structs nor would have known to apply OOD correctly.
I'm not sure where the popular and quite irrelevant obsession with derivation and inheritance comes from. must be C++. :)
I don't know why the word “obsession” was used by you in this context. Personally I am not obsessed with derivation. Maybe aggregation. But I digress.
The entire idea behind objected driven design is just like you said - semantically encoding different types of data in your programs and provide means to facilitate communications to and from these types of data. The only product I have known that provides a full practical implementation of this idea is a C++ compiler.
In order to achieve this goal (at least theoretically) in a program, one needs the tool to meet certain criteria and allow to do certain things. If your tool supports only strings and integers - you really can not “make the conceptual leap”.
Perhaps you need to know moreabout server side scripting languages and I need to know more about Perl / Python to make this discussion more fruitful.
Sincerely yours,
Gila
(http://livejournal.com/users/lake_of_fire)
O Da! Da!
Dustom ix, dustom! Kalenym zhelezom! ))))
(http://livejournal.com/users/lake_of_fire)
Why?
You call a method of the server side object “Request”. This method returns a string. You have to store the result somewhere. You store it in a variable. The variable has a name. You define that name. The author suggests that when defining names, you use a certain naming convention so that when reviewing and maintaining the code everybody knows which HTML should be encoded and which isn't :-)
(http://livejournal.com/users/lake_of_fire)
> I don't think that you are right.
of course I am right.
in fact, I'm infallible!
in this case, the point wasn't “people don't use structs”. the point was “people don't use structs when there is a built-in type {or a preexisting struct or class, for that matter) that is capable of representing the raw physical information needed”. or, more generally, people don't realize that type checking is there to help them, not to punish them.
> to apply OOD correctly.
it is impossible to practice a religion “correctly”, because correctness is a scientific idea. though you can certainly practice a religion effectively, productively and in many cases even enjoy the process.
> The entire idea behind objected driven design is just like you said - semantically encoding different types of data in your programs and provide means to facilitate communications to and from these types of data. The only product I have known that provides a full practical implementation of this idea is a C++ compiler.
uh. well, nevermind, I won't open that pandora's box here.
let's just quite one Alan Key: “I've invented the term 'object-oriented', and C++ is not it”.
> In order to achieve this goal (at least theoretically) in a program, one needs the tool to meet certain criteria and allow to do certain things. If your tool supports only strings and integers - you really can not “make the conceptual leap”.
“really can't” is obviously too strong. perhaps “find it highly impractical”.
then again, if one's thinking is rigidly constrained by the vocabulary of the specific tool, one has a problem.
on the practical side, many people use smart languages to generate programs in stupid ones.
(http://livejournal.com/users/cmm)
> This method returns a string. You have to store the result somewhere. You store it in a variable. The variable has a name. You define that name.
there! this storing process, how does it look?
if it looks like this (pseudo-code):
, then what's stopping you from writing this:
?
I must be still missing the real horror of ASP, I guess.
(http://livejournal.com/users/cmm)
Спольский - раскрученный зануда, возомнивший себя проповедником software engineering-а
отмазка: мне тож приходят уведомления о его новых статьях, сам не помню на какой имейл и когда подписался, однако-ж с собственному изумлению иногда читаю
(http://livejournal.com/users/brumka)
да ладно тебе, вполне живенько чувак пишет. :)
(http://livejournal.com/users/cmm)