Estaba en mi cuarto, acostado en mi cama, llorando (figuradamente) y quejándome de mi pereza y vagancia, por tener algunos inventos que quiero hacer y no tener suficiente motivación, y preferir mejor descansar mi mente lo más que pueda, ya que es más beneficioso invertir mis energías en un trabajo útil que genere divisas, que en un pasatiempo inútil que sólo yo entenderé y usaré… ¿Verdad? ¿Cierto? ¿O no?
Hay un hobbie que de vez en cuando viene a mi vida, y es el de resolver problemas con algoritmos matemáticos y/o computacionales que surgen en forma de retos. Mis fuentes favoritas de este tipo de retos son CodingBat, SPOJ, TopCoder y Project Euler. Cada problema permanece en mi cabeza por mucho tiempo y eso me gusta, aunque últimamente TopCoder se ha encargado de desilucionarme con eso de resolverlos en menos de una hora. ¿Cómo pretendo yo querer resolver cada uno de los algoritmos que desconozco en la forma más óptima posible, y en menos de una hora?
Pero estas no son las únicas fuentes de retos. Existen personas que apuestan y confían en mis habilidades. A esas personas les agradezco de corazón. Aunque, de vez en cuando aparecen algunos que indirectamente se aprovechan de ellas, pero de estas personas sólo un reducido grupo logra dejar en mi mente un algoritmo que resolver, y en mi corazón un deseo quemante de resolverlo. Y en esta ocasión, una persona me comentó sobre un problema particular. Específicamente del problema, diré que está relacionado con encontrar la ruta más corta entre nodos. Pero lo que en realidad quiero dejar claro es que la sensación de querer resolverlo me motivó a pensar en muchas cosas, como hacer mi versión de un juego famoso sólo para entender un poco la física en sus elementos, y llevar una especie de bitácora de lo que quiero o voy a desarrollar. Esa sensación de motivación fue lo suficientemente grande como para motivarme a escribir todo esto.
Suficiente de escribir. Ahora a pensar un poco en este hobbie de cómo optimizar mi versión de este cálculo de ruta corta entre nodos.
Mostrando entradas con la etiqueta Programming. Mostrar todas las entradas
Mostrando entradas con la etiqueta Programming. Mostrar todas las entradas
sábado, 9 de junio de 2012
lunes, 27 de septiembre de 2010
Recursion
Twisting. A new way to think and analyze algorithms. Its structure seems that can be exploitable with multicore systems, excepting of course the size of stacks... In essence, Recursion is a function that calls itself until certain condition is met. And this simple essence is still twisting...
You can define a function as:
The 'Hello, World!' of recursion, Factorial:
-------
What follows now is a curiosity I found in Python.
I coded a solution for the previous backtrack recursion in CodingBat by using loops and binary numbers. That solution is good for an amount of elements less than 32 (int) or 64 (long) . Python has "unlimited" integers, so I tested if I can create an integer with a googol of bits and typed:
a = 1<<(10**100)
OverflowError: long int too large to convert to int
Experimenting with previous expression, I assume the limit is:
a = 1 << ((1 << 31) - 1)
print a
OverflowError: long is too large to format
This means 2,147,483,648 (more than two thousand millions) elements, an amount still lower than the amount of people in Earth; Although, in terms of integers, with 64 elements (bits), you can express a number like 9, 223,372, 036,854, 775,808 (more than nine trillions), a number good enough for some kind of accounting.
Python can't format and print (1 << ((1 << 31) - 1)), but at least we can know how many digits it has:
import math
math.log10(1 << ((1 << 31) - 1))
646456992.94488049
The number we can express in Python has 646,456,993 (more than six hundred millions) digits! But we can't print it. That number in ASCII string will weight 617MB. The same number in binary storage should weight 256MB, but it seems Python has something like Computational Notation to store binary strings (analogous to Scientific Notation), because it handles these calculations very well.
Bit: data? instruction? element? state? number? group?
You can define a function as:
function hola() {
echo "hola!";
}To make hola() recursive, we need to call hola() inside hola():function hola() {
echo "hola!";
hola();
}But if we execute hola() right now, it will execute forever! We still need some condition that stops that infinite recursion:function hola($n) {
if($n<=0) return;
echo "hola!";
hola($n-1);
}And then, a recursive function was born. This is a completely too big jump away from sequential programming! Just try to solve factorial, fibonacci, quicksort and backtracking by using loops only, and compare them with their recursive counterparts... Twisting!The 'Hello, World!' of recursion, Factorial:
function fact($n){
if($n<=1) return $n;
return $n * fact($n-1);
}Right after factorial, the next example is Fibonacci:function fibo($n){
if($n<1) return 0;
if($n==1) return 1;
return fibo($n-1) + fibo($n-2);
}Fibonacci recursion still twists me, just like any QuickSort algorithm:function qs($list){
if(count($list)<2) return $list;
$less=array();
$more=array()
$pivot=$list[(int) (count($list)/2)];
foreach($list as $e){
if($e<$pivot) $less[]=$e;
else $more[]=$e;
}
return array_merge( qs($less), qs($more) );
}And, if that was not enough twist, there's also a Backtracking recursive algorithm! You can look an example of it at CodingBat, using Java. Backtracking is useful for solving problems similar to Knapsack and Eight Queens puzzles. function backtracking($start, $charArray, $counter = ""){
if($start >= count($charArray)) return;
echo $counter, $charArray[$start], '<br />';
backtracking($start + 1, $charArray, $counter);
backtracking($start + 1, $charArray,
$counter . $charArray[$start]);
}
backtracking(0, array("A","B","C","D"));I am starting to think that recursion (or at least my knowledge of recursion) is still in diapers.-------
What follows now is a curiosity I found in Python.
I coded a solution for the previous backtrack recursion in CodingBat by using loops and binary numbers. That solution is good for an amount of elements less than 32 (int) or 64 (long) . Python has "unlimited" integers, so I tested if I can create an integer with a googol of bits and typed:
a = 1<<(10**100)
OverflowError: long int too large to convert to int
Experimenting with previous expression, I assume the limit is:
a = 1 << ((1 << 31) - 1)
print a
OverflowError: long is too large to format
This means 2,147,483,648 (more than two thousand millions) elements, an amount still lower than the amount of people in Earth; Although, in terms of integers, with 64 elements (bits), you can express a number like 9, 223,372, 036,854, 775,808 (more than nine trillions), a number good enough for some kind of accounting.
Python can't format and print (1 << ((1 << 31) - 1)), but at least we can know how many digits it has:
import math
math.log10(1 << ((1 << 31) - 1))
646456992.94488049
The number we can express in Python has 646,456,993 (more than six hundred millions) digits! But we can't print it. That number in ASCII string will weight 617MB. The same number in binary storage should weight 256MB, but it seems Python has something like Computational Notation to store binary strings (analogous to Scientific Notation), because it handles these calculations very well.
Bit: data? instruction? element? state? number? group?
sábado, 18 de septiembre de 2010
My praise for Python language
Disclaimer: PHP is my main scripting tool. I still prefer PHP for things related to HTML. Python threads looks like a total copy from Java's, but some concepts of Python have me dreaming too much...
I like when languages focus on both, problems and users. There are still many other common problems that bothers developers everyday, but I like like when solutions go towards freedom, instead of going towards constraints (although the world itself is a constraint).
Don't you find it rude to use Eclipse, NetBeans, VisualStudio or Zend Studio on EVERY computer you will ever use, only to check the a method's syntax? Programming environments should be cheaper and lighter... nevertheless, these comments looks contradictory...
When you unify several complex concepts into simple principles, you feel a surge of freedom in your brain, head, body, self, ... well, whatever you choose. Well, that's what I felt when I discovered that I can slice arrays the same way I slice strings.
I like when languages focus on both, problems and users. There are still many other common problems that bothers developers everyday, but I like like when solutions go towards freedom, instead of going towards constraints (although the world itself is a constraint).
Don't you find it rude to use Eclipse, NetBeans, VisualStudio or Zend Studio on EVERY computer you will ever use, only to check the a method's syntax? Programming environments should be cheaper and lighter... nevertheless, these comments looks contradictory...
When you unify several complex concepts into simple principles, you feel a surge of freedom in your brain, head, body, self, ... well, whatever you choose. Well, that's what I felt when I discovered that I can slice arrays the same way I slice strings.
- If you have no text editor for coding, it brings Python GUI and a prompt to make tests.
- It forces you to tabulate your code, which makes code looks nicer
- Nested block delimiters reduced: neither {...} nor begin...end
- help() and dir() functions: pass any object as a parameter and look.
- The way you can access your own packages and modules
- Built-in: highest integer number you can express is limited only by your computer
- Built-in: complex number calculations (2+3i)
- Its slicing system for arrays and string, for example: "python"[1:5:2]
- dict.items() and enumerate(array)
- Integer division for floating point numbers, without casting
- You can use named parameters, for example: print my_page(head='Hello', foot='Bye');
- Its flexible object definitions. It looks more flexible than JavaScript definitions.
- Lambda
- Jython and binaries
martes, 14 de septiembre de 2010
Transforming If Conditions
I feel that breaking logic operations into several 'if' statements are easy to read and follow. But, from time to time I want to transpose them from single 'if' statement to multiple 'ifs' and vice versa. These are some patterns I use.
if(a==1) {
if(b==2{
f1();
}
}
/*AND*/ if (a==1 && b==2) { f1(); }
It looks a nice way to decompose a 'conjunction' (and); but it's not so well with 'disjunction' (or):
if(a==1) { f1(); }
if(b==2) { f1(); }
/*OR*/ if (a==1 || b==2) { f1(); }
But, if you have different conditions that execute the same statements, it's nice to know that you can join them with 'or'.
And now, there's one that annoyed me way too much, the empty 'if' block.
if(a==1) { /*nothing*/ }
else { f1(); }
/*NOT*/ if ( !(a==1) ) { f1(); }
I can remove that 'empty' block by negating the condition; but that extra parenthesis in NOT example looks odd. We can erase it by inverting that condition to:
if (a!=1) { f1(); }
And now, some other inversions of boolean operators:
if(a > b) ... if( !(a <= b) )
if(a >= b) ... if( !(a < b) )
if(a != b) ... if( !(a == b) )
It's fun to see that, if a number is not greater than another, it can, not be only lesser, but also equal; and that, if a number is neither less nor equal than another, then it's greater. Never forget the equal when inverting a less-than and greater-than operators.
Now I understand why the word NOT is never used in boolean variables. Which API method looks good: is_not_good() or !is_good()? Sorry for english language! ;-P
¿NOT is good? -vs- ¿NO está bien?
if(a==1) {
if(b==2{
f1();
}
}
/*AND*/ if (a==1 && b==2) { f1(); }
It looks a nice way to decompose a 'conjunction' (and); but it's not so well with 'disjunction' (or):
if(a==1) { f1(); }
if(b==2) { f1(); }
/*OR*/ if (a==1 || b==2) { f1(); }
But, if you have different conditions that execute the same statements, it's nice to know that you can join them with 'or'.
And now, there's one that annoyed me way too much, the empty 'if' block.
if(a==1) { /*nothing*/ }
else { f1(); }
/*NOT*/ if ( !(a==1) ) { f1(); }
I can remove that 'empty' block by negating the condition; but that extra parenthesis in NOT example looks odd. We can erase it by inverting that condition to:
if (a!=1) { f1(); }
And now, some other inversions of boolean operators:
if(a > b) ... if( !(a <= b) )
if(a >= b) ... if( !(a < b) )
if(a != b) ... if( !(a == b) )
It's fun to see that, if a number is not greater than another, it can, not be only lesser, but also equal; and that, if a number is neither less nor equal than another, then it's greater. Never forget the equal when inverting a less-than and greater-than operators.
Now I understand why the word NOT is never used in boolean variables. Which API method looks good: is_not_good() or !is_good()? Sorry for english language! ;-P
¿NOT is good? -vs- ¿NO está bien?
domingo, 12 de septiembre de 2010
Validation Overkill
"The price of reliability is the pursuit of the utmost simplicity. It is a price which the very rich find most hard to pay."
Sir Antony "Tony" Hoare, 1980
People keep inventing new ways of validation, and that's really good! The problem is when they want them all in the whole same form!
[This link] provides an example I have elaborated about what I have called "Validation Overkill."
I will list some overkill principles:
Javascript problems: visibility, library size, duplication of validation code, excesive AJAX
Sir Antony "Tony" Hoare, 1980
People keep inventing new ways of validation, and that's really good! The problem is when they want them all in the whole same form!
[This link] provides an example I have elaborated about what I have called "Validation Overkill."
I will list some overkill principles:
- State validation constraints, before, while and after:
before: by using a label, and description of the time of data and its formatting
while: show errors while typing data, or when changing focus, with Javascript or AJAX
after: it's normal that back-end rejects wrong data - Indicate validation errors. It's normally done by adding a red color to a data field
- List a summary of errors with anchor links to data fields, normally at the top of the form.
- Retell errors, just like the while part of validation constraints.
Javascript problems: visibility, library size, duplication of validation code, excesive AJAX
- Javascript code is visible
- if libraries are big, they will take time to be downloaded
- sometimes it's needed to validate twice: front-end and back-end
- excessive ajax requests can kill bandwidth
- If your user base is big, it will be a load for your server
- AJAX is a process running on back-end, not in the browser.
- You would like to squeeze the total capability of the machine, but
- sometimes to pay for a CPU upgrade, or
- to buy an extra CPU to use as replication could be a faster way to solve latency
- because all these rules are present in every field of an input form,
- and specially if those fields are required
miércoles, 18 de agosto de 2010
Function's Name, Code and Usage Relationship
To show how important the relation between a function's name, code and usage is, let me show you this silly example using Python:
What can you see? It's fun to see how function name says one thing, and its implementation says another.
Conventions are important. It should be clear by reading any part of the code.
In validation functions, there are two possible values. True and False. Although you can choose to return the one you like the most, when you want to say that a validation has_failed or has_passed, it "should" be clear what value to use, shouldn't it? ...
Actions (or processes) should be according with names. Names should be chosen according to actions. "What you say should be backed-up with what you do." "Things you do speak louder than things you name."
Comparing this with Positivism, I like how inspiring messages are written, although they don't promote planning.
#300-private
#Look this valid function definition:(You can download previous code in this link. Double-click to run it.)
def are_different(a,b):return a==b
#This line looks nice. They are different:
if are_different(1,2):print "1 & 2 are different!"else:print "Houston: we have a problem!"#Huh? Where is the mistake?
raw_input("Press [ENTER] key...")
What can you see? It's fun to see how function name says one thing, and its implementation says another.
Conventions are important. It should be clear by reading any part of the code.
In validation functions, there are two possible values. True and False. Although you can choose to return the one you like the most, when you want to say that a validation has_failed or has_passed, it "should" be clear what value to use, shouldn't it? ...
Actions (or processes) should be according with names. Names should be chosen according to actions. "What you say should be backed-up with what you do." "Things you do speak louder than things you name."
Comparing this with Positivism, I like how inspiring messages are written, although they don't promote planning.
#300-private
martes, 17 de agosto de 2010
What Programming Languages contribute
Each programming language should contribute something new to the programming world, like some kind of new element to the structure of a program, to name a example. An inconvenient I have is that I still see sequential solutions easier to find than a structured ones.
My programming rabbit hole started when I was 14, with slight touches toMS-DOS command prompt. Then I lightly met FoxPro, then COBOL, until I hit Turbo Basic.
I learned that Assembly Language existed, the one I consider the genesis of imperative programming language style. When you notice that Assembler is essentially data movement and comparison, it's hard to imagine something like Warcraft coded in this language. Some time ago I learned that programs are based in a theoretical Turing Machine.
When I saw function and sub statements in QBASIC and the list of commands of the Help, I knew that something different was comming. Something called procedural or structured programming. In college, I saw DBASE III Plus (which I compared with FoxPro), Turbo Pascal and Borland C. I saw in the last two some resemblances to QBASIC, but declaring variables and importing libraries where something new to me.
In the university I learned what was the real importance of C and Pascal, why GOTO is evil, complex typedef struct, and recursion, that by itself was something too abstract for me, not to mention the fact that it's needed for some sorting algorithms (also abstract) like Quick Sort. I wish I had met SmallTalk and LISP at this time... I feel power and flexibility in LISP, but I still neither understand it, nor its macros.
In 1995, the first language I saw after QBASIC was HTML, but I didn't see some statements (no conditions, no loops, no variables). So HTML was not programming language for me, and I rejected it until I learned about JavaScript. Something interesting that I learned with JavaScript is that you can "store" function definitions in variables, but later I learned that what gets stored is a reference, and that C allowed this kind of assigment. About JavaScript events, I heard of the event concept with Visual Basic (QBASIC successor) and Delphi (Pascal's).
OOP... What a headache!! I was doing a lot of HTML, CSS, JavaScript and PHP, before I learned about OOP and Java. I saw C++ before, but I never saw something about Object-Oriented Programming on it. I learned that SmallTalk was an older OOP language than Java. Inheritance, abstraction, polymorphism, encapsulation, imports (I took them like includes, but later I learned that they are namespaces!), collections, threads, bytecodes, and patterns: all of these were part of the tsunami that Java was for me. Some interesting things that I tested with Java for Eclipse were Test-Driven Development and Source Navigation (like navigation in Internet)
If something was difficult after starting to learn Java, it was to learn CakePHP and the concept of MVC Frameworks. It's nice to jail a group of developers into conventions, but the problem is when the framework doesn't provide what you need in a way that is easy, accesible and well documented.
A problem I get with JavaScript is when I want to access some local variable, inside a function called from another function. In C# there is something called closures, designed to avoid this kind of problems.
I wanted to experiment something new, so I looked into Ruby, and then Python. I choose Python because of how it does things and it tends toward procedural and imperative styles easier. Not to mention Python IDLE. What I discovered is that code blocks are delimited by tabs or spaces, but the flexibility of its dynamic typing was a good pay-off for me. I later knew that FORTRAN was also space-delimited for code blocks. Python use import for namespaces, but here, they are are real plus!
The first time I heard the term lambda was when I learned what is the Haskell language. This is a concept vaguely experimented by me, but it's a pending one.
ASSEMBLY speed never will be 100% matched by compiled languages, but his drawback is his bad programming productivity.
FORTRAN was the most used language for Math.
LISP seems so flexible and so abstract that it looks boring.
C focus on Implementations to increase Portability.
SmallTalk was the first famous OOP language.
Now we have Haskell, Scripting Languages, C++ and Java. It seems like including several new libraries and constraints, and also change the semantics of old languages. But how could you use the power of LISP without never ever using parenthesis? or fixed-width? or brackets? or tabs? or begin/end blocks? If you can solve the problem of Hierarchy of Operators without using any of these block delimiters, please show me that novell discovery! But not bring another one.
Now, I think that the next step would be a language that could abstract or force segregation of the many individual areas of a program in a meaningful way. MVC Frameworks are a great example, but not wide and crystal-clear enough. I think that OOP is for Programming the same that Calculus is for Math.
There are things like SSH and HTTPS that are standard and globally "accepted". So, why can't some essential authentication structures come by default in some languages, just the same objects like System, String, Math, Thread, etc. exist?
My programming rabbit hole started when I was 14, with slight touches toMS-DOS command prompt. Then I lightly met FoxPro, then COBOL, until I hit Turbo Basic.
I learned that Assembly Language existed, the one I consider the genesis of imperative programming language style. When you notice that Assembler is essentially data movement and comparison, it's hard to imagine something like Warcraft coded in this language. Some time ago I learned that programs are based in a theoretical Turing Machine.
When I saw function and sub statements in QBASIC and the list of commands of the Help, I knew that something different was comming. Something called procedural or structured programming. In college, I saw DBASE III Plus (which I compared with FoxPro), Turbo Pascal and Borland C. I saw in the last two some resemblances to QBASIC, but declaring variables and importing libraries where something new to me.
In the university I learned what was the real importance of C and Pascal, why GOTO is evil, complex typedef struct, and recursion, that by itself was something too abstract for me, not to mention the fact that it's needed for some sorting algorithms (also abstract) like Quick Sort. I wish I had met SmallTalk and LISP at this time... I feel power and flexibility in LISP, but I still neither understand it, nor its macros.
In 1995, the first language I saw after QBASIC was HTML, but I didn't see some statements (no conditions, no loops, no variables). So HTML was not programming language for me, and I rejected it until I learned about JavaScript. Something interesting that I learned with JavaScript is that you can "store" function definitions in variables, but later I learned that what gets stored is a reference, and that C allowed this kind of assigment. About JavaScript events, I heard of the event concept with Visual Basic (QBASIC successor) and Delphi (Pascal's).
OOP... What a headache!! I was doing a lot of HTML, CSS, JavaScript and PHP, before I learned about OOP and Java. I saw C++ before, but I never saw something about Object-Oriented Programming on it. I learned that SmallTalk was an older OOP language than Java. Inheritance, abstraction, polymorphism, encapsulation, imports (I took them like includes, but later I learned that they are namespaces!), collections, threads, bytecodes, and patterns: all of these were part of the tsunami that Java was for me. Some interesting things that I tested with Java for Eclipse were Test-Driven Development and Source Navigation (like navigation in Internet)
If something was difficult after starting to learn Java, it was to learn CakePHP and the concept of MVC Frameworks. It's nice to jail a group of developers into conventions, but the problem is when the framework doesn't provide what you need in a way that is easy, accesible and well documented.
A problem I get with JavaScript is when I want to access some local variable, inside a function called from another function. In C# there is something called closures, designed to avoid this kind of problems.
I wanted to experiment something new, so I looked into Ruby, and then Python. I choose Python because of how it does things and it tends toward procedural and imperative styles easier. Not to mention Python IDLE. What I discovered is that code blocks are delimited by tabs or spaces, but the flexibility of its dynamic typing was a good pay-off for me. I later knew that FORTRAN was also space-delimited for code blocks. Python use import for namespaces, but here, they are are real plus!
The first time I heard the term lambda was when I learned what is the Haskell language. This is a concept vaguely experimented by me, but it's a pending one.
ASSEMBLY speed never will be 100% matched by compiled languages, but his drawback is his bad programming productivity.
FORTRAN was the most used language for Math.
LISP seems so flexible and so abstract that it looks boring.
C focus on Implementations to increase Portability.
SmallTalk was the first famous OOP language.
Now we have Haskell, Scripting Languages, C++ and Java. It seems like including several new libraries and constraints, and also change the semantics of old languages. But how could you use the power of LISP without never ever using parenthesis? or fixed-width? or brackets? or tabs? or begin/end blocks? If you can solve the problem of Hierarchy of Operators without using any of these block delimiters, please show me that novell discovery! But not bring another one.
Now, I think that the next step would be a language that could abstract or force segregation of the many individual areas of a program in a meaningful way. MVC Frameworks are a great example, but not wide and crystal-clear enough. I think that OOP is for Programming the same that Calculus is for Math.
There are things like SSH and HTTPS that are standard and globally "accepted". So, why can't some essential authentication structures come by default in some languages, just the same objects like System, String, Math, Thread, etc. exist?
jueves, 5 de agosto de 2010
Extra Comma
Middle-Square Method vs. Linear Congruential Generator. Two methods for generating random numbers... TIMTOWTDI.
A friend of mine (Puntiel) and I were analyzing a common problem that I have named "Extra Comma". When you elaborate a query to insert several records at once, each input should be separated with comma, except either the first or the last one.
A similar problem also is presented when you should separate several web links with the pipe character '|'.
I think the best way to do this is by using a flag boolean to indicate if it's either the first or the last data, but its easier to indicate the first data.
Although I believe that's the ideal way, I don't like how it looks. So, I modified it a little bit.
I chose this one because I didn't find that comma re-assignation as expensive, and also it's easier to read. But my friend prefer this method:
He says that his method is faster than mine. It could be true, because we are not benchmarking anything. But I don't believe that 'substr' is faster than:
TIMTOWTDI ("Tim Toady") as you can see. When performance is an issue, these trivialities become important. But, only a benchmarking for both, processes and network, shows when those modifications gives us a real gain.
A friend of mine (Puntiel) and I were analyzing a common problem that I have named "Extra Comma". When you elaborate a query to insert several records at once, each input should be separated with comma, except either the first or the last one.
A similar problem also is presented when you should separate several web links with the pipe character '|'.
I think the best way to do this is by using a flag boolean to indicate if it's either the first or the last data, but its easier to indicate the first data.
$isFirstTime = true;
$comma="";
while($data = get_value($rst)) {
$output .= "{$comma} '{$data}'";
if($isFirstTime) {
$comma = ",";
$isFirstTime = false;
}
}
Although I believe that's the ideal way, I don't like how it looks. So, I modified it a little bit.
$comma="";
while($data = get_value($rst)) {
$output .= "{$comma} '{$data}'";
$comma = ",";
}
I chose this one because I didn't find that comma re-assignation as expensive, and also it's easier to read. But my friend prefer this method:
while($data = get_value($rst)) {
$output .= ", '{$data}'";
}
$output = substr($output, 1);
He says that his method is faster than mine. It could be true, because we are not benchmarking anything. But I don't believe that 'substr' is faster than:
while($data = get_value($rst)) {
$output .= ", '{$data}'";
}
$output[0]='';
TIMTOWTDI ("Tim Toady") as you can see. When performance is an issue, these trivialities become important. But, only a benchmarking for both, processes and network, shows when those modifications gives us a real gain.
viernes, 30 de julio de 2010
Genius + Brute Force = Ingenious
These two statements have been branded with fire in my mind:
Donald Knuth invented algorithms for pseudo-random number generation.
Edsger Dijkstra stated that there are two approaches to solve computer problems: Mozart Vs. Beethoven. (As a curious fact, Mozart and Beethoven met each other in 1787) The former is a genius, but the latter works by brute force.
In India, Pachisi and Chaturanga were played with Dice. Orthodox Chess can be also played with dice, but Chess isn't normally played that way. The praise of what is random have been lost.
In Watchmen movie, Dr. Manhattan talks about the "Pleasure of Randomness" If there's an origin for that phrase, I'd like to find it out. Also, some levels of randomness are required to produce Fine Arts.
To try to get in touch with that "Pleasure of Randomness", I decided to create a little program that generated three numbers between zero and one-hundred inclusive. Then, I will use only the first two numbers and some operations to generate a result equal to the third number. For example, if those three numbers where {2, 3, 6}, then (2+3)+(3-2)=6. Of course that 2*3=6, but what would you do if numbers were {53, 92, 59}? This is what I did, using Python IDLE:
This simple game taught me some lessons:
---
20100729T0948:
round a problem many times
look for hindrances, obstacles, inconveniences
re-round each found obstacle and find inner obstacles
until one obstacle is solved
then, that solution will solve another
and so, like a domino effect,
the first and original problem
starts to get solved
- [id, status, created, modified, position, modcount]
20100729T1125:
writing undefined sentences to describe the problem
making calculations with parameters to find a result
opening many files to understand and solve the code
20100729T1143:
TDD to automate tests "seems" the way to go.
GUI needs to be scriptable, and HTML allows this.
Maybe JavaScript could be a problem, but if you could
append a [SCRIPT] tag and run it, it will be no problem
Enterprise, Human Resources, People and Wars:
- If you kill people, you must find and train new ones.
- If you forgive people, they will squeeze you.
- Genius find a solution instantly
- Brute Force searches for a needle in a haystack
Donald Knuth invented algorithms for pseudo-random number generation.
Edsger Dijkstra stated that there are two approaches to solve computer problems: Mozart Vs. Beethoven. (As a curious fact, Mozart and Beethoven met each other in 1787) The former is a genius, but the latter works by brute force.
In India, Pachisi and Chaturanga were played with Dice. Orthodox Chess can be also played with dice, but Chess isn't normally played that way. The praise of what is random have been lost.
In Watchmen movie, Dr. Manhattan talks about the "Pleasure of Randomness" If there's an origin for that phrase, I'd like to find it out. Also, some levels of randomness are required to produce Fine Arts.
To try to get in touch with that "Pleasure of Randomness", I decided to create a little program that generated three numbers between zero and one-hundred inclusive. Then, I will use only the first two numbers and some operations to generate a result equal to the third number. For example, if those three numbers where {2, 3, 6}, then (2+3)+(3-2)=6. Of course that 2*3=6, but what would you do if numbers were {53, 92, 59}? This is what I did, using Python IDLE:
## OUR THREE RANDOM NUMBERS
a=53 ; b=92 ; c=59 ;
## EXPLORING NUMBERS
92-53 = 39 (b-a)Looking at this simplification, some questions pops out from my mind: Would a genius had gotten an equation like this from the start? Would have a genius known that a solution found using this method could be simplified without even trying to solve one problem in the first place? I don't know, but I'm sure I'm not a genius.
53-39 = 14 a-(b-a)
39-14 = 25 (b-a)-(a-(b-a))
25-14 = 11 (b-a)-(a-(b-a)) - (a-(b-a)) //???
92-11-11-11 = 59 //MAGIC!
b \
-((b-a)-(a-(b-a))-(a-(b-a))) \
-((b-a)-(a-(b-a))-(a-(b-a))) \
-((b-a)-(a-(b-a))-(a-(b-a))) \
== c
## SIMPLIFICATION
>>> ((b-a)-(a-(b-a))-(a-(b-a)))
11
>>> ((b-a)-(a-b+a)-(a-(b-a)))
11
>>> (b-a-a+b-a-(a-(b-a)))
11
>>> (b-a-a+b-a-(a-b+a))
11
>>> (b-a-a+b-a+(-a+b-a))
11
>>> (b-a-a+b-a-a+b-a)
11
>>> b-a-a+b-a-a+b-a
11
>>> 3*b-5*a
11
>>> (9*b-15*a)
33
>>> b-(9*b-15*a)==c
True
>>> b+(-9*b+15*a)
59
>>> b-9*b+15*a
59
>>> 15*a-8*b
59
This simple game taught me some lessons:
- Pseudo-Random exploration is helpful to find a solution.
- Be ware of the word 'repeat'. It could hide a mathematical operation.
---
20100729T0948:
round a problem many times
look for hindrances, obstacles, inconveniences
re-round each found obstacle and find inner obstacles
until one obstacle is solved
then, that solution will solve another
and so, like a domino effect,
the first and original problem
starts to get solved
- [id, status, created, modified, position, modcount]
20100729T1125:
writing undefined sentences to describe the problem
making calculations with parameters to find a result
opening many files to understand and solve the code
20100729T1143:
TDD to automate tests "seems" the way to go.
GUI needs to be scriptable, and HTML allows this.
Maybe JavaScript could be a problem, but if you could
append a [SCRIPT] tag and run it, it will be no problem
Enterprise, Human Resources, People and Wars:
- If you kill people, you must find and train new ones.
- If you forgive people, they will squeeze you.
martes, 20 de julio de 2010
SQL = Sets Quarantined, Lost
I have two tables in a MySQL database. They both have persons, but BOTH tables have persons that are not in both. So, I wanted to bring all those people that are not repeated. I can do this using inner loops, but I tried to do it by MySQL alone.
I elaborated an example with two sets: t1=[a,b,c]; t2=[a,b,d]. What I want to bring is this set: r=[c,d]; because [a,b] can be retrieved by a simple INNER JOIN.
#TEMPORARY TABLES WE WILL USE
#TABLES WITH ELEMENTS WILL BE: t1 AND t2
DROP TEMPORARY TABLE IF EXISTS t1,t2,plus,minus;
#FIRST DATA SET
CREATE TEMPORARY TABLE t1 AS
SELECT 'a' AS f1 UNION SELECT 'b' UNION SELECT 'c';
#SECOND DATA SET
CREATE TEMPORARY TABLE t2 AS
SELECT 'a' AS f2 UNION SELECT 'b' UNION SELECT 'd';
#CREATING THE "UNION"
CREATE TEMPORARY TABLE plus AS
SELECT * FROM t1
UNION
SELECT * FROM t2;
#CREATING THE "INTERSECTION"
CREATE TEMPORARY TABLE minus AS
SELECT t1.* FROM t1
INNER JOIN t2
ON t1.f1=t2.f2;
#CHECK OUR TEMPORARY TABLES
SELECT * FROM t1; #FIRST TABLE
SELECT * FROM t2; #SECOND TABLE
SELECT * FROM plus; #ALL ELEMENTS
SELECT * FROM minus; #COMMON ELEMENTS
#AND THIS IS THE OPERATOR I NEED IN MYSQL
SELECT plus.* FROM plus
LEFT JOIN minus
ON minus.f1=plus.f1
WHERE minus.f1 IS NULL
/*
AN UNION MINUS AN INTERSECTION BRINGS ALL RECORDS
THAT ARE NOT PRESENT IN ANY SET
YOU SEE, VENN DIAGRAMS AND SET THEORY ARE TOO OLD SCHOOL
THAT THEY SEEM NOT NEEDED NOWADAYS. BUT NOW,
OBJECT-ORIENTED ANALYSIS AND DESIGN IS, AGAIN,
BRINGING ALL THOSE OLD-SCHOOLERS BACK!!
*/
jueves, 1 de julio de 2010
Frameworks = Mathematical Placebos
Thanks to Online LaTeX Equation Editor. Very helpful for "The Placebo Formula"
---
Programming Frameworks are like something I have called as Mathematical Placebos, extra data that we add to equations to help us reach its results.
This extra data bloats the language ahead of the future. We tend to find many gotchas before and while we are working on a code, and they will delay code delivery.
What started easy, now is not.
To give a mathematical example, a very interesting equation, Euler's Identity, goes like this:

LaTeX: e^{i\pi}+1=0
PHP: it doesn't have built-in calculations for imaginary numbers.
Python: print (math.e**(math.pi*1j))+1
The result is this Python expression is not exactly 'zero', but very near to it. This is a common catch in floating point calculations. ;-P
Do you imagine what amount of tests Leonhard Euler did, in order to find out that relation of constants returns -1?
What I call "The Placebo Formula" (numbers I recall when I solve fractional, algebraic, or exponential equations), goes like this:

LaTeX: \frac{\sqrt[1]{\left(\textbf{1}\right)^{1}}}{1}+0=1
PHP: echo pow(1.0,1.0/1.0)*1.0/1.0+0.0;
Python: print 1.0*1.0**(1.0/1.0)/1.0+0.0
Do you get the idea of all those extra artifacts in both placebo formula and frameworks? You have to remind yourself that if you see a simple "1" in a formula, you can add any of those pseudo-numbers to ease your calculations.
In programming, this effect is also achieved when you create a common Object class for every object, including those objects not yet discovered or planned. When you have to add a behavior to all objects, you add it to that base Object class.
---
PS: I annotated what I need to do in this post instead of actually doing it! (e.g. I typed "use an image of euler's identity and wikipedia link") It is always easier said than done, although this action can prompt you to do a better organization of the way in which you express your thoughts. Write for yourself!
---
Programming Frameworks are like something I have called as Mathematical Placebos, extra data that we add to equations to help us reach its results.
This extra data bloats the language ahead of the future. We tend to find many gotchas before and while we are working on a code, and they will delay code delivery.
What started easy, now is not.
To give a mathematical example, a very interesting equation, Euler's Identity, goes like this:

LaTeX: e^{i\pi}+1=0
PHP: it doesn't have built-in calculations for imaginary numbers.
Python: print (math.e**(math.pi*1j))+1
The result is this Python expression is not exactly 'zero', but very near to it. This is a common catch in floating point calculations. ;-P
Do you imagine what amount of tests Leonhard Euler did, in order to find out that relation of constants returns -1?
What I call "The Placebo Formula" (numbers I recall when I solve fractional, algebraic, or exponential equations), goes like this:

LaTeX: \frac{\sqrt[1]{\left(\textbf{1}\right)^{1}}}{1}+0=1
PHP: echo pow(1.0,1.0/1.0)*1.0/1.0+0.0;
Python: print 1.0*1.0**(1.0/1.0)/1.0+0.0
Do you get the idea of all those extra artifacts in both placebo formula and frameworks? You have to remind yourself that if you see a simple "1" in a formula, you can add any of those pseudo-numbers to ease your calculations.
In programming, this effect is also achieved when you create a common Object class for every object, including those objects not yet discovered or planned. When you have to add a behavior to all objects, you add it to that base Object class.
---
PS: I annotated what I need to do in this post instead of actually doing it! (e.g. I typed "use an image of euler's identity and wikipedia link") It is always easier said than done, although this action can prompt you to do a better organization of the way in which you express your thoughts. Write for yourself!
Evolution of Coding
It all started so simple:
---
PS: IPO (Input-Proccess-Output) ... Hajime no 'IPO' ;-P
- George Boole, and his Boolean Algebra.
- Claude Elwood Shannon, and his Information Theory.
- Alan Mathison Turing, and his Turing Machine.
- Charles Babbage, and his Programmable Computer.
- John von Neumann, and his Computer Architecture.
- Every computer problem is composed by 'only' three main parts: input, process, output.
- The input part needs both a layout and an interface to look nice.
- The main process must be structured, and it should support alternate logic to handle possible exceptions.
- The output also needs a layout specifically designed for screens, papers and files.
- Not all users will be allowed to use this program. So an authentication system is required. Also, it should allow many users, each one with possible different roles and levels.
- In the input part, users commit many mistakes, so validation is needed for each data that program receives.
- To ease distribution of the program, and to centralize the data store, a client/server structure is defined.
- Many users in different remote location have different languages. So, programs now need to support different types of languages, like english, spanish, etc.
- Good database software and modern platforms have been developed. So, it should be useful to make programs able to migrate to them. (db, os, platform, web, mobile, etc.)
- It's hard to create a migrable program, so we should separate our development into three layers or tiers: back,middle,front (A.K.A M.V.C.)
- There are several programming languages on which we can express many of these principles easier (C++, Java, etc.), so we should migrate our programs to them.
- We are losing performance as our user base grows up. So, we should test concepts like replication.
- Some foreign programs and systems also want to have access to our program. So, we should create Web Service or open ports for Socket programming.
- It's probable that, with all these changes, we have left some doors open because of lack of sanitation. We must protect our programs against Session Hijacking, Cross-Site Scripting (XSS), and several types of Injections (SQL, HTML, CMD)
- Many users access the same resource simultaneously, and that generates either deadlocks or data inconsistency. So, we should program taking into account concurrency and multiple threads of execution.
- Our application is growing too much. So, we should apply concepts like distributed/cloud computing, to make our programs and database expandable by simply buying extra hardware.
- OOP, EXCEPTIONS, CHANGE (files,interrupt)
---
PS: IPO (Input-Proccess-Output) ... Hajime no 'IPO' ;-P
viernes, 14 de mayo de 2010
Parameterizing
There are two ways to pass values to functions. I will state examples using PHP:
The power of the New one is that parameters can be expressed in any order!! For example, if you want to add the middle name and a second last name to showUser() function, we can add it, and it won't bring problems to other code using that function, but its interface and implementation stars to become a mess, something that is somewhat reduced with the Old method.
DOS
--Vs--
In lambda calculus, each function has exactly one parameter. The process to emulate multiple parameters is called currying. It looks crazy, but I think it is the way to go if we want to find a new order for these Parameters' disorder. Python supports this kind of paradigm, and is my next language to study after I achieve a basic-intermediate level of my C++ abilities. I was looking to Haskell or LISP, but Python's documentation on the web is way too much better.
This is the strongest Yin-Yang I have found in programming. Which one to choose?
- showUser('Ignacio','Cortorreal');
- showUser(array('name'=>'Ignacio','last'=>'Cortorreal'));
The power of the New one is that parameters can be expressed in any order!! For example, if you want to add the middle name and a second last name to showUser() function, we can add it, and it won't bring problems to other code using that function, but its interface and implementation stars to become a mess, something that is somewhat reduced with the Old method.
DOS
- format /q/u/v/c/s
- g++ -Wall hello.cpp -o hello.bin
- type a.txt b.txt
- grep -v " OK "
- save({a:1,b:2,c:3});
- sum(1,2,3);
- /products/view/5/1
- /products/list/page:3/sort:desc/
- script.php?first=john&last=doe
- Horizontal Vs. Vertical Structures:
| ID | First | Last |
|---|---|---|
| 3 | Ignacio | Cortorreal |
--Vs--
| ID | Field | Value |
|---|---|---|
| 3 | First | Ignacio |
| 3 | Last | Cortorreal |
In lambda calculus, each function has exactly one parameter. The process to emulate multiple parameters is called currying. It looks crazy, but I think it is the way to go if we want to find a new order for these Parameters' disorder. Python supports this kind of paradigm, and is my next language to study after I achieve a basic-intermediate level of my C++ abilities. I was looking to Haskell or LISP, but Python's documentation on the web is way too much better.
This is the strongest Yin-Yang I have found in programming. Which one to choose?
miércoles, 3 de marzo de 2010
Oda a la programación
hacer la programación divertida: meditar inventar codear con belleza resolver un problema, suicidio moral, pensar solo en ella. procesos paralelos! Fun!
no es codear. sinó hacer algo que funcione en el menor tiempo posible aunque lances un torrente de codigo. Es tenerlo siempre en la mente. solo eso y nada más.
Es pensar en los arreglos condiciones bucles matemática cadenas variables tipos y almacenamiento como las operaciones para resolver problemas.
Lo gracioso de las abstracciones es que hay otras cosas divertidas que encajan con el mismo concepto. Por ejemplo: fea, larga y complicada puede ser la programación, una mujer o un pene!
programar es como redactar: tienes la libertad de expresar un mensaje de muchas formas diferentes, aunque algunas palabras son mas bellas que otras.
Hay infinidades de formas para resolver un problema. y de vez en cuando el tiempo trae nuevas alternativas que quiza hayas ignorado mucho antes.
programar es feo por dentro y bello por fuera. Agitan con el tiempo. Y traen una solución que amarra o se vuelve inmanejable con el tiempo. Mejor algo que nada. Nada es eterno.
programar es simplemente otro canal para conversar con la gente. Pues entonces tiene las mismas desventajas que hablar y las mismas ventajas también.
en la vida la opción es mejorar al mundo. En programación es resolver problemas. Uno mejora al mundo al resolver los problemas que tiene o al mejorar alguno de sus procesos.
velocidad o masa, desempeño o seguridad. fuerza o inteligencia.
spaguetti+reusar. el fin justifica los medios. Orden en mi mente. Algoritmo. Si pienso, pierdo tiempo; si actúo cometo errores. La pregunta mágica es: cual es el problema que tú tienes en este preciso momento?
codear y depurar. Metas: visual proceso datos -> variables validar/sanitar ILSUD. Otro cálculo? Reporte Errores+Ajax? Gallina o Huevo? Objeto o Proceso?
validación+errores paginación ordenación árboles Ajax|Sesiones
disciplina horario itinerario agenda programa algoritmo codigo... chess openings! Recuerda practicarlos y mejorarlos siempre!
no es codear. sinó hacer algo que funcione en el menor tiempo posible aunque lances un torrente de codigo. Es tenerlo siempre en la mente. solo eso y nada más.
Es pensar en los arreglos condiciones bucles matemática cadenas variables tipos y almacenamiento como las operaciones para resolver problemas.
Lo gracioso de las abstracciones es que hay otras cosas divertidas que encajan con el mismo concepto. Por ejemplo: fea, larga y complicada puede ser la programación, una mujer o un pene!
programar es como redactar: tienes la libertad de expresar un mensaje de muchas formas diferentes, aunque algunas palabras son mas bellas que otras.
Hay infinidades de formas para resolver un problema. y de vez en cuando el tiempo trae nuevas alternativas que quiza hayas ignorado mucho antes.
programar es feo por dentro y bello por fuera. Agitan con el tiempo. Y traen una solución que amarra o se vuelve inmanejable con el tiempo. Mejor algo que nada. Nada es eterno.
programar es simplemente otro canal para conversar con la gente. Pues entonces tiene las mismas desventajas que hablar y las mismas ventajas también.
en la vida la opción es mejorar al mundo. En programación es resolver problemas. Uno mejora al mundo al resolver los problemas que tiene o al mejorar alguno de sus procesos.
velocidad o masa, desempeño o seguridad. fuerza o inteligencia.
spaguetti+reusar. el fin justifica los medios. Orden en mi mente. Algoritmo. Si pienso, pierdo tiempo; si actúo cometo errores. La pregunta mágica es: cual es el problema que tú tienes en este preciso momento?
codear y depurar. Metas: visual proceso datos -> variables validar/sanitar ILSUD. Otro cálculo? Reporte Errores+Ajax? Gallina o Huevo? Objeto o Proceso?
validación+errores paginación ordenación árboles Ajax|Sesiones
disciplina horario itinerario agenda programa algoritmo codigo... chess openings! Recuerda practicarlos y mejorarlos siempre!
jueves, 11 de febrero de 2010
Excite/Motivate
Excite and/or motivate solutions and make them to be expressed either by yourself or others. Don't ignore the possibility!
Problem? Objective!
Way? Algorithm!
Structure? Start and End!
Test the Algorithm!
Algorithm Types: Informal and Computational
In Andrea: The Revenge of the Spirit, Babu Corsicack said: "A question might bring many answers; but one only answer might bring many questions." Remember that your answers will be upgraded, commonly when needs appear.
Nothing stays the same. Everything changes. (Buddhism)
Problem? Objective!
Way? Algorithm!
Structure? Start and End!
Test the Algorithm!
Algorithm Types: Informal and Computational
In Andrea: The Revenge of the Spirit, Babu Corsicack said: "A question might bring many answers; but one only answer might bring many questions." Remember that your answers will be upgraded, commonly when needs appear.
Nothing stays the same. Everything changes. (Buddhism)
miércoles, 3 de febrero de 2010
Programming Minutes: 15-5
Oscillations are Everywhere. If you go to one extreme, sooner or later you will want to experiment with the other.
Biorithm. Some people tried to create approximation formulas related to our mood, just like we calculated a year or menstruation cycle, and in some sense, it worked approximately!
Freedom of Choice: Work and Rest cycles. You can neither work nor rest forever. Your body and mind will speak out loud, even if you either drink tons of coffee or you have two months of vacation.
Extreme Programming. Techniques promoting a programming environment full of speed. Although Linux method starts slow, but it gets too fast after some time.
Google's long tail. Success of Google, like Linux, focused on everything Big Boys ignored or overlooked: how useful can be to show appreciation for The Underdogs.
15-5. Fifteen minutes of work, and five minutes of rest. This is not a Lord's Prayer, but you must always include moments of rest or fun in your job.
Vices. It is the biggest problem of the 15-5, that you can get too attached to moments of rest, but that is the risk, because "humans are lazy by nature."
Sleep is too long. Work too.
Biorithm. Some people tried to create approximation formulas related to our mood, just like we calculated a year or menstruation cycle, and in some sense, it worked approximately!
Freedom of Choice: Work and Rest cycles. You can neither work nor rest forever. Your body and mind will speak out loud, even if you either drink tons of coffee or you have two months of vacation.
Extreme Programming. Techniques promoting a programming environment full of speed. Although Linux method starts slow, but it gets too fast after some time.
Google's long tail. Success of Google, like Linux, focused on everything Big Boys ignored or overlooked: how useful can be to show appreciation for The Underdogs.
15-5. Fifteen minutes of work, and five minutes of rest. This is not a Lord's Prayer, but you must always include moments of rest or fun in your job.
Vices. It is the biggest problem of the 15-5, that you can get too attached to moments of rest, but that is the risk, because "humans are lazy by nature."
Sleep is too long. Work too.
lunes, 1 de febrero de 2010
Divide? Distractions? Prototype!
"Divide and conquer" is a very good advice to give in order to solve really big problems; nevertheless, techniques for division are not so vast. There appear many alternatives for division and we need to analyze and take note about all of them, and later choose decisions. I am trying to develop a method for myself and, in essence, it resembles a tree data structure: a tree whose branches grows until each and every one of them get exhausted.
If I "solace" myself, then I fall sleep and stop working. If I don't do it, I only thing about it. If I work, then it's too late or I need to ignore other duties. At this time somebody would say "You are a crazy morbid idiot", but I am more interested to find out what things in life induce these kind of thoughts or branches, then I will study each one of them.
Even though 0.01% is a very good plan to build motivation, exactly after you finish, distractions might appear. For example, if a work flow is to turn computer on, to open a folder, then an internet browser, a file editor and a script file, then print a little example, and write conclusions on paper... alright, these are elemental steps that conform your 0.01% effort. Then, what about those distractions after 0.01%?
My answer right now is prototype. Create the dumbest and silliest prototype of a solution! The dumber, the better. Remember that you can improve it. The fact that you don't know the final look of interface and solution adds the necessary randomness, but remember to start with K.I.S.S. (Keep It So Simple), of course, until clients needs something new... but the client could be yourself!
If I "solace" myself, then I fall sleep and stop working. If I don't do it, I only thing about it. If I work, then it's too late or I need to ignore other duties. At this time somebody would say "You are a crazy morbid idiot", but I am more interested to find out what things in life induce these kind of thoughts or branches, then I will study each one of them.
Even though 0.01% is a very good plan to build motivation, exactly after you finish, distractions might appear. For example, if a work flow is to turn computer on, to open a folder, then an internet browser, a file editor and a script file, then print a little example, and write conclusions on paper... alright, these are elemental steps that conform your 0.01% effort. Then, what about those distractions after 0.01%?
My answer right now is prototype. Create the dumbest and silliest prototype of a solution! The dumber, the better. Remember that you can improve it. The fact that you don't know the final look of interface and solution adds the necessary randomness, but remember to start with K.I.S.S. (Keep It So Simple), of course, until clients needs something new... but the client could be yourself!
martes, 22 de diciembre de 2009
Programming Blindspots
"A programmer who hasn't been exposed to all four of the imperative, functional, objective, and logical programming styles has one or more conceptual blindspots. It's like knowing how to boil but not fry."
-Tom Christiansen
I know more or less what MVC is about, but I have some "blindspots" when I try to organize some of my code. One example is: Where should I put twenty SQL queries that are needed for filling twenty combo boxes? In some solutions there is a master table which has many foreign keys, and you should choose data from other tables in order to fill this table.
Another example: How should I use data stored on a user session: to pass them as parameters (objects), or use them as global access (static)? Because there are many "unconnected" sections of a program which may need an access to a session, like when there are many parts of a view which can only be seen for admin users.
From my point of view, there are still some topics where Structured and OOP programming can't be agreed. Sometimes an Idea can suffer disadvantages from both of them. The quote I used here prompted me two more programming styles, but I think that list will grow with time.
-Tom Christiansen
I know more or less what MVC is about, but I have some "blindspots" when I try to organize some of my code. One example is: Where should I put twenty SQL queries that are needed for filling twenty combo boxes? In some solutions there is a master table which has many foreign keys, and you should choose data from other tables in order to fill this table.
Another example: How should I use data stored on a user session: to pass them as parameters (objects), or use them as global access (static)? Because there are many "unconnected" sections of a program which may need an access to a session, like when there are many parts of a view which can only be seen for admin users.
From my point of view, there are still some topics where Structured and OOP programming can't be agreed. Sometimes an Idea can suffer disadvantages from both of them. The quote I used here prompted me two more programming styles, but I think that list will grow with time.
martes, 1 de diciembre de 2009
My mind set up on this
Now my thoughts are really set up on these things:
Of course, this list is not completely improved, because these are not enough to fully motivate me. Thinks like 1%, 70% and People have a hidden meaning that I am eagerly searching for.
- Create useful and helpful things for at least yourself
- Have a strong desire to create and upgrade
- Divide and Conquer
- Design - Code - Test
- Maintain - Extend - Reuse
Of course, this list is not completely improved, because these are not enough to fully motivate me. Thinks like 1%, 70% and People have a hidden meaning that I am eagerly searching for.
lunes, 30 de noviembre de 2009
About little improvements
Have you ever tried to make little improvements to any kind of thing you normally create? Have you tried to do visual improvements to it? For example: using smaller or bigger letters smaller, or using narrower or wider spaces between letters, words or lines, or making colors a little brighter or darker, and so forth.
It is very meticulous to make these very little variations of these modifications. Sometimes to do them feels like a very silly job.
Working on solutions of problems could be like using catapults, because you need to make one or two experimental shots before being able to calculate correct landing of stones.
Thomas Alva Edison said that "Opportunity is missed by most people because it is dressed in overalls and looks like work.". So, to really improve something, a certain amount of work is needed, including those silly modifications.
It is very meticulous to make these very little variations of these modifications. Sometimes to do them feels like a very silly job.
Working on solutions of problems could be like using catapults, because you need to make one or two experimental shots before being able to calculate correct landing of stones.
Thomas Alva Edison said that "Opportunity is missed by most people because it is dressed in overalls and looks like work.". So, to really improve something, a certain amount of work is needed, including those silly modifications.
Suscribirse a:
Entradas (Atom)
