Solved

ProgramingHardCodinng

Posted on 2011-02-26
20
277 Views
Last Modified: 2012-05-11
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?

0
Comment
Question by:sam15
  • 9
  • 6
  • 4
  • +1
20 Comments
 
LVL 73

Expert Comment

by:sdstuber
ID: 34988712
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.
0
 

Author Comment

by:sam15
ID: 34988970
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;
0
 
LVL 37

Assisted Solution

by:TommySzalapski
TommySzalapski earned 200 total points
ID: 34989079
It really depends on the scope of the problem whether you should hard-code or not. If it's a small script that is used by only a couple people, then I think it's worth the time it saves to just hard code. If it's a compiled program used by many that someone might need to modify down the road, you'd better use constants (and good comments).

Is not changing the constant hard coding too?

No, that is not considered hard coding. Consider the following example

inputVal = GetInputFromUser
If(inputVal > 1000)
  while(inputVal > 1000)
    Output("Please enter a value smaller than 1000");
    inputVal = GetInputFromUser
  end while
end if

Let's say it can be 2000 now. You have to change all three, what if you miss one? Most programs are much more complicated.

So if you instead used
const MAX_VAL = 1000
inputVal = GetInputFromUser
If(inputVal > MAX_VAL)
  while(inputVal > MAX_VAL)
    Output("Please enter a value smaller than "&MAX_VAL);
    inputVal = GetInputFromUser
  end while
end if

then you only need to change it once.
0
 
LVL 37

Expert Comment

by:TommySzalapski
ID: 34989093
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.
0
 
LVL 73

Expert Comment

by:sdstuber
ID: 34989344
>> 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
http://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.
0
 
LVL 3

Expert Comment

by:sergiobg57
ID: 34989369
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.
0
 

Author Comment

by:sam15
ID: 34989697
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;
0
 
LVL 73

Expert Comment

by:sdstuber
ID: 34989726
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
0
 
LVL 73

Expert Comment

by:sdstuber
ID: 34989730
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.
0
 

Author Comment

by:sam15
ID: 34989983
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
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 73

Expert Comment

by:sdstuber
ID: 34990088
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;
0
 
LVL 73

Expert Comment

by:sdstuber
ID: 34990090
ideally the constant would be declared in a package header that could be referenced by all code that needed it.

0
 

Author Comment

by:sam15
ID: 34991797
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.
0
 
LVL 37

Expert Comment

by:TommySzalapski
ID: 34991853
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.
0
 
LVL 37

Expert Comment

by:TommySzalapski
ID: 34991862
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.
0
 

Author Comment

by:sam15
ID: 34991877
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.
0
 
LVL 73

Accepted Solution

by:
sdstuber earned 300 total points
ID: 34992288
>>> any program that has input or configuration data embeded is considered hard code.

yes,  any value that is stored within the code itself is hardcoding.

and yes, the declaration of a constant is itself also hardcoding.

There is 0 performance impact to using constants in compiled code because the values are resolved at compile time.

Using constants instead of literal values lets you give name and meaning to the values and allows for discreet changes if needed.

It's same reason complex code is encapsulated in sub routines and those subroutines are given meaningful names.


You "could" write all of your code as one gigantic process with goto's and all variables named v1, v2, v3, etc and all relevant values hardcoded
as embedded literals.  But that's poor code quality because it's harder to maintain, harder to debug, harder to train and pass on to someone else.


Which code is easier to read and understand?
Which would you rather have to edit when somebody says
"We've merged with a new company so we'll have a 6th division to report on now"


A
-------

if x <= 5 then
    -- do something
end if;

if y <= 5 then
    -- do something else
end if;

Open in new window



or

B
-----
if x <= pkg_public_constants.c_division_qty then
    -- do something
end if;

if y <= pkg_public_constants.c_days_in_work_week then
    -- do something else
end if;

Open in new window




I would MUCH rather support the B code.  Especially if there are lots of instances where we might loop over the divisions in the company
and other places where we might loop over days in a work week.

Finding all places where there is "5" and updating to 6 could be an awful task in the A code.
Not only would you have to find all 5's but then check the context in which they were used to be sure you weren't changing work day counters
or any other place there might be a 5 used anywhere.









0
 
LVL 73

Expert Comment

by:sdstuber
ID: 34992297
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.

0
 

Author Comment

by:sam15
ID: 34993402
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
0
 
LVL 73

Expert Comment

by:sdstuber
ID: 34994314
>>> 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?





0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
"Disruption" is the most feared word for C-level executives these days. They agonize over their industry being disturbed by another player - most likely by startups.
This video shows syntax for various backup options while discussing how the different basic backup types work.  It explains how to take full backups, incremental level 0 backups, incremental level 1 backups in both differential and cumulative mode a…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now