linked list MutableString homework inheriting vs delegation - string

I have a linked list question that stems from this homework prompt I am about to post. it might help with the answer:
Specifics
The Java String class is immutable (you cannot change the contents). This is sometimes a hindrance to what you want to do with a string (i.e. make changes to the existing string). So, for this assignment you will create a class called MutableString. NOTE/DISCLAIMER: The Java API does have a class StringBuffer, which is mutable, but for the intents and purposes of this assignment we'll pretend we don't know about it ;-)
An object of the MutableString class contains the following operations/behaviors -- which means the class itself must contain the following methods:
Character charAt(int index): returns the Character at the specified index in the string -- if the index lies outside the string, throw a MutableStringIndexOutOfBoundsException (you must write this class)
void set(int index, Character ch): replaces the existing Character at the specified location -- if the index lies outside the string throw a MutableStringIndexOutOfBoundsException
void add(int index, Character ch): creates a new spot in the list for the Character at the index specified -- if the index lies outside the string throw a MutableStringIndexOutOfBoundsException
Character remove(int index): removes the Character at specified index -- if the index lies outside the string, throw a MutableStringIndexOutOfBoundsException
boolean remove(Character ch): removes the first occurrence (starting from the beginning of the MutableString) of the Character -- if the Character is not found, return false
boolean removeAll(Character ch): removes all occurrences of the specified Character -- if Character is not found, return false
void toUpper(): converts the current string to all upper case
void toLower(): converts the current string to all lower case
MutableString substring(int start, int finish): returns a string starting at the Character specified by start and concluding with the Character specified by finish -- if start or finish is outside the the string, throw a MutableStringIndexOutOfBoundsException
char [] toCharArray(): returns a char array containing all the characters in the string -- be sure and handle all cases
int length(): reports/returns the length of the string
String toString(): returns a String containing all the Characters
String toReverseString(): returns a String containing all the Characters in reverse order -- you must utilize recursion to accomplish this task
int compareTo(MutableString that): allows comparison of two MutableString objects -- this implies you will implement the Comparable interface for your MutableString class
void sort(): alphabetizes the letters in case-insensitive fashion in ascending order -- you must write the code for this sort (no API calls are allowed)
You must use a linked list to represent the characters of the string (you must write the
LinkeList class). Your LinkedList class should contain fundamental operations for updating and modifying the list. With this in mind, implement the List interface in the Java API. For methods that you deem unnecessary for your LinkedList's functionality, stub those methods out and throw an Exception that contains information about what method was called and that it has not been implemented. NOTE: Make sure your LinkedList class does not do anything MutableString specific. Feel free to use the following stubbed out LinkedList class for your assignment. It may not contain all the methods you will need, but it does contain the methods from the List interface from the Java API.
MutableString must utilize the LinkedList behaviors (methods) wherever possible (don't write code in MutableString that does the same thing as something in the LinkedList class). Thus your MutableString will contain a field that is a reference to a LinkedList object. BTW, this concept is known as delegation, a very important idea in software engineering and design. Do NOT design MutableString so that it inherits from LinkedList.
Each Node of your MutableString should contain a Character -- note that this does not mean the reference to the data in your node class should/must be type Character -- that would make your LinkedList class specific to MutableString, and we don't want that in this case.
**the part I dont understand is the paragraph 2 above that talks about inheriting from the linked list class. I was always used to writing something like public class MutableString extends LinkedList but we cant do that and I dont really know how to start writing this mutablestring class without inheriting from the class. Help on explaining how to do it and the difference would be awesome. thanks.
Im not very good at linked lists so bare with this question :)
**

It says that you should use delegation instead of inheritance.
For difference between delegation and inheritance, check this out. It explains with an example.

Related

Using Roslyn, if I have an IdentifierNameSyntax, can I find the member type it refers to (field, property, method...)

I am attempting to use the Roslyn SDK and StackExchange.Precompilation (thank you!) to implement aspect-oriented programming in C#6. My specific problem right now is, starting with an IdentifierNameSyntax instance, I want to find the "member type" (method, property, field, var, etc.) that the identifier refers to. (How) can this be done?
Background:
The first proof-of-concept I am working on is some good old design-by-contract. I have a NonNullAttribute which can be applied to parameters, properties, or method return values. Along with the attribute there is a class implementing the StackExchange.Precompilation.ICompileModule interface, which on compilation will insert null checks on the marked parameters or return values.
This is the same idea as PostSharp's NonNullAttribute, but the transformation is being done on one of Roslyn's syntax trees, not on an already compiled assembly. It is also similar to Code Contracts, but with a declarative attribute approach, and again operating on syntax trees not IL.
For example, this source code:
[return: NonNull]
public string Capitalize([NonNull] string text) {
return text.ToUpper();
}
will be transformed into this during precompilation:
[return: NonNull]
public string Capitalize([NonNull] string text) {
if (Object.Equals(text, null))
throw new ArgumentNullException(nameof(text));
var result = text.ToUpper();
if (Object.Equals(result, null))
throw new PostconditionFailedException("Result cannot be null.");
return result;
}
(PostconditionFailedException is a custom exception I made to compliment ArgumentException for return values. If there is already something like this in the framework please let me know.)
For properties with this attribute, there would be a similar transformation, but with preconditions and postconditions implemented separately in the set and get accessors, respectively.
The specific reason I need to find the "member type" of an identifier here is for an optimization on implementing postconditions. Note in the post-compilation sample above, the value that would have been returned is stored in a local variable, checked, and then the local is returned. This storage is necessary for transforming return statements that evaluate a method or complex expression, but if the returned expression is just a field or local variable reference, creating that temporary storage local is wasteful.
So, when the return statement is being scanned, I first check if the statement is of the form ReturnKeyword-IdentifierSyntaxToken-SemicolonToken. If so, I then need to check what that identifier refers to, so I avoid that local variable allocation if the referent is a field or var.
Update
For more context, check out the project this is in reference to on GitHub.
You'll need to use SemanticModel.GetSymbolInfo to determine the symbol an identifier binds to.
Use SemanticModel.GetTypeInfo.Type to obtain the TypeInfo and use it to explore the Type

Why doesn't calling repr on type objects work as expected?

First, let me say that I agree that eval(repr(some_string)) is potentially a bad idea. But it is a thing that exists, and I have a specific question about it.
Why doesn't this work?
my_type = int
my_type_str = repr(int)
my_type_from_str = eval(my_type_str)
To clarify, I know specifically why the eval call fails. The command repr(int) produces a string which cannot be automatically interpreted. I guess my issue is that this isn't behaving as I expect... so either my expectation is faulty or the implementation is faulty. Which is it?
Side Note
There are some tricks that can be used to get around this default behavior, some obvious, some not. For instance, this:
my_type = int
my_type_str = my_type.__name__
my_type_from_str = eval(my_type_str)
assert my_type is my_type_from_str
This sets off my "hack" alert hardcore, and I don't like it (or other similar hacks, for instance parsing the string "<class 'int'>" with some home made function).
The documentation explains:
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a repr() method.
(emphasis mine)
So, it doesn't say that repr must always return valid Python code - sometimes it's not the case. Just another argument for not relying on it.

Does groovy ignore the type of null values in method signatures?

To illustrate the following example I created a litte spock test (but it's about groovy itself, not spock):
void "some spock test"() {
given: String value = null
expect: someMethod(value) == 3
}
int someMethod(String s) {
return 3
}
int someMethod(Map s) {
return 5
}
There are two methods who's signatures only differ by the type of the given parameter. I thought that when I give it a null value that is explicitly typed as a string, the string-method will be called.
But that doesn't happen; the test fails, because the map-method is called! Why?
I guess groovy ignores the type and treats all nulls the same. There seems to be some kind of priority of types: When I use Object instead of Map as the parameter type of the wrong-method, its all the same, but when I for instance use Integer, the test succeeds.
But than again: If groovy really ignores the type of nulls, why can the following fix the original test:
expect: someMethod((String) value) == 3
If you read my answer to the question Tim already mentioned you will see that I talk there about runtime types. The static type plays normally no role in this. I also described there how the distance calculation is used and that for null the distance to Object is used to determine the best fitting method. What I did not mention is that you can force method selection by using a cast. Internally Groovy will use a wrapper for the object, that also transports the type. Then the transported type is used instead. But you surely understand, that this means a one additional object creation per method class, which is very inefficient. Thus it is not the standard. In the future Groovy maybe change to include that static type information, but this requires a change to the MOP as well. And that is difficult

how to initialize PriorityQueue

I'm reading the API http://docs.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html. I'm still a bit lost.
Which is the right way to initialize?
PriorityQueue(Caller caller_pq);
or
static PriorityQueue<Caller> caller_pq;
caller_pq = new PriorityQueue<Caller>();
If caller_pq is the variable you want to hold your PriorityQueue then the second one --
static PriorityQueue<Caller> caller_pq;
caller_pq = new PriorityQueue<Caller>();
-- is correct.
It's hard to tell what you mean by your first option PriorityQueue(Caller caller_pq). If you're intending to create a PriorityQueue containing elements of type Caller (which is what I think you're intending), then no, that won't work.
If Caller implements Collection or extends PriorityQueue then it will make a PriorityQueue containing the elements in caller_pq (as long as you precede it with new).

Pass a dynamic variable in a static parameter of a method in C# 4

This is what I am trying to do:
public void method(int myVal, string myOtherVal)
{
// doing something
}
dynamic myVar = new SomeDynamicObjectImplementer();
method(myVar.IntProperty, myVar.StringProperty);
Note that my properties are also DynamicObjects. My problem is that the TryConvert method is never called and that I get a runtime error saying the method signature is invalid.
The following is working great:
string strVar = myVar.StringProperty;
int intVar = myVar.IntProperty;
And I would like to avoid
method((int)myVar.IntProperty, (string)myVar.StringProperty);
Is it possible to override something in DynamicObject to allow this? (or something else)
Thank you
The problem is your assumption that it will try a dynamic implicit convert on arguments of an dynamic invocation to make a method call work, this is not true.
When your arguments aren't statically typed, it will use the runtime type to find the best matching method (if the runtime type matches the static rules for implicit conversion to the argument type this will work too), since your your IntProperty,StringProperty seem to be returning a DynamicObject rather than an Int and a String or something that could statically be converter implicitly, this lookup will fail.
If SomeDynamicObjectImplementer could actually return an Int for IntProperty and a String for StringProperty your method call for without casting would actually work. It's also probably a better dynamic typing practice if you data type is based on the actually type of data rather than usage using try convert. You could add actually implicit convert methods for every possible type that you could return to that returned DynamicObject type, but that could cause strange resolution issues to depending on how much you are overloading.
However, another option to keep your dynamic implementation the same is to mix a little controlled static typing in, you can use ImpromputInterface (in nuget) to put an interface on top of a dynamic object, if you do that then the TryConvert method would be called on your returned DynamicObjects.
public interface ISomeStaticInterface{
int IntProperty {get;}
string StringProperty {get;}
}
...
var myVar = new SomeDynamicObjectImplementer().ActLike<ISomeStaticInterface>();
method(myVar.IntProperty, myVar.StringProperty);
Instead of using myVar.IntProperty can't you just put them in variables first, like you already did, and then use then for your method?
so method(intVar , strVar); seems fine. At least more elegant than casting.
Of course, if you're already certain your object will have IntProperty and StringProperty, why not just make an actual object with those properties instead?
Why are you doing the cast?
method(myVar.IntProperty, myVar.StringProperty);
should compile.
If the two properties must be the types suggested by the names then they shouldn't be dynamic.

Resources