How to lock/unlock a resource? - language-agnostic

First 2 parts of this query has been addressed in link and further would like to understand more about third part before implementation.
Part III (3 points)
Implement a "lockable" doubly-linked list ADT: a list in which any node can be "locked." A locked node can never be removed from its list. Any attempt to remove a locked node has no effect (not even an error message). Your locked list classes should be in the list package alongside DList and DListNode.
First, define a LockDListNode class that extends DListNode and carries information about whether it has been locked. LockDListNodes are not locked when they are first created. Your LockDListNode constructor(s) should call a DListNode constructor to avoid code duplication.
Second, define a LockDList class that extends DList and includes an additional method
public void lockNode(DListNode node) { ... }
that permanently locks "node".
Your LockDList class should override just enough methods to ensure that
(1) LockDListNodes are always used in LockDLists (instead of DListNodes), and
(2) locked nodes cannot be removed from a list.
WARNING: To override a method, you must write a new method in the subclass with EXACTLY the same prototype. You can’t change a parameter’s type to a subclass. Overriding won’t work if you do that.
Your overriding methods should include calls to the overridden superclass methods whenever it makes sense to do so. Unnecessary code duplication will be penalized.
It is important to understand locking and unlocking a DListNode without using any existing Java package. With an approach of, boolean flag; being member of LockDListNode to represent lock/unlock status, setting of this flag is non-atomic. Because, if i set flag = true; this set operation could be a multi-line instruction at byte code level.
Once this clarification that became a bottleneck to implement lock/unlock is resolved, Inheritance and override stuff could be taken care easily after this.
My question:
Can you suggest an approach to implement lock/unlock feature on DListNode?
Note: This query has nothing to do with knowledge of Java.

The new class LockDListNode will extend DListNode. Now you need to understand inheritance. DListNode should have an delete operation method you need to override that method not not do anything. See the code template below:
public class DListNode {
public DListNode{
}
public void delete(){
// TODO some delete code here
}
}
public class LockDListNode extends DListNode {
public LockDListNode{
super();
}
#override
public void delete(){
// DO nothing here
}
}
Now if you do
DListNode unableToDeleteNode = new LockDListNode();
unableToDeleteNode.delete();
You created an object of LockDListNode and call delete method it will call the delete for the LockDListNode and not DListNode.

Related

AS3: inline way to write get and set?

I was reading a tutorial and the user there was starting setters and getters like so
function get f():Number;
function set f(value:Number):void;
inside an interface, then saving it in the main file inside a variable
var testNode:INode;
and referencing them as
testNode.f;
I thought this was really handy, specially for when you have a lot of variables. Instead of having to create two functions for each private value.
However, I tried to do the same without instancing the get and set inside an interface (because I had no need for this) and I get an error saying the function doesn't have a body.
Why is that? Is there any way to write get and set in such a clean, short manner? So far I've been writing these as
public function get someVar():SomeClass {
return _someVar;
}
public function set someVar(newValue:SomeClass):void {
_someVar = newValue;
}
but it's a bit of a hassle when I have several private variables.
An interface is just a model for your class, it does not allows you to skip the definition of a function (or a getter/setter). You must declare the getter and the setter in any class implementing your interface. What you are looking for is an extension (inheritage).
If you define a class Mother.as with a getter and a setter, the class Child.as which extends Mother.as doesn't need to redefine the getter and setter.
Furthermore, if you don't plan on writing anything else inside the getter and setter, you should use a public variable. These are less resource consuming than useless get/set.

MVC3 ImportMany on Constructor Parameter for Exported Controller

I have a controller that is exported using MEF and loaded by the Controller factory.
[Export(Controller)]
public class MyController : Controller
{
private IRepository MyRepsoitory;
[ImportMany]
public IEnumerable<MyImportedItem> TestImportItems {get;set;}
public MyController([ImportMany]IEnumberable<MyImportedItem> items, [Import]IRepository repository)
{
// items here is always null
// However if I grab the container that the ControllerFactory used and tell it ComposeParts on this the TestImportItems will be filled with 50+ items
// repository however is instantiated appropriately.
GlobalItems.Container.ComposeParts(this);
//Now TestImportItems if filled but my items parameter alway null... how do I get constructor to fill
}
}
So MEF creates MyController but only creates the repository and sends null for the ImportMany even though it can fill the property later with the same Container.
What's also odd is if I do something that breaks one of the items the creation of MyConroller breaks in ControllerFactory.. as if it checks that is has parts for the constructor but never pushes them to the IEnumerable parameter.
What am I missing?
Obviously I have the parts available if the same Container works for .ComposingParts on (this) (and I reflected the catalog which has appropriate import/export Parts available at time of creating the Controller.
I could rewrite my class to use the filled Property but I would really like my importing constructor to get a filled collection.
UPDATE:
If I add a simple wrapper class for the import many MEF will load the [ImportMany] parameter.
So the following will fill the IEnumerable for me...
public MyController(TestImportClass test, [Import]IRepository repository)
{
//test.Items != null
}
public class TestImportClass
{
public IEnumberable<MyImportedItem> Items {get;set;}
[ImportingConstructor]
public TestImportClass([ImportMany]IEnumberable<MyImportedItem> items)
{
this.Items = items;
}
}
I am using a "Convention" system in my actual code to mark the Controller for Export. Maybe for some reason that is causing MEF to not understand the Import on initial Constructor Parameter? If that were the case though i am not sure why my IRepository always gets filled?
When you call ComposeParts, you pass objects which have already been constructed. It's not possible to call the constructor again on an existing object. (And in this case if you did you'd end up with infinite recursion). So ComposeParts doesn't satisfy constructor imports.
If your controller is pulled from the container some other way, and you put an ImportingConstructorAttribute on the constructor, the constructor imports should be satisfied.
Probably the convention system you are using doesn't support ImportMany in constructor arguments. Presumably the convention isn't applying to TestImportClass which is why the ImportMany works on that constructor.
We plan to have official convention model support in the next version of MEF, and we should be shipping a new codeplex release with a preview of this support soon.

Why can't an object of abstract class be created?

Here is a scenario in my mind and I have googled, Binged it a lot but got the answer like
"Abstract class has not implemented method so, we cant create the object"
"The word 'Abstract' instruct the compiler to not create an object of the class"
But in a simple class where we have all virtual method, able to create an object???
Also, we can define different access modified to Abstract class constructor like private, protected or public.
My search terminated to this question:
Why we can't create object of an Abstract class?
An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.
An abstract class has a protected constructor (by default) allowing derived types to initialize it.
For example, the base-type Stream is abstract. Without a derived type where would the data go? What would happen when you call an abstract method? There would be no actual implementation of the method to invoke.
Because it's abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.
Take for example an "Animal" abstract class. There's no such thing as a "pure" animal - there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn't be able to instantiate plain Animal - that's just a basic template. And there's certain functionality that all animals share, such as "makeSound()", but that can't be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?
It's intended to be used as a base class.
http://msdn.microsoft.com/en-us/library/sf985hc5(VS.71).aspx
The abstract modifier can be used with
classes, methods, properties,
indexers, and events.
Use the abstract modifier in a class
declaration to indicate that a class
is intended only to be a base class of
other classes.
Abstract classes have the following
features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Abstract classes should have at least one virtual method or property that has no implementation. This is marked with the abstract keyword. Inheriting classes must provide an implementation if they are not abstract themselves. You cannot create an instance of an abstract class because it does not have a complete implementation. If it does, it should not be marked abstract in the first place.
As an addition to the other answers, you may not be able to create an instance of the abstract class, but you can certainly refer to instances of derived types through the abstract type and use methods or properties that are defined within the abstract base.
abstract class A
{
public abstract void D();
public void E() { }
}
class B : A
{
public override void D() { }
}
class C : A
{
public override void D() { }
}
...
A a = new B();
a.D();
a.E();
List<A> list = new List<A>() { new B(), new C() };
Simply speaking, an abstract class is like a shell of a class. Not all the methods have implementations, something like a circuit with some wire segments missing. While the majority of it may be constructed, it is up to the users to stick in the wires and resistors in those segments as they see fit.
As to why Java won't let you create it, part of it is just a failsafe (many abstract classes will function just fine without any additions as long as you don't call unimplemented methods).
If we have a class containing pure virtual function then the class is abstract. If we will create an object of the abstract class and calls the method having no body(as the method is pure virtual) it will give an error. That is why we cant create object of abstract class.
We cannot create object for abstract class bcoz ,mostly abstract class contain "abstract methods" ,so abstract methods are incomplete methods.so we cannot estimate the memory of those methods how much they are going to occupy .This is one of the reason why we cannot create object for abstract class.
Here is a similar StackOverflow question. In short, it is legal to have a public constructor on an abstract class. Some tools will warn you that this makes no sense.
Whats the utility of public constructors in abstract classes in C#?
Actually when we create an object of a normal class we use Constructor to allocate the memory
for that object like
myclass obj=new myclass();
Here using constructorr clr identifies how much memory the object needed depending upon the instance variabless and methods. But in case of abstract classes we cant predict the amount of memory required as we dont implement the abstract methods so its not possible to create object.
When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.
Source : Study Tonight
The reference studytonight :
When we create a pure virtual function in Abstract class, we reserve a
slot for a function in the VTABLE(studied in last topic), but doesn't
put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler
will not let the creation of object for such class and will display an
errror message whenever you try to do so.
Sorry guys...
You can Create object for an abstract class, if and only if that abstract class does not contains any abstract method.
Here is my Example. Copy it and compile and run.
abstract class Example {
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo {
public static void main(String[] args) {
Example ob = new Example(){};
ob.display();
}
}
So your answer is yes, we can create object for abstract class if it's no Abstract Method.
Check my program.
I don't agree with the accepted answer. The reason is that we can have body for pure virtual function.
The answer is that :
When we create a pure virtual function in the class, we reserve a slot for a function in the VTABLE, but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an error message whenever you try to do so.
we can create object for abstract class like this also...
public class HelloWorld
{
public static void main(String args[])
{
Person p = new Person()
{
void eat()
{
console.writeline("sooper..");
}
};
p.eat();
}
}
abstract class Person
{
abstract void eat();
}
every body is writing dat abstract class has some virtual function which has not defined. for dat reason we cant create object, but abstract class is a class with the key word 'abstract' which may or may not have abstract method. i think it is a concept, it does not take any memory for dat. so if we can create an object den a memory will be created which is not possible, for dat reason we can't create object of an abstract class bt we can create reference of it which does not occupy any memory location.

Design pattern to use instead of multiple inheritance

Coming from a C++ background, Im used to multiple inheritance. I like the feeling of a shotgun squarely aimed at my foot. Nowadays, I work more in C# and Java, where you can only inherit one baseclass but implement any number of interfaces (did I get the terminology right?).
For example, lets consider two classes that implement a common interface but different (yet required) baseclasses:
public class TypeA : CustomButtonUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
public class TypeB : CustomTextUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
Both classes are UserControls so I cant substitute the base class. Both needs to implement the DoMagic function. My problem now is that both implementations of the function are identical. And I hate copy-and-paste code.
The (possible) solutions:
I naturally want TypeA and TypeB to share a common baseclass, where I can write that identical function definition just once. However, due to having the limit of just one baseclass, I cant find a place along the hierarchy where it fits.
One could also try to implement a sort of composite pattern. Putting the DoMagic function in a separate helper class, but the function here needs (and modifies) quite a lot of internal variables/fields. Sending them all as (reference) parameters would just look bad.
My gut tells me that the adapter pattern could have a place here, some class to convert between the two when necessary. But it also feels hacky.
I tagged this with language-agnostic since it applies to all languages that use this one-baseclass-many-interfaces approach.
Also, please point out if I seem to have misunderstood any of the patterns I named.
In C++ I would just make a class with the private fields, that function implementation and put it in the inheritance list. Whats the proper approach in C#/Java and the like?
You can use the strategy pattern or something like it to use has a (composition) instead of is a (inheritance):
public class TypeA : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class TypeB : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class Magical : IMagician {
public void DoMagic() {
// shared magic
}
}
There are other ways to instantiate your private IMagician members (such as passing them as a param via constructor) but the above should get you started.
In .Net, you can have extension methods apply to interfaces. It's really neat when it's possible, and applicable for you because it's a rare way to apply a common implementation to an interface. Certainly consider it, but it might not work for you since you say that DoMagic works with a lot of Private members. Can you package these private variables internal possibly? This way the extension method could access them.
Have the common functionality in another class. If there's a logical place to put this common functionality, pass your objects to this other class method (perhaps this is UI functionality, and you already have a UI helper . . .). Again, can you expose the private data with an internal/public property? (Security/encapsulation is a concern in all this of course. I don't know if your classes are for internal use only or will be exposed publicly.)
Otherwise, pass a separate functionality class (or specific function pointer) into the interface-defined method. You would have to have a little bit of duplicated code to pass your private variables to this external function reference, but at least it wouldn't be much, and your implementation would be in one place.
We might be making this too complicated. It won't make you feel all object-oriented when you go to sleep tonight, but could you have a static routine in your library somewhere that all IMagician implementers call?
In the end, Adapter might indeed be what you're looking for. Less likely but still worth consideration is the Decorator pattern.
If nothing seems particularly good, pick what feel best, use it a couple times, and rearrange tomorrow. :)
Replace inheritance with composition.
Move your 'common' function to separate class, create an instance of that class, and insert it to TypeA object and to TypeB object.
Your gut is correct in this case. The Adapter pattern is what you're looking for.
DoFactory has good .NET examples (that should be pretty close to their Java counterparts as well):
Adapter Design Pattern in C# and VB.NET
The composite pattern is meant for complex objects, that means the focus is on one object being made up of other objects. The strategy-pattern can be regarded as a special case of that, but a strategy does not have to be an object. I think this would apply more to your case. Then again, this heavily depends on the nature of what DoMagic() does.
public interface IMagician{ /* declare here all the getter/setter methods that you need; they will be implemented both in TypeA and TypeB, right? */ }
public static class MyExtensions {
public static void doMagic(this IMagician obj)
{
// do your magic here
}
}
Now, the problem is if you REALLY need to use private properties/methods (as opposed to "internal" ones), this approach won't work. Well, actually, you may be able to do your magic if you can read those properties through reflection, but even if it works, it's a rather ugly solution :)
[Note that "doMagic" will automatically appear to become a part of TypeA and TypeB,simply because you implement IMagician - there is no need to have any implementation there ]
You can use composition to have magician as a property of typeA and typeB
class Magician : IMagician
{
public void DoMagic()
{}
}
Class TypeA : CustomButtonUserControl
{
//property
Magician magicianInTypeA
}
Class TypeB : CustomTextUserControl
{
//property
Magician magicianInTypeB
}
abstract class Magical: CustomButtonUserControl
{
public void DoMagic()
{
// ...
}
}
public class TypeA : Magical
{
}
public class TypeB : Magical
{
}

Copy constructor using private attributes

My first question here so be gentle.
I would like arguments for the following code:
public class Example {
private String name;
private int age;
...
// copy constructor here
public Example(Example e) {
this.name = e.name; // accessing a private attribute of an instance
this.age = e.age;
}
...
}
I believe this breaks the modularity of the instance passed to the copy constructor.
This is what I believe to be correct:
public class Example {
private String name;
private int age;
...
// copy constructor here
public Example(Example e) {
this.setName(e.getName());
this.setAge(e.getAge());
}
...
}
A friend has exposed a valid point of view, saying that in the copy construct we should create the object as fast as possible. And adding getter/setter methods would result in unnecessary overhead.
I stand on a crossroad. Can you shed some light?
Access is class based, not object based.
The rationale for making a member private is that the ther classes should not know the details of implementation outside of well defined API, so as to make the rest of the system tolerate the change of implementation. However, the copy constructor is not "the rst of the system" - it is your own class.
The first example is not copying a private attribute of an instance, because they are bot instances of the same class.
However, if you add access methods/properties, any decent compiler should optimise them away to simple "inlines", in which case the second method is cleaner code (all accesses go via your access function) but both approaches should end us as be equally efficient (probably identical) memberwise copies.
If you really want a copy constructor to be efficient, then a lower level binary copy will be faster than a memberwise copy. But significantly "dirtier".
In general I prefer to access all member fields via properties/accessors as that encapsulates them better, allowing you to change the underlying implementation/storage of a field without having to change any of the code that accesses it, except for the property/accessor itself.