Link to home
Start Free TrialLog in
Avatar of sam15
sam15

asked on

ProgramingHardCodinng

A quick question on hardcoding in programming.

Few users say not to hardcode as it makes system locked up and not flexible and I sometimes find
business logic force you to do that

If you have code like this that supports real-life business logic

If (media='CD' and production_stage='XX') then
  do this...
  caluclate costs using this formula
elsif (media='PAPER' and production_stage='YY') then
  do this....
  calculate costs using this formula.
end if;


IF (contract_Type = "A") Then
  add STAGE1, STAGE 2 to table;
else if (contract ty[e = "C") THen
  add stage 3, stage 4
end if;

DO you see this as hardcoding and bad practice or not?

Is there differenet rule engine metadata processing or using global variables to implement this for more flexibility?

Avatar of Sean Stuber
Sean Stuber

yes that's hard coding

the "A", "C",  "PAPER"  should probably be constants,  or functions that encapsulate the hardcoded values but return true/false according to whatever rule you are trying to implement

Sometimes hardcoding is necessary,  using a constant helps abstract it,  encapsulating in procedures or functions does do further.
Avatar of sam15

ASKER

Can you provide me a small example on how to do above using  a constant or encapsulated function or globals.

Is not changing the constant hard coding too?

declare
l_contract_type CONSTANT varchar2(1) default "A";
begin

IF (l_contract_type = "A")
  do this..
else
do that...
end if;
SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I try to avoid hard coding whenever I can. What if you decide that you don't want to call it 'CD' any more since everything is on DVDs now? If you had it set up as a constant, this would be an easy change.
>> Is not changing the constant hard coding too?

Yes, but you've abstracted the value to it's business context and given it a referencable meaning.


If the name or value changes it's easy to find and correct.
You might not be able to do a simple search and replace,  what if you had multiple things with value 'A'


If you'd like to see a mix of where I embed hard coded values and where I declare constants, check out my FTP pacakge
https://www.experts-exchange.com/Database/Oracle/PL_SQL/A_3043-How-to-FTP-with-Oracle-PL-SQL.html

You'll see I declare constants for the port numbers even though they aren't really variable.

Later, in the various functions and procedures I have hardcoded strings.
Why?  Because they are self-describing, single use,  and I have encapsulated them within a routine so the values are masked anyway.
You won't use those values, instead you'll invoke the procedure or function and the values used within it are isolated from you.
Hello, i develop firmwares, drivers and high level applications.
So as a developer which migrates too often btw high and low level languages, i face many times those questions.

While at hardware level you do hardcode ALOT, in software level you will be most of the times, running from it.

There is no easy rule, for smaller apps hardcoding isn't that bad, in fact, it isn't bad at all.
But for bigger projects or projects which have the possibility to grow, then it's mostly likely to be a bad idea.

First things first:
Normaly, you'll get in touch with some C++ derivated language.
If you use constants in your 'IF' statement, use it after the variable, EVER.

If (media='CD' and production_stage='XX') then

Open in new window


This should be:
If ('CD' = media and 'XX' = production_stage) then

Open in new window



Get used to it because any CPP derivated language has to operands very similar:
'==' and '='
One compares the other assigns.
In a IF statement, if you trade one for another, it'll lead to unpredictable behavior.
But if you let the constant as the first operand, then you'll get a compile time error if you mistakenly write the wrong one.('=')
And believe, it sometimes saves you alot of time.

Even if you aren't yet in touch with this kind of language, it's good to use it until you do it automatically.

As for good practices, it's really abstract in everyways.
There are some which defend the "dont-use-goto"'s cause but sometimes, goto's are not just faster but more readable.

This is the case of constants.
Sometimes they are faster to write for small codes.
Very little times they are not bad for bigger codes.
But most of the times, you will need to encapsulate then.

In the above case, instead of doing this:
f ('CD' = media and 'XX' = production_stage)

Open in new window


You should do this:
f (media.IsCD() and production_stage.IsXX())

Open in new window


This way you can keep track of the constant in the method and even if you want to replace it, you can still let be for backwards compatibility until you complete replaces this method call by the new one, calmly, with no rush, thus with less bugs.
Use the OO concept to your favor.
Avatar of sam15

ASKER

I am using pl/sql and you cant switch variable with value like this (if 'CD' = my var)

ALso, it sounds like constants is anything that can be stored in a database tabl. that way we can change it without changing
the code in production.

My situation is different though. I wanna see if this is considered hard coding and where there is an alternative to it.

Company ABC assigns books to vendors for production. They use a contract number for each assignment. Each contract number
has a type.

SO here is the business rule for book assignment.

When user assigns book to vendor using contract type "A", then the code needs to add production stage A1,A2,A3 (3 records to a production table).
When user assigns a book to vendor using contrat type "B", then the code needs to add production stage B1, B2.

To me this is coded like this

Procedure assign_book (book_no, contract_type)

begin

if (contract_type = "A") Then

  insert into production_table values (A1,...);
  insert int production_Table values (A2..);
   insert into production_Table values (A3,....);
elsif (contract_type = "B") then

  insert into production_table values (B1,...);
   insert into productioN_table values (B2,...)'

end if;

end;
yes, that's hard coding.  The fact that you could look up in a table in a table makes it more likely to be a variable.

A constant is a value that you don't expect to change, hence it is "constant"

If "A" and "B" are values that aren't expected to change,  then declare them constants that mean something.

Even if the value is varchar2(1) 'A' or varchar2(1) 'B',  given them meaningful names that define what "A" and "B" mean.

If they are arbitrary strings that have no business value or technical logic then A/B literals are fine.
Assuming you are dividing your data into A and B tables for a reason, then name them according to that reason
If the ONLY place you ever use A/B literals is inside one small procedure then it's probably ok, maybe even preferable to leave them as is.

If the A/B values might be used someplace else, then declare a constant that is shareable and use that.
Avatar of sam15

ASKER

A means Analog, D = Diigital, and so on. They mean something logically..

These are used all over the application with different business rules for each type.

Can you show me a sample on how would this be rewritten so it wont be considered hard coding.

I do not see it.

The only other way of doing this i see is adding a table (contract_type, stage) and looking up the stage dunamically from table using code like this

IF (contract_Type = "A") then
  for x in (select * from table where contract_type = "A") lool
    insert into prod_table values (....
  end loop;
end ifl
declare
    c_analog constant char(1) := 'A';

begin
   IF (contract_Type = c_analog) then
      for x in (select * from table where contract_type = c_analog) loop
          insert into prod_table values (....
      end loop;
    end if;
end;
ideally the constant would be declared in a package header that could be referenced by all code that needed it.

Avatar of sam15

ASKER

so, simply declaring a constant as "A" and referencing it in the code turns it from "harcoding" to "non hardcoding" and make it more flexible and easier to maintain?

If there is only one reference to the "A" it is same work anyway. I do not see much benefit.

If the current database does not have a lookup table, and i have 3 hardcoded insert statements, is this also bad?

I cant see a system where there is no specific hardcoding for some business rules. I do understand how those rule driven engine systems work but infinite flexibility comes at a high cost for performance.
If there is only one reference to the "A" it is same work anyway. I do not see much benefit.
There are two main reasons to use constants in this case.
1. It's a good habit to be in for later.
2. What if the program gets bigger? I work with a huge enterprise management system that started out as a couple short scripts. Little pieces kept getting added and the programmer (not me) didn't feel the need to do things the 'right way' since it was so small. It was really useful though and stuff kept getting added. Now it's massive with over 100,000 lines of code and it takes forever to debug.

If the current database does not have a lookup table, and i have 3 hardcoded insert statements, is this also bad?
If you could use a loop and a table then it would be super easy to add a new one or 5 new ones. Also, if you find a bug in the insert line, now you have to fix it all three times and you might miss one.

but infinite flexibility comes at a high cost for performance.
There is usually no cost in performance. It just takes a bit longer to write the initial code. But it takes a lot less time to modify the code.
We could also discuss using comments and longer, more descriptive variable names since the same rules apply. It takes more time now but saves a lot of time later.
It all comes down to forward thinking. If you are in the habit of doing it the 'right' way now, it will eventually save you time in the future.
I deduce from the spelling in the title of this question that you generally prefer the quick and dirty solution ;-). I usually do as well, but the longer I do this, the more I realize that it's just better to do it the right way every time. Once you get in the habit, it's not that much slower anyway. In fact, your code all gets so uniform since that it's almost faster since you're so you've basically written it before.
Avatar of sam15

ASKER

interestingly, according to the hardcoding definition, any program that has input or configuration data embeded is considered hard code.

If i am correct, processing a book based on contract type (A) is not configuration or input data.
The input data is book number.

It is difficult to determin sometimes when you are writing code whether it is considered hardcode or not.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The goal is not to remove hardcoding completely, the goal is to encapsulate it so the code is easier to maintain and then minimize the places where it's necessary to use them.

Shared constants do exactly that

The constant itself is hardcoded, but only once.  After that you never need to hardcode that value again, you can simply use the constant.

Avatar of sam15

ASKER

To me, I would pick your A version of the code. IT is easier for me to see the condition (x <= 5) firectly rather than figure out what your packaged variable is.

If yuo reference this 100 times in code everywhere and might change in the future then i agree it is easier for maintenance. Actually, i would prefer to store it in a table personally.

I forgot to show the link for hardcoding definition. But I meant to say it talks about configuration data and input parameters. If the value like contract type is not configuration and input then it is not hardcoding. There is really a fine line on the defintion. Some might say every SQL statement with WHERE clause is hardcoding.

http://en.wikipedia.org/wiki/Hard_coding
>>> rather than figure out what your packaged variable is.

That's the point.  You don't have to figure anything out,  the constant tells you what it is.

What is "5"?  I happen to work for a company with 5 divisions, except sometimes it's 6 and sometimes 8.  
Is 5 correct in that line?  Maybe, maybe not.

Before you say "but the constant might be defined wrong"  that's avoiding the question.
 but even if it is,  it's a one time trivial fix of one line of code and easily identified.


>>> I would pick your A

Seriously?
I don't want to offend, but I have to ask.  Is this entire thread just a troll?