Categories
discuss

JavaScript Classes and Variable Scope

I’m relatively new to JS and I’m having issues properly emulating OOP principles.

I guess I have two questions. Question the first is regarding the many ways to declare variables.

Say I have a class:

function clazz(a)
{
    this.b = 2;
    var c = 3;
    this.prototype.d = 4; // or clazz.prototype.d = 4?
}

var myClazz = new clazz(1); 

Am I correct in the following assessments:

a is a private variable that is instance specific (i.e. different instances of clazz will have unique and independent variables ‘a’). It can be accessed from within clazz as: ‘a’.

b is a public variable that is instance specific. It can be accessed from within clazz as ‘this.b’ and from outside clazz as ‘myClazz.b’.

c is a private variable that is static, or class specific (i.e. different instances of clazz will share the same ‘c’ variable). It can be accessed from within any instance of clazz as ‘c’ and changes in instance of clazz are reflected in all instances of clazz.

d is a public variable that is static/class specific. It can be accessed from anywhere via ‘clazz.prototype.d’ or ‘myClazz.prototype.d’.

The overall issue I have with my understanding of the variable scheme is that there’s no way to declare a private variable that is NOT static (i.e. a unique version for every instance of the class).

The second question is with respect to different types of class declarations.

I’ve been using:

var MySingleton = new function() {...};

to create singletons. Is this correct? I’m also unsure as to the effect of the “new” keyword in this situation as well as appending () function braces to the end of the declaration as so:

var MySingleton = new function() {...}();

I’ve been using this pattern to declare a class and then instantiate instances of that class:

function myClass() {...};
var classA = new myClass();
var classB = new myClass();

Is this the proper method?

Answer

You are right for a and b:

a is an argument, available only within the scope of the constructor function.

bis a public instance variable, available on all instances created with that constructor function.

c is a private variable, accessible only within the constructor function.

The d declaration is invalid, because the prototype object is meant to be used only on constructor functions, like Clazz.prototype.d = 3;, if you do it like this, the variable will be shared, but you can assign a value on an specific instance, and the default value will be shadowed (through the prototype chain).

For “private variables” you can use the way you declare c, for example:

function Clazz(){
    var c = 3; // private variable

    this.privilegedMethod = function () {
      alert(c);
    };
}

Privileged methods, are public, but they can access “private” variables declared inside the constructor function.

For creating singletons, the easiest way is maybe to use an object literal, like:

var myInstance = {
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  }
};

And if you want private members on your singleton instance, you can:

var myInstance = (function() {
  var privateVar = '';

  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // all private members are accesible here
    },
    publicMethod2: function () {
    }
  };
})();

This is has been called the module pattern, it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.

More info:

Edit: About the syntax you post:

var mySingleton = new (function() {
  // ...
})();

By using the new operator, you are declaring and using in one step an “anonymous constructor function“, which will generate a new object instance, it is valid but I personally would prefer the “module” pattern approach, to create my own object instance (and avoid new).

Also, reading new function () {}, I think that is not really intuitive and may create confusion, if you don’t understand well how the new operator works.

About the parentheses, they are optional, the new operator will call the function constructor without parameters if you don’t add them (see ECMA-262, 11.2.2).

Categories
discuss

Java Collections.sort – help me remove the unchecked warning

List<Question> questions = new ArrayList<Question>();
questions.addAll(getAllQuestions()); //returns a set of Questions
Collections.sort(questions, new BeanComparator("questionId")); //org.apache.commons.beanutils.BeanComparator

Under Java 1.5, the above works fine except that the ‘new BeanComparator(“questionId”)’ generates an unchecked warning. I do not like warnings. Is there a way I can provide the BeanComparator a type, or do I have to use @SuppressWarnings("unchecked")?

Answer

Options are:

  • Change BeanComparator to implement Comparator<Question>. This is not a real option here, given it is a well-known external library class. People ain’t going to let you do it.
  • Fork and modify BeanComparator as above, giving it a different FQN.
  • Wrap the existing BeanComparator with a class that implements Comparator<Question>.
  • Change the type of questions to List<?>.
  • Add a suppress warnings annotation.
Categories
discuss

How do I implement a test framework in a legacy project

I’ve got a big project written in PHP and Javascript. The problem is that it’s become so big and unmaintainable that changing some little portion of the code will upset and probably break a whole lot of other portions.

I’m really bad at testing my own code (as a matter of fact, others point this out daily), which makes it even more difficult to maintain the project.

The project itself isn’t that complicated or complex, it’s more the way it’s built that makes it complex: we don’t have predefined rules or lists to follow when doing our testing. This often results in lots of bugs and unhappy customers.

We started discussing this at the office and came up with the idea of starting to use test driven development instead of the develop like hell and maybe test later (which almost always ends up being fix bugs all the time).

After that background, the things I need help with are the following:

  1. How to implement a test
    framework into an already existing
    project? (3 years in the
    making and counting)

  2. What kind of frameworks are there
    for testing? I figure I’ll need one
    framework for Javascript and
    one for PHP.

  3. Whats the best approach for testing
    the graphical user interface?

I’ve never used Unit Testing before so this is really uncharted territory for me.

Answer

G’day,

Edit: I’ve just had a quick look through the first chapter of “The Art of Unit Testing” which is also available as a free PDF at the book’s website. It’ll give you a good overview of what you are trying to do with a unit test.

I’m assuming you’re going to use an xUnit type framework. Some initial high-level thoughts are:

  1. Edit: make sure that everyone is is agreement as to what constitutes a good unit test. I’d suggest using the above overview chapter as a good starting point and if needed take it from there. Imagine having people run off enthusiastically to create lots of unit tests while having a different understanding of what a “good” unit test. It’d be terrible for you to out in the future that 25% of your unit tests aren’t useful, repeatable, reliable, etc., etc..
  2. add tests to cover small chunks of code at a time. That is, don’t create a single, monolithic task to add tests for the existing code base.
  3. modify any existing processes to make sure new tests are added for any new code written. Make it a part of the review process of the code that unit tests must be provided for the new functionality.
  4. extend any existing bugfix processes to make sure that new tests are created to show presence and prove the absence of the bug. N.B. Don’t forget to rollback your candidate fix to introduce the bug again to verify that it is only that single patch that has corrected the problem and it is not being fixed by a combination of factors.
  5. Edit: as you start to build up the number of your tests, start running them as nightly regression tests to check nothing has been broken by new functionality.
  6. make a successful run of all existing tests and entry criterion for the review process of a candidate bugfix.
  7. Edit: start keeping a catalogue of test types, i.e. test code fragments, to make the creation of new tests easier. No sense in reinventing the wheel all the time. The unit test(s) written to test opening a file in one part of the code base is/are going to be similar to the unit test(s) written to test code that opens a different file in a different part of the code base. Catalogue these to make them easy to find.
  8. Edit: where you are only modifying a couple of methods for an existing class, create a test suite to hold the complete set of tests for the class. Then only add the individual tests for the methods you are modifying to this test suite. This uses xUnit termonology as I’m now assuming you’ll be using an xUnit framework like PHPUnit.
  9. use a standard convention for the naming of your test suites and tests, e.g. testSuite_classA which will then contain individual tests like test__test_function. For example, test_fopen_bad_name and test_fopen_bad_perms, etc. This helps minimise the noise when moving around the code base and looking at other people’s tests. It also has then benefit of helping people when they come to name their tests in the first place by freeing up their mind to work on the more interesting stuff like the tests themselves.
  10. Edit: i wouldn’t use TDD at this stage. By definition, TDD will need all tests present before the changes are in place so you will have failing tests all over the place as you add new testSuites to cover classes that you are working on. Instead add the new testSuite and then add the individual tests as required so you don’t get a lot of noise occurring in your test results for failing tests. And, as Yishai points out, adding the task of learning TDD at this point in time will really slow you down. Put learning TDD as a task to be done when you have some spare time. It’s not that difficult.
  11. as a corollary of this you’ll need a tool to keep track of the those existing classes where the testSuite exists but where tests have not yet been written to cover the other member functions in the class. This way you can keep track of where your test coverage has holes. I’m talking at a high level here where you can generate a list of classes and specific member functions where no tests currently exist. A standard naming convention for the tests and testSuites will greatly help you here.

I’ll add more points as I think of them.

HTH

Categories
discuss

Javascript disabled, short questions

Just some short Q regarding javascript and websites.

1- By javascript enabled, does it mean to have ‘sun java’ installed and enabled in the browser settings? Or does every browser have javascript enabled always?

2- If javascript is disabled, my website for example wouldn’t work at all, so what does major developers do in these situations, if the only way to achieve their goal is to use javascript?

3- Is ajax also disabled if javascript is disabled? Also, same for Jquery because its a javascript library ?

Thanks guys

Answer

  1. Sun’s Java is not the same thing as JavaScript. Java is an extension to the browser which user might or not have installed. JavaScript comes with browser and can be disabled by the user.

  2. Display a notice to the user that he/she should turn JavaScript on.

  3. Ajax and jQuery are Javascript, so yes, they’re disabled also.

Categories
discuss

Attributes.Add Onclick Event in c# code behind

I have two textboxes tbxProdAc & txtbxHowMany. I would like to write a bit of code in the code behind so that when I enter text in one, any text that may have been in the other is removed.

How would one go about achieving this and in which event should I place it?

I have tried to use

txtbxHowMany.Attributes.Add("onclick", "document.getElementById('tbxProdAC').innerText='';");

in the page load event but twithout success…should this be in the pre_init?

As you can probalby tell, complete novice at work here.

Answer

First off, make sure that when the page has been generated that the ID is still “tbxProdAC” if this is a .Net control, the ID would have been changed. In this case you can use a class.

Try the following, – This uses JQuery – you will need to include that

txtbxHowMany.Attributes.Add("onclick", "$('#tbxProdAC').val('');"); 

Add the following to the Head Section of your page.

 <script type="text/javascript" src="jquery.js"></script> 

And you can get the JQuery.Js file from here: http://docs.jquery.com/Downloading_jQuery#Download_jQuery

And Why: https://stackoverflow.com/questions/308751/why-use-jquery

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..