or should one always act according to the rule that "you never know who or what will end up using this code and how"
This leads to paranoia. Like security.
You can go mad and protect everything from possible (but improbable) threats and spend an insane amount of resources on it... And yet, you won't be able (ever) to protect the code from human stupidity or ignorance.
Doesn't matter how much effort you put into this, it will take me a day to pervert or bypass it if I want. I can convince my PM that, against all claims, this time was necessary for us to meet the deadlines. It's "temporary" and we'll get (cough) rid of later (cough).1
So no, appealing the common sense won't work.
However, it could come in quite handy to break this rule and define for example my SELECT statements like so and use it for all my tables:
If you look for ways to ignore and bypass best practices you will find many. These are solutions that fall into the group I call happy ideas. Everyone has one and everyone can make them work. Sometimes are good, sometimes are ... well, let's just stop here.
But, just because something is possible doesn't mean you have to do it. As I said, it will take only a couple of minutes to copy SelectAll
, make the template more complex and insecure and elaborate on my reasons. At some point, I could succeed at doing this and I will leave an open window to doubtful but accepted practices.
Would it, therefore, be acceptable to write code like the above
It depends on whether you can afford the trade-offs, or in this case, the risks. Risks, like security, are measured and managed proportionally to the threat they represent. How probable they are, how often and for how long we are exposed to them, etc. So, you are asking the wrong audience.
If you take measures to mitigate the risks, then it's "acceptable". But don't lie to yourself. Like @Ewan suggested, things can shift quickly and lead you to unexpected situations if you are not cautious about measuring the risks.
If you don't have enough experience on this subject, I would suggest implementing a well-known solution that allows you to do it in the safest way possible and is future-proof.
1: You can't imagine how fast projects embrace the normalization of deviance. Add then the fact that code, as evolves, is prone to get worse, not to get better.
"SELECT * from X where A = " + unsanitizedUserInput
is ok (and it is very, very, very not OK).typeof(T)?.Name
(with the rules for sql identifiers, not the rules for sql literals)