Javascript discussion: Variable scopes and functions

Hi,
I'm wondering how people proceed regarding variable scope, and calling
functions and things. For instance, it's finally sunk in that almost
always a variable should be declared with var to keep it local.
But along similar lines, how should one deal with functions? That is,
should every function be completely self contained -- i.e. must any
variables outside the scope of the function be passed to the function,
and the function may not alter any variables but those that are local to
it? Or is that not necessary to be so strict?
Functions also seem to be limited in that they can only return a single
variable. But what if I want to create a function that alters a bunch of
variables?
So I guess that's two questions:
(1) Should all functions be self-contained?
(2) What if the function needs to return a whole bunch of variables?
Thanks,
Ariel

Ariel:
(Incidentally, I couldn't find any way of  marking answers correct when I visited the web forums a few days ago, so I gave up.)
It's there...as long as you're logged in at least, and are the poster of the thread.
What I want is to write code that I can easily come back to a few months later
and make changes/add features -- so it's only me that sees the code, but
after long intervals it can almost be as though someone else has written
it! So I was wondering if I would be doing myself a favour by being more
strict about make functions independent etc. Also, I was noticing that
in the sample scripts that accompany InDesign (written by Olav Kvern?)
the functions seem always to require all variables to be passed to it.
Where it is not impractical to do so, you should make functions independent and reusable. But there are plenty of cases where it is impractical, or at least very annoying to do so.
The sample scripts for InDesign are written to be in parallel between three different languages, and have a certain lowest-common-denominator effect. They also make use of some practices I would consider Not Very Good. I would not recommend them as an example for how to learn to write a large Javascript project.
I'm not 100% sure what you mean by persistent session. Most of my
scripts are run once and then quit. However, some do create a modeless
dialog (ie where you can interface with the UI while running it), which
is the only time I need to use #targetengine.
Any script that specifies a #targetengine other than "main" is in a persistent session. It means that variables (and functions) will persist from script invokation to invokation. If you have two scripts that run in #targetengine session, for instance, because of their user interfaces, they can have conficting global variables. (Some people will suggest you should give each script its own #targetengine. I am not convinced this is a good idea, but my reasons against it are mostly speculation about performance and memory issues, which are things I will later tell you to not worry about.)
But I think you've answered one of my questions when you say that the
thing to avoid is the "v1" scope. Although I don't really see what the
problem is in the context of InDesign scripting (unless someone else is
going to using your script as function in one of theirs). Probably in
Web design it's more of an issue, because a web page could be running
several scripts at the same time?
It's more of an issue in web browsers, certainly (which I have ~no experience writing complex Javascript for, by the way), but it matters in ID, too. See above. It also complicates code reuse across projects.
Regarding functions altering variables: for example, I have a catalog
script. myMasterPage is a variable that keeps track of which masterpage
is being used. A function addPage() will add a page, but will need to
update myMasterPage because many other functions in the script refer to
that. However, addPage() also needs to update the total page count
variable, the database-line-number-index-variable and several others,
which are all used in most other functions. It seems laborious and
unnecessary to pass them all to each function, then have the function
alter them and return an array that would then need to be deciphered and
applied back to the main variables. So in such a case I let the function
alter these "global" (though not v1) variables. You're saying that's okay.
Yes, that is OK. It's not a good idea to call that scope "global," though, since you'll promote confusion. You could call it...outer function scope, maybe? Not sure; that assumes addPage() is nested within some other function whose scope is containing myMasterPage.
It is definitely true that you should not individually pass them to the function and return them as an array and reassign them to the outer function's variables.
I think it is OK for addPage() to change them, yes.
Another approach would be something like:
(function() {
  var MPstate = {
    totalPages: 0,
    dbline: -1
  function addPage(state) {
    state.totalPages++;
    state.dbline=0;
    return state;
  MPstate = addPage(MPstate);
I don't think this is a particularly good approach, though. It is clunky and also doesn't permit an easy way for addPage() to return success or failure.
Of course it could instead do something like:
    return { success: true, state: state };
  var returnVal = addPage(MPstate);
  if (returnVal.success) { MPstate = returnVal.state; }
but that's not very comforting either. Letting addPage() access it's parent functions variables works much much better, as you surmised.
However, the down-side is that intuitively I feel this makes the script
more "messy" -- less legible and professional. (On the other hand, I
recall reading that passing a lot of variables to functions comes with a
performance penalty.)
I think that as long as you sufficiently clearly comment your code it is fine.
Remember this sort of thing is part-and-parcel for a language that has classes and method functions inside those classes (e.g. Java, Python, ActionScript3, C++, etc.). It's totally reasonable for a class to define a bunch of variables that are scoped to that class and then implement a bunch of methods to modify those class variables. You should not sweat it.
Passing lots of variables to functions does not incur any meaningful performance penalty at the level you should be worrying about. Premature optimization is almost always a bad idea. On the other hand, you should avoid doing so for a different reason -- it is hard to read and confusing to remember when the number of arguments to something is more than three or so. For instance, compare:
addPage("iv", 3, "The rain in spain", 4, loremIpsumText);
addPage({ name: "iv", insertAfter: 3, headingText: "The rain in spain",
  numberColumns: 4, bodyText: loremIpsumText});
The latter is more verbose, but immensely more readable. And the order of parameters no longer matters.
You should, in general, use Objects in this way when the number of parameters exceeds about three.
I knew a function could return an array. I'll have to read up on it
returing an object. (I mean, I guess I intuitively knew that too -- I'm
sure I've had functions return textFrames or what-have-you),
Remember that in Javascript, when we say Object we mean something like an associative array or dictionary in other languages. An arbitrary set of name/value pairs. This is confusing because it also means other kinds of objects, like DOM objects (textFrames, etc.), which are technically Javascript Objects too, because everything inherits from Object.prototype. But...that's not what I mean.
So yes, read up on Objects. They are incredibly handy.

Similar Messages

  • CRMOD Presentation variable scope and usage in drilldown report

    Hello dear all,
    I have dashboard and presentation variables on dashboard promt. When selecting these presentation variables all work fine within dashboard.
    But when I drilldown to another report that also uses these presentation varibales its not working.
    How to make possible to use presentation variables within dashboard ? Or maybe there is another way how to accomplish this.

    why do you want to show folder name for every column? folder name means name of the folder that reports saved in?? or presentation table name??
    you may use static rep variable to display folder name in report.
    Thanks
    Jay.

  • Sending and parse javascript object variable to java variable

    can anyone help me how to send and parse javascript object variable from client to java variable on servlet. Here is what i mention about:
    suppose i have object variable var_js with it's properties:
    <script>
    var var_js = {
    id: 'var_js1',
    name: 'this is var javascript',
    allow_value_type: ['int', 'string', 'object']
    </script>
    /* after processing javascript object to java var, that i hope you guys may help me, it's java var (var_java) become something like*/
    var_java.id = "var_js1";
    var_java.name = "this is var javascript";
    var_java.allow_value_type = {"int", "string", "object"}

    You could have this html page:
    <html>
    <script>
    var var_js = {
    id: 'var_js1',
    name: 'this is var javascript',
    allow_value_type: ['int', 'string', 'object']
    function send()
    document.getElementById("id").value = var_js.id;
    document.getElementById("name").value =var_js.name;
    document.getElementById("allow_value_type").value =var_js.allow_value_type;
    document.form.submit();
    </script>
    <form name="myForm" action="http://localhost:8080/servlet/myServlet" method="post" >
    <input id="id" type="hidden" value="">
    <input id="name" type="hidden" value="">
    <input id="allow_value_type" type="hidden" value="">
    <input id="cmdGo" type="button" value="Button" onClick="send()">
    </form>
    </html>
    Then have a servlet like this:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class myServlet extends HttpServlet {
    public void doPost( HttpServletRequest request,
    HttpServletResponse response )
    throws ServletException, IOException
    String id = request.getParameter("id");
    String name = request.getParameter("name");
    String allowed_value_type = request.getParameter("allowed_value_type");
    Var_java var_java = new Var_java(id,name,allowed_value_type);
    //and have you java object
    class Var_java
    String id;
    String name;
    String allowed_value_type;
    public var_java(String id,String name,String allowed_value_type)
    this.id=id;
    this.name=name;
    this.allowed_value_type=allowed_value_type;
    well...something like that i think.
    Hope it helps.

  • Accessing variables and functions between loaded external swfs?

    Using AS 3.0: Say I have a menu.swf that loads a content.swf
    below it using the following
    var newContent:Loader = new Loader();
    newContent.load(new URLRequest("fowContent.swf"));
    addChildAt(newContent,0);
    Now say I have a frame label in newContent that is an
    animation ending the display of that swf. Upon clicking of another
    menu button in menu.swf, can I access the content's ending sequence
    by:
    newContent.gotoAndPlay(newContent.endingSequence);
    Also can you use while loops in AS 3.0? I would like to have
    a boolean variable "ended" in the newContent that becomes true
    after the ending animation has played.
    while ( newContent.ended != true)
    //wait
    then have it run the function to load and display the new
    content.swf

    quote:
    Originally posted by:
    kglad
    p.s. you can't use a for-loop and you can't use a while-loop
    to effect any time delays. they both execute from beginning to end
    before anything is updated on-stage and no other code can execute
    outside of those loops (unless called from within the loop).
    Thank you very much for the help.
    Would I need to declare a MovieClip variable before using
    that statement or does that automatically cast newContent as a
    movieclip and go to the frame?
    So in order to achieve the flow I'm looking for.
    I'll have this in the menu.swf looking for clicks. It will
    run a function in the content.swf that runs the ending sequence and
    receives a string variable which is a concatenation of the
    buttonclicked (which is also the filename of next content) and
    .swf. (can I cast the event.target.name into a string the same way
    you casted the other into a movieclip?)
    function buttonClick(event:MouseEvent):void //in the menu.swf
    var nextFile:string = string(event.target.name) + ".swf";
    MovieClip(newContent.contentLoaderInfo.content).endSequence(nextFile)
    fowContent.addEventListener(MouseEvent.CLICK, buttonClick);
    In the content.swf I will have a public variable nextContent
    and the function that the menu.swf calls, which begins the ending
    sequence.
    public var nextContent:string;
    function endSequence(nextFile:string)
    nextContent = nextFile;
    gotoAndPlay(endingSequence);
    Then at the end of the movie sequence I could call this
    function that passes back the variable that was modified by the
    previous function and runs the loader.
    parent.loadNext(nextContent) //in the content.swf
    function loadNext(nextContent:string) //function in menu.swf
    newContent.load(new URLRequest(nextContent));
    addChildAt(newContent,0);
    I'm sure theres a better way to do this, and I don't even
    know if this will work. But I'd like to make sure it makes sense
    before I try to implement it.

  • Having Truble Reading and Echoing Using PHP in HTML. Possible Variable Scope Problem?

    Hey guys,
       Thanks for your always knowledgable help! Today I am working with displaying text from a text file in an HTML table using PHP. I can't get the data to display properly, I think it has something to do with the scope of the variables, but I am not sure. Here is the code I am struggeling with:
    <table width="357" border="1" cellspacing="0" cellpadding="0">
      <tr>
        <td width="165">Pizza 1</td>
        <td width="186"><? echo  $price['0']; ?></td>
      </tr>
      <tr>
        <td>Burger 1</td>
        <td><? echo $price['1']; ?></td>
      </tr>
      <tr>
        <td>Drink 1</td>
        <td><? echo $price['2']; ?></td>
      </tr>
    </table>
    In the above PHP (not shown) the array $price is filled properly (I tested by echoing each bit line by line) but by the time we get into the HTML it seems the array is empty or it is not liking how I am calling it. Does the scope of a PHP variable end with the closing "?>" tag? Am I missing something? Bellow is the full code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <style type="text/css">
    body {
        background-color: #333;
        color: #FFF;
    </style>
    </head>
    <body>
    <?php
    $menu=fopen("prices.txt","r") or exit("Unable to open file!");
    $price=array();
    $priceposition=null;
    $tempstring;
    //This loop does all of the READING and populating of variables
    while(!feof($menu))
        //Check to see if this is the first pass, if not add one to the array possition
        if ($priceposition==null){
            $priceposition=0;
        else{
        $priceposition++;
        //populate the temparary string
        $tempstring = fgets($menu);
        //Populate the array if the temporary string is not a comment
        if(substr($tempstring,0,2) != "//"){
            $price['$priceposition']= $tempstring;
            echo $price['$priceposition'];
      //End of reading loop
    fclose($menu);
    ?>
    <table width="357" border="1" cellspacing="0" cellpadding="0">
      <tr>
        <td width="165">Pizza 1</td>
        <td width="186"><? echo  $price['0']; ?></td>
      </tr>
      <tr>
        <td>Burger 1</td>
        <td><? echo $price['1']; ?></td>
      </tr>
      <tr>
        <td>Drink 1</td>
        <td><? echo $price['2']; ?></td>
      </tr>
    </table>
    </body>
    </html>
    and you can run the code on my test server here: christianstest.info/phptest/readwritetesting/readtest.php
    thanks guys!

    MurraySummers wrote:
    Try changing this -
    fclose($menu);
    to this -
    fclose($menu);
    echo "<pre>";exit(print_r($price));
    and see what you get.
    Wow, what a great little peice of testing code, thanks! That showed me the problem right away! Is there any way to test your php line by line in Dreamweaver CS6? I am used to computer programing in Visual Studio and Eclipse where they have an option of running code line by line and seing how variables populate and change with each line of code execution. Or is thier a program that can do this for PHP?

  • Variable scope within an interface and some questions

    I am creating a DataStorage interface with a member variable (can I call it a member variable when it is in an interface?) called dataObject. From what I remember, and what the compiler is telling me, the scope declarations "private," or "protected" can not be used on either methods or member variables in an interface.
    Now I have another class DataInput that implements DataStorage and I want to make the dataObject private and put in accessor methods to get to the dataObject. But I also remember reading something that said, during inheritance you can not make the scope of the method (and variable?) more narrow. Meaning if a method was defined as default in the parent class, the subclass can not override that method to give it private access all of a sudden.
    Now a couple of questions with this...does that rule only apply to subclassing (that is with extends) or does it also apply to implementing interfaces. Second question, I am pretty sure that rule applies to methods that are being overriden, but does it also apply to variables in an interface...because if that is the case, I can't re-declare the variable in the class that implements the interface to be private...and then there is no way to protect that variable.
    By the way I did re-declare the variable in the subclass (implementing class) and declared it as a private, and it works...but I'm still trying to figure out the general rule.

    well if the interface variables are implicitly public static final, how come I am able to re-declare the variable name within the class that implemented the interface.
    If for example in interface Car there is a variable color, how come in class Honda implements Car, I can redeclare the variable color, and give it public access. I thought final meant final, no redeclaring...but does that not hold for static variables?

  • Location of variable and function names in SWF bytecode?

    Ok, so I'm looking at the specification PDF for v10 of a SWF file.
    Here is a link to it: http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v10.pdf
    I can't find anything in there about where or how a SWF stores variable and function names in the bytecode, though SWF decompilers can find them in any SWF file. So they must be in there somewhere.
    Can any one help me on this one?

    Hi check the varaibles by giving ur tech.name of report input parameter to the below program,
    RSRQ_QUERYDEFINITION
    it will all the query details. So you can find ur varaibles where it is used exactly.
    bhaskar

  • Using a global variable within a function

    Hi all,
    I'm trying to learn how to use global variables, but can't quite get it right:
    Im trying to use two buttons, named UpButton and DownButton to control one global variable, p1
    A text field, named "Value" displays p1.
    Here's my code:
    p1 = 0;
    ButtonClick("UpButton", p1, 100,"Value");
    ButtonClick("DownButton", p1,(-100),"Value");
    function ButtonClick(ButtonName,Var,Increment,TextToChange){
                        sym.$(ButtonName).click(function(){
                        Var = Var + Increment;
                        sym.$(TextToChange).html(Var);
    However, it seems to be treating p1 as two different variables.
    Here's a link to the page to show you what I mean, apologies but this link wont work in google chrome because I'm using dropbox as a server temporarily
    In other browsers you may need to click "Show all content" or similar to any security warnings...
    https://dl.dropboxusercontent.com/u/83693404/ButtonTest/buttons.html
    Here are the project files:
    https://app.box.com/s/0shocivto8fl295h62uq
    Any help greatly appreciated, sorry if this is a stupid question,
    Katherine

    Hi Katherine,
    However, it seems to be treating p1 as two different variables.
    Indeed, your code created two different variables in two different scopes (I guess it as to do with JavaScript closures, but do  not ask me more, I am still a bit foggy about that idiosyncrasy ).
    In JavaScript, a primitive parameter – this is the case here with p1, a Number value –, is passed by value. In other words, a copy of the value is made. Your code handles two copies of the value stored in p1.
    This contrasts with an object parameter, which is passed by reference (address in memory), without copy. Your code would work if Numbers were passed by reference : the two Var (p1) would then point to the same address.
    The intent behind your trial is a global variable.
    1) Let us be as simple as possible :
    Stage : document.compositionReady event handler
    p1 = 0;
    buttonClick = function( Increment)
      p1 += Increment;
      sym.$( "Value").html( p1);
    Stage : DownButton.click event handler
    buttonClick(-100);
    Stage : UpButton.click event handler
    buttonClick(100);
    Without being preceded by the var keyword the variables are global.
    So the Number variable p1 can be accessed inside function buttonClick.
    And the Function variable buttonClick as well, is accessible inside click event handlers, everything (function definition +function calls) being inside the same symbol (Stage).
    2) Now, suppose this is no longer the case : you want to access a variable from another symbol.
    We create a new GraySquare symbol, instantiated both in the DownButton symbol (instance name DownSquare) and in the UpButton symbol (instance name DownSquare).
    Stage : document.compositionReady event handler
    p1 = 0;
    sym.buttonClick = function( Increment)
      p1 += Increment;
      sym.$( "Value").html( p1);
    The sym. prefix is now necessary to make the variable (here a Function, but you would proceed exactly the same with a String, Number or Boolean) accessible in other symbols.
    DownButton symbol : DownSquare.click event handler
    sym.getComposition().getStage().buttonClick( -100);
    UpButton symbol : UpSquare.click event handler
    sym.getComposition().getStage().buttonClick( 100);
    From these other symbols, the sym.getComposition().getStage(). prefix is necessary to acces to our global variable (function).
    The two examples are downloadable here : https://app.box.com/s/6vkyiqk7i8zwlw0j1wk1
    Gil

  • Difference between procedure and function

    hi
    please give solution to below discussion:
    Interviewer: What is the difference between Procedure and Function ?
    Myself: Procedure may or may not return a value and can return multiple values and Function must return a value.
    Interviewer : Can function return multiple values ?
    myself: Yes, It can return multiple values.
    Interviewer: Then, there is no need to use procedures any more, according to your previous answer (function can return multiple values) "we can do all the things by using procedures by using functions". Then why there is differentiation between procedure and function ?
    myself : no reply (simply frustated at this question)
    The above is conversation between me and interviewer.
    Please suggest me what would be my reply to above topic.
    In one book i find that using functions we can return multiple values but it is poor programming practice.
    why this is a programming practice ?
    please suggest me solution
    thanks in advance
    prasanth as.

    Another difference is function must return something. There is no such restriction on procedure.In fact, a procedure CANNOT contain an expression in its RETURN statement.
    SQL> create or replace procedure test_return is
      2  begin
      3    return(10) ;
      4  end ;
      5  /
    Warning: Procedure created with compilation errors.
    SQL> show errors
    Errors for PROCEDURE TEST_RETURN:
    LINE/COL ERROR
    3/3      PLS-00372: In a procedure, RETURN statement cannot contain an
             expression
    3/3      PL/SQL: Statement ignored
    SQL>And, a procedure cannot be called as part of a expression (it must be a function).
    SQL> create or replace procedure test_return is
      2  begin
      3    return ;
      4  end ;
      5  /
    Procedure created.
    SQL> variable x number ;
    SQL> exec :x := test_return ;
    BEGIN :x := test_return ; END;
    ERROR at line 1:
    ORA-06550: line 1, column 13:
    PLS-00222: no function with name 'TEST_RETURN' exists in this scope
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    SQL>

  • Are the Pl/sql procedure and function atomic by themself

    i want to ask a question does oracle pl/sql procedure and function support Atomicity for the database by themself , or they became atomic incase we call them using begin -- end;

    You appear to be discussing transaction scope which is completely independent of PL/SQL blocks like procedures or how you call procedures. It's all in where commits (or rollbacks) are issued.
    If you have a procedure like this
    CREATE PROCEDURE p1
    AS
    BEGIN
      INSERT INTO some_table( key, value ) VALUES( 1, 'Foo' );
      INSERT INTO some_table( key, value ) VALUES( 1, 'Bar' );
    END;where the first statement succeeds and the second statement fails as a result of a duplicate key, there will still be a Foo row in the table but the procedure will have thrown an exception. The caller of the procedure may choose to commit or rollback the change-- that will determine whether the first statement's results are made permanent. If you have a procedure like this,
    CREATE PROCEDURE p1
    AS
    BEGIN
      INSERT INTO some_table( key, value ) VALUES( 1, 'Foo' );
      commit;
      INSERT INTO some_table( key, value ) VALUES( 1, 'Bar' );
    END;the commit will make the first insert permanent regardless of whether the second statement fails no matter what the calling code does (that's one reason that putting commits in stored procedures is generally a bad idea-- the caller is in a much better position to know what other uncommitted work has been done and whether it is safe to commit.
    Justin

  • Variable scope with loaded external SWF's?

    I’ve got an SWF, call it calcLite, that will be deployed both independently (ie: attached to an HTML doc) and also imported at run time (linked as an external asset via the loader class) to another SWF, let’s call it calcPro. That part is working fine.
    I’ve got a global variable, gRunMode:String that calcLite must declare and set when it’s running independently, but must inherit when attached to calcPro (which will declare and set gRunMode before attaching calcLite).
    Here’s where I am:
    At the root of calcPro:
    var gRunMode:String = “touchScreen”;
    At the root of calcLite:
    var gRunMode:String = “web”
    if (this.parent == this.stage) {
         gRunMode = MovieClip(this.parent.parent.parent).gRunMode;
    I’ve also tried creating function in the parent to return gRunMode:
    At the root of calcPro:
    var gRunMode:String = “touchScreen”;
    function getRunMode():String {
         return gRunMode;
    At the root of calcLite:
    var gRunMode:String = “web”
    if (this.parent == this.stage) {
         gRunMode = MovieClip(this.parent.parent.parent). getRunMode();
    I’ve also tried the second technique, renaming the global in calcPro to gRunModeExe incase there was a naming violation. In all cases I get “attempt to access prop of a null” error. The construct MovieClip(this.parent.parent.parent).function() works, I use it later in the program for a different function and it’s fine, just doesn’t work here.

    My bad, I wrote the post from memory at home. My actual code properly tested the stage (!=) and would have worked EXCEPT under the following condition:
    This is my second project in a row that involved an SWF that must operate independently and also function as a loaded child to a bigger project. What I keep forgetting is that loaded content begins to execute IMMEDIATELY!!!, it does not wait to be attached to the stage. Further, loaded content does not have access to stage assets until it’s been attached, so any premature attempts to access global variables and functions from loaded clip to stage fail. A good explanation of these issues can be found here (scroll to middle of page, post by senocular titled Access to stage and root): http://www.kirupa.com/forum/showthread.php?p=1955201
    The solution was simple enough. If calcLite is running as a child, stop in frame 1 (before any other processing) and wait for calcPro to push us to the next frame (which happens after attachment to the stage). If calcLite is running independently skip the stop and proceed as normal.
    As for this.parent.parent.parent vs. this.parent.parent vs this.parent, since gRunMode is global within the calcPro scope any of these would probably work (although I’ve only tested the first option). The first parent references the loader object, the second parent references the movie clip to which the loader object is attached, and the third parent finally references root.

  • How to find Unused variables in procedure,function or package

    Hi all,
    I want find out unused variables in procedure, function and package.
    I have written below script for doing this ,but i am not getting the expected result.
    Kindly help me to improve the below code ,so that it works as expected.
    {code}
    version details
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    "CORE    11.2.0.3.0    Production"
    TNS for Linux: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production
    {code}
    {code}
    What i Have tried is This.
    DECLARE
      V_OBJECT_NAME VARCHAR2(30) :='PR_PRINT';
      V_OBJECT_TYPE VARCHAR2(30) :='PROCEDURE';
      CURSOR C1(CP_OBJECT_NAME VARCHAR2,CP_OBJECT_TYPE VARCHAR2)
      IS
        SELECT US.NAME,
          US.TYPE,
          US.LINE,
          REGEXP_SUBSTR(US.TEXT,'.* ') AS var_name
        FROM user_source US
        WHERE name=CP_OBJECT_NAME
        AND type  =CP_OBJECT_TYPE
        AND REGEXP_LIKE (TEXT,'(v_|g_|c_)','i')
        AND REGEXP_LIKE (TEXT,'^[^ ]')
        AND REGEXP_LIKE (TEXT,'^[^--]') ;
      v_count NUMBER ;
    BEGIN
      FOR i IN C1(V_OBJECT_NAME,V_OBJECT_TYPE)
      LOOP
        SELECT COUNT( *)
        INTO V_COUNT
        FROM USER_SOURCE US
        WHERE US.NAME=I.NAME
        AND REGEXP_LIKE(US.TEXT,i.var_name,'i' )
        AND US.LINE<>I.LINE;
        IF V_COUNT  =0 THEN
          DBMS_OUTPUT.PUT_LINE('variable '||I.VAR_NAME||'Is declared at line#'||I.LINE||' But no where used');
        END IF ;
      END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('p_err_code := '||SQLCODE||dbms_utility.format_Error_backtrace());
      DBMS_OUTPUT.PUT_LINE('p_err_msg := '||sqlerrm);
    END ;
    {code}
    Thanks,
    P Prakash

    Hello,
    as suggested by padders you can use PL/Scope, an example:
    ALTER SESSION SET PLSCOPE_SETTINGS='IDENTIFIERS:ALL';
    CREATE OR REPLACE PACKAGE ui_test1 AS
        global_number   NUMBER := 9;
    FUNCTION get_number
        RETURN NUMBER;
    END ui_test1;
    CREATE OR REPLACE PACKAGE BODY ui_test1 AS
    PROCEDURE setNull
         p_varchar          IN OUT VARCHAR2
    IS
    BEGIN
        p_varchar := NVL(p_varchar,'NULL');
    END setNull;
    FUNCTION get_number
        RETURN NUMBER
    IS
        FUNCTION setZero
             p_number       IN NUMBER
            RETURN NUMBER
        IS
        BEGIN
            RETURN NVL(p_number,0);
        END setZero;
    BEGIN
        RETURN global_number;
    END get_number;
    END ui_test1;
    SELECT  DISTINCT
            object_name
           ,object_type
           ,name
           ,type
           ,line
           ,col
    FROM    all_identifiers obj
    WHERE   obj.owner = USER
    AND     obj.usage = 'DECLARATION'
    AND     obj.object_name = 'UI_TEST1'
    AND     NOT EXISTS (
                SELECT  1
                FROM    all_identifiers with_rh
                WHERE   obj.signature = with_rh.signature
                AND     with_rh.usage IN ('REFERENCE','CALL','ASSIGNMENT')
    ORDER BY TYPE
            ,object_name
            ,object_type
            ,name;
    OBJECT_NAME  OBJECT_TYPE   NAME       TYPE       LINE COL
    UI_TEST1     PACKAGE       GET_NUMBER FUNCTION     11  10
    UI_TEST1     PACKAGE BODY  SETZERO    FUNCTION     35  14
    UI_TEST1     PACKAGE       UI_TEST1   PACKAGE       1   9
    UI_TEST1     PACKAGE BODY  SETNULL    PROCEDURE    12  11
    Regards
    Marcus

  • JSP Variable Scope

    Hello,
    I'm fairly new to JSP, so I apologize if this is a newbie question. I'm having a problem where it appears as though some variables I defined in the declaration area of my JSP page are shared by multiple clients. Here is a code snippet...
    <%@ page import="java.util.*" %>
    <jsp:useBean id="postSearch" scope="request" class="healthweb.PostBean" />
    <%!
    String hridErr = "";
    String emplHrid = "";
    String supvHrid = "";
    String yourHrid = "";
    boolean youAreEmpl = true;
    boolean youAreSupv = false;
    Hashtable[] empl;
    Hashtable[] you;
    Hashtable[] supv;
    %>
    <SCRIPT LANGUAGE="JavaScript">
    alert("<%= request.getParameter("yHrid") %>");
    alert("<%= youAreEmpl %>");
    </SCRIPT>
    As you can see, I'm initializing the youAreEmpl variable to true. However, if a client executes this JSP and the variable gets set to false, it seems to be false when other clients access the JSP initially.
    I'm very confused by this. Doesn't each client receive its own scope and its own instance of the object created by the JSP page?

    First off, let's start by explaining what's going on here. A JSP page is converted to a servlet via the JSP parsing servlet that initially handles the request. When you use the declaration syntax <%!...%> you are declaring members (variables, methods, etc.) that are local to the underlying servlet. Since a servlet is a multi-threaded object, all clients share the same servlet object created from the JSP page. Thus, threading issues apply to all local members of the servlet object. In other words you have to make sure the members of the servlet are thread safe.
    Many are confused by this because JSP shields you somewhat from these concerns if you stay within the confines of the predefined service() method. What I mean is this. everything you code within the <%...%> and <%=...%> delimiters is placed in the service method of the underlying servlet. This is the collection of code/objects that each client runs a unique copy of. These areas are not subject to threadding concerns/issues.
    Now, There are a number of remedies to your situation. You can remove the exclamation point from the delimeters around your variable declarations (i.e. change all <%!...%> to <%...%>), or you could add the following implements clause to your JSP page via JSP directive: implements SingleThreadModel
    Forgive me, I don't recall the exact syntax for this as I don't have any of my manuals at hand. I believe it's something like: <%@ page implements="SingleThreadModel" %> Either would solve the problem. The SingleThreadModel forces each servlet to execute in it's own thread.
    Kind Regards,
    Cliff

  • Variable Scope Help Needed

    Can someone help me understand or can someone point me to the documentation that describes variables?
    I am thinking that variables defined in the BPELProcess are like global variables, variables defined in a scope are local variables to the scope, is this accurate?
    I am trying to access the receive activity input variable in my catch block but it appears to be empty, when a fault occurs do the "global" variables go out out of scope?

    Hi ,
    As soon as you create a BPEL process , you have a parent scope already .If you create variables for that scope then the variables are global and can be used any where in the complete process .
    Now , if you drag and drop some scope in it and if you creaete variables for that scope then it would become local to that scope ie.. it can be used only in that scope ie like local variables in called function in java.
    When you have an exception and when you try to catch the exception in the Catch block , you need to throw the catch variable and if you are using catch all block ,then there is no need for throwing but in both the cases you need to set the fault variable.Fault variable with the corresponding message has to be created earlier before assigning any values to it .
    Ideally Fault variables are kept global because some times you may require to propogate your fault to your parent scope ,it depends on your need .

  • Cfm template updating cfc variable scope

    Don't know if anybody's run into this before, but I ran into a strange issue with the variable scope in a cfc.  Basically, I have some application settings stored in a database table, and then I have a cfc saved to application scope in which I store the contents of the table in a variable scope query.  Within the cfc, I have a getter function that preforms a query of queries to pull the data I need.  I then have an admin screen within the application to update the settings.
    This is (very generally) what my cfc looks like:
    <cfcomponent  name="settings.cfc">
         <cffunction name="init" returntype="settings">  
              <cfset setAppSettings() />  
              <cfreturn this />  
         </cffunction>  
         <cffunction name="setAppSettings">  
              <cfquery name="variables.qrySettings" datasource="#application.dsn#">  
                   SELECT *
                   FROM SETTINGS
              </cfquery>  
         </cffunction>  
         <cffunction name="getAppSettings" returntype="query">  
              <cfargument name="id" />
              <cfset var local = structNew() />  
              <cfquery name="local.qryResult" dbtype="query">  
                   SELECT *
                   FROM variables.qrySettings
                   WHERE ID = <cfqueryparam value="#arguments.id#" cfsqltype="cf_sql_numeric" />  
              </cfquery>  
              <cfreturn local.qryResult />  
         </cffunction>  
    </cfcomponent>
    In onApplicationStart in Application.cfc, I have this line:
    <cfset  
    application.objSettings = createObject("component","settings").init() />

    Sorry, accidentally posted before I was done...
    Basically, the problem is that I have an admin screen that updates the settings.  I call the getter function in a cfm template, and I save the result to a variable called variables.qrySettings (same name as in the cfc) like this - <cfset variables.qrySettings = application.objSettings.getAppSettings(url.id) />.  For some reason, this seems to overwrite variables.qrySettings in the cfc.  Any ideas????

Maybe you are looking for