Could you create an object from a class named Trung.NguyenThe since NguyenThe isn't a method ?
In Java C# and Ruby, you cannot create variables with a . in the name.
// C# and Java
Object Trung.NguyenThe = "";
# Ruby
Trung.NguyenThe = ""
That variable name is illegal in all three languages.
If you want to do something similar to this, use an underscore _.
// C# and Java
Object Trung_NguyenThe = "";
# Ruby
Trung_NguyenThe = ""
First of all, objects do not have names. Classes and variables do.
So I'll assume you're asking about naming classes with periods (based on your last comment)...
The straight answer is "no", but one can emulate that using namespaces/packages or inner classes.
Namespace:
namespace Trung {
public class NguyenThe {}
}
// Usage:
namespace Whatever {
public class Client {
public main() {
var x = new Trung.NguyenThe();
}
}
}
Inner class:
namespace Whatever {
public class Trung {
public class NguyenThe {}
}
// Usage:
public class Client {
public main() {
var x = new Trung.NguyenThe();
}
}
}
(Note: This is C# code, but I'm sure the same could be done in Java. I guess Ruby has the same concepts also.)
In Ruby, there's no such thing as a class name. Classes are just objects like every other object which get assigned to variables just like any other variable.
Trung.NguyenThe is not a legal variable name, therefore this is impossible:
class Object
klass = Class.new do
def to_s; 'Hello' end
end
const_set :'Trung.NguyenThe', klass
# NameError: wrong constant name Trung.NguyenThe
end
You could, of course, create an object which responds to a NguyenThe message with a class and assign that object to a variable named Trung, but that's not what you are asking about:
klass = Class.new do
def to_s; 'Hello' end
end
(Trung = Object.new).define_singleton_method(:NguyenThe) { klass }
puts Trung.NguyenThe.new
# Hello
In C# and Java, periods are illegal in class names as well. C# has an escaping mechanism that allows you to use otherwise reserved words as names, but this mechanism doesn't make it possible to use illegal names, only reserved ones.
There are proposals for more symbolic freedom in Java names, but so far, they have not yet been implemented.
Sure. Create a package called Trung. Within this package create a class called NguyenThe.
Or are you assuming that Trung is already a class name?
Related
I understand in C# there is such thing as named parameters so that is a bit misleading. The question I have is what they should be called in general.
In my time using libraries in other languages I've sometimes run across predefined values that can be used within functions of a class.
object.myFunc(SPECIAL_VALUE);
It's usually named in all capitol letters and is a very specific value within the function. I figure it behaves much like a public static string but when I use this idea intellisense doesn't pick this up. Can someone inform me of the general name of this kind of parameter option and if they exist, pros and cons of using such a thing.
Thanks,
Normally, those kind of constants in C# are declared and cased like this...
public const String MyConstantThingHere = "Some value";
In Java, it would be more like...
public static final String MY_CONSTANT_THING_HERE = "Some value";
I would simply call these public class constants. See HERE.
Also, for reference: http://www.dofactory.com/reference/csharp-coding-standards
You can also use static imports to refer to them...
See here: static imports in c#
I'm not really sure, what you mean. The concept of named parameters in C# is shown in this example:
namespace Testconsole {
public class obj {
public int myFunc(int value1, int value2 = 4, int value3 = 8) {
return value1 + value2 + value3;
}
}
class Program {
static void Main(string[] args) {
obj adder = new obj();
Console.WriteLine(adder.myFunc(value1: 1, value3: 1));
Console.ReadLine();
}
}
}
Testconsole returns 6: value1 is set with '1', value3 is set with '1', value2 is missing and therefore filled with default value '4'.
Also it is possible to pass a public static String into a Function:
namespace Testconsole {
public class obj {
public String myFunc(String mySpecialValue) {
return "now I " + mySpecialValue;
}
}
class Program {
public static String SPECIAL_VALUE = "got it";
static void Main(string[] args) {
obj Learn = new obj();
Console.WriteLine(Learn.myFunc(SPECIAL_VALUE));
Console.ReadLine();
}
}
}
Console output:
Now I got it.
What you are referring to is a "constant." They serve two purposes:
They ensure that a value that has some meaning (a "special value", as you said) is declared in one place and re-used so that if it changes we change it in one place.
They make our code more readable. For example, we might want two always display the top four items from a list on a web page. And we might have an input that should always be four characters in length. If other people just read our code and see the number 4 here and there it might not be apparent what that number 4 means. We want our code to be as easy to understand as possible.
So when we declare
const int NUMBER_OF_ITEMS_TO_DISPLAY = 4
or
const string MAX_INPUT_LENGTH_SETTINGS_KEY = "maximumInputLength"
Then when we use those constants in our code other people can tell what they mean.
The opposite of using constants is called using "magic numbers" or "magic strings." They just appear in our code without context or explanation. It might just be value we arbitrarily picked, but declaring it as a constant gives it context and meaning.
The capital letters aren't required. They're just a convention that makes constants easy to recognize.
I come from a C# background, and that's probably the reason for my hesitation, but imagine we have the following scenario. We have a class that takes in some raw data, and then pushes it up to some external API. In the process of doing so, we need to process the data according to some business rules. The catch is, these business rules aren't always the same. In C#, I would use an interface for the "data processing" business rules, and then use different implementations at different times:
public interface IDataProcessor
{
object Process(object data);
}
public class SomeBuilder
{
private object _data;
private IDataProcessor _dataProcessor;
public SomeBuilder(object data, IDataProcessor dataProcessor)
{
_data = data;
_dataProcessor = dataProcessor;
}
public void Build()
{
var processedData = _dataProcessor.Process(_data);
//do the fun building stuff with processedData
}
}
In the above example, I would have different implementations of my IDataProcessor that process the data differently.
Now, in the Ruby world, my first inkling was to do something similar:
class SomeBuilder
def initialize(some_data, data_processor)
#some_date = some_date
#data_processor = data_processor
end
def build
processed_data = #data_processor.process(#some_data)
#do build logic
end
end
My issue is twofold: First, this somehow doesn't "feel" quite right in the Ruby ecosystem. e.g. is this the Ruby way? Second of all, if I were to go down this path, what would the data_processor look like? It feels like it should be a module, since it's just some behavior, but if it is just a module, how do I interchangeably use different modules in my SomeBuilder class?
Thanks in advance!
It feels like it should be a module
I don't know about that. Modules are used for injecting identical behavior into classes(or other modules), and you want different behavior.
how do I interchangeably use different modules in my SomeBuilder
class?
Instead of a compiler enforcing the rule that your interface class has a Process method, in ruby you will get a runtime error. So you can use any class you want in conjunction with your SomeBuilder class, but if the class doesn't have a Process method, then you will get a runtime error. In other words, in ruby you don't have to announce to a compiler that the class you use in conjunction with your SomeBuilder class must implement the IDataProcessor interface.
Comment example:
class SomeBuilder
def initialize(some_data)
#some_data = some_data
end
def build
processed_data = yield #some_data
puts processed_data
end
end
sb = SomeBuilder.new(10)
sb.build do |data|
data * 2
end
sb.build do |data|
data * 3
end
--output:--
20
30
You're on the right track. Ruby Modules and Classes can both be used. In this scenario, I would tend to have a DataProcessor module that wraps the various concrete implementations of the processors. So, that would give:
banana_processor.rb:
module DataProcessor
class Banana
def process(data)
# ...
end
# ...
end
end
apple_processor.rb:
module DataProcessor
class Apple
def process(data)
# ...
end
# ...
end
end
Then you instantiate the processor with:
processor = DataProcessor::Apple.new
Basically, the module DataProcessor "namespaces" your processor classes and more useful in larger libraries where you might have a name collision or if you're producing a gem that might get included in any number of projects where name collisions are possible.
Then for your Builder class
class SomeBuilder
attr_reader :data, :processor, :processed_data
def initialize(data, processor)
#data = data
#processor = processor
end
def build
#processed_data = #processor.process(#data)
# do build logic
end
...and used:
some_processor = DataProcessor::Apple.new
builder = SomeBuilder.new(some_data, some_processor)
builder.build
Combining ideas from other answers:
class DataProcessor
def initialize &blk
#process = blk
end
def process data
#process[data]
end
end
multiply_processor = DataProcessor.new do |data|
data * 10
end
reverse_processor = DataProcessor.new do |data|
data.reverse
end
This works just fine with your example SomeBuilder class.
This is sort of a happy medium between Michael Lang and 7stud's answers. All data processors are instances of one class, which allows you to enforce common behavior, and each processor is defined using a simple block, which minimizes code repitition when defining new ones.
Your interface has only a single method. An object with only a single method is isomorphic to a function/procedure. (And an object with some fields and a single method is isomorphic to a closure). Therefore, you would actually use a first-class procedure.
class SomeBuilder
def initialize(some_data, &data_processor)
#some_data, #data_processor = some_data, data_processor
end
def build
processed_data = #data_processor.(#some_data)
#do build logic
end
end
# e.g. a stringifier-builder:
builder = SomeBuilder.new(42) do |data| data.to_s end
# which in this case is equivalent to:
builder = SomeBuilder.new(42, &:to_s)
Actually, you would probably do the same thing in C# as well. (Plus, you probably should make it generic.)
public class SomeBuilder<I, O>
{
private I _data;
private Func<I, O> _dataProcessor;
public SomeBuilder(I data, Func<I, O> dataProcessor)
{
_data = data;
_dataProcessor = dataProcessor;
}
public void Build()
{
var processedData = _dataProcessor(_data);
//do the fun building stuff with processedData
}
}
// untested
// e.g. a stringifier-builder
var builder = new SomeBuilder(42, data => data.ToString());
In addition to 'var' (see my other post here), one of the things I really like about C# is that I can both declare, then initialize members of a class using braces, like this...
var reallyLongFooVarName = new ReallyLongFooClassName(){
Name = "I'm an instance of Foo",
ID = 23 };
or even on one line, like this...
var longFooVarName = new ReallyLongFooClassName(){ Name = "I'm an instance of Foo", ID = 23 };
This creates an instance of ReallyLongFooClassName and then sets its members 'Name' and 'ID'.
This compiles to the same thing as if you typed this...
ReallyLongFooClassName reallyLongFooVarName = new ReallyLongFooClassName();
reallyLongFooVarName.Name = "I'm an instance of Foo";
reallyLongFooVarName.ID = 23;
So does Objective-C/C++ have anything equivalent to the member-brace-initialization of C#?
Note: Thanks to my other post, I already know that 'auto' is the 'var' equivalent in Objective-C++ but Objective-C doesn't have any such equal, which is a shame. Again, see my other post here for more info.)
Update
I'm aware of writing initializers. That is a different beat altogether. The technique I demoed above In C# uses the setters of the properties, or sets the member variables directly without having to write a constructor (their sort-of-equivalent to Objective-C's 'init' members.) Having to write init members forces you to have to pre-specify what you want to set. Member brace-initialization lets you specify any combination of properties/member variables and in any order you want. Again, it's just syntactic sugar for writing multiple lines of code at once. It doesn't actually change the class.
There are several alternative if you think of using Objective C/C++.
Objective C:
Create initialization method in class A as;
#interface ClassA:NSObject
-(id)initWithName:(NSString*)name id:(NSUinteger)id;
#end
#implementation ClassA{
NSString *name;
NSUinterger id;
}
-(id)initWithName:(NSString*)name id:(NSUInteger)id{
self = [super init];
if(!self)
return nil;
self -> name = name;
self -> id = id;
return self;
}
Initializing;
[[ClassA alloc] initWithName:#"MyName" id:1000];
Objective C alternative,
Using class or struct;
Using struct;
struct MyClass{
NSString *name;
NSString *identifier;
MyClass(NSString *name, NSUInteger identifier):name(name), identifier(identifier);
};
Initilializing;
MyClass *myclass = new MyClass(#"Sandeep", 1000);
Using class;
class MyClass{
private:
NSString *name;
NSString *identifier;
public:
MyClass(NSString *name = #"", NSUInteger identifier = 0);
};
I think this should some how answer your question.
You can write a helper function that does something similar (here in Objective-C++, but you can do this in Objective-C easily by taking a Class as parameter):
template<class T>
T* NewObject(NSDictionary *fields) {
static_assert(std::is_convertible<T*, id>::value,
"T must be an Objective-C class.");
auto* obj = [[[[T class] alloc] init] autorelease];
for (auto* key in fields.keys) {
auto* capitalizedKey =
[key stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:[key substringToIndex:1].uppercaseString];
auto* message = [NSString stringWithFormat:#"set%#:", capitalizedKey];
[obj performSelector:NSSelectorFromString(message) withObject:fields[key]];
}
return obj;
}
Then use it as follows:
auto* object = NewObject<MyClass>(#{
#"foo": #"bar",
#"baz": #42
});
I have not tested it, but it should work. Note that it won't work when setters take non-Objective-C-objects (such as int), but it is possible to alter the function to make this work (through reflection).
No, there is no such facility.
Objective-C takes the path of providing an initializer. Typically, the initializer takes the required arguments necessary to initialize an instance of the class. Sometimes, some of those arguments will be optional. I.e. you might have:
- (instancetype)initWithCar:(Car*)car tires:(NSArray*)tires cover:(Cover*)cover;
And cover might sometimes be nil.
In Objective-C, instances of classes are generally initialized with the required state to provide a minimal working instance and then you call various setters to then configure the class further.
Here are a couple approaches used in ComponentKit for inspiration:
{[CKLabelComponent
newWithLabelAttributes:{
.string = (indicatesSuccess ? #"Yes" : #"No"),
.color = [UIColor whiteColor],
.font = [UIFont fontWithName:#"Cochin-Bold" size:45.0],
.alignment = NSTextAlignmentCenter
}
viewAttributes:{
{#selector(setBackgroundColor:), [UIColor clearColor]},
{#selector(setUserInteractionEnabled:), #NO},
}]
},
You can take a variable number of named attributes either via
a struct with aggregate initialization (struct CKLabelAttributes)
an std::unordered_map (in this case, typedef std::unordered_map<CKComponentViewAttribute, id>) that contains whatever keys and values you want to use to initialize your class.
This syntax obviates the -initWithA:B:C:, -initWithA:, -initWithB:, ... explosion that usually happens with complicated Obj-C interfaces.
I'm working on a program that controls character in a game.
I want my users to be able to write Lua scripts in my program for the game.
There's an int variable in my program, int SelfManaPc, that is passed into scripter in that way: lua_compiler["SelfManaPc"] = SelfManaPc;.
This variable is being changed pretty fast in my main program in a different thread.
My problem is, that it is passing value only into Lua scripter, not the pointer.
After value change in C# program, in Lua scripts it doesn't change anymore.
I've made my solution and it works pretty well (SelfManaPc is now an object of my own class Integer so I can pass the pointer instead of value).
C# class:
public class Integer
{
int value;
public Integer(int xd) { value = xd; }
public void Set(int xd) {value = xd;}
public int Get() { return value; }
}
Example of use in Lua code:
while true do
Say(SelfManaPc:Get())
Sleep(2000);
end
If there's no other way, I'll leave it like that. But, I wanted to ask any of you first about any other ideas. It's kinda stupid to access int with Get and Set so some of you might know some nice trick.
If there are several such variables in your script, you can consider placing them inside a single global table, for example named options. Then you add a metatable to that table: __index metamethod returns the value of a variable given its name, and __newindex metamethod sets a new value to a variable given its name.
How to implement this depends on the binding library you are using for C#.
Example of use in Lua code:
while true do
Say(options.SelfManaPc)
Sleep(2000)
options.SelfManaPc = 1000 -- sets new value
Sleep(500)
end
This one's really an offshoot of this question, but I think it deserves its own answer.
According to section 15.13 of the ECMA-334 (on the using statement, below referred to as resource-acquisition):
Local variables declared in a
resource-acquisition are read-only, and shall include an initializer. A
compile-time error occurs if the
embedded statement attempts to modify
these local variables (via assignment
or the ++ and -- operators) or
pass them as ref or out
parameters.
This seems to explain why the code below is illegal.
struct Mutable : IDisposable
{
public int Field;
public void SetField(int value) { Field = value; }
public void Dispose() { }
}
using (var m = new Mutable())
{
// This results in a compiler error.
m.Field = 10;
}
But what about this?
using (var e = new Mutable())
{
// This is doing exactly the same thing, but it compiles and runs just fine.
e.SetField(10);
}
Is the above snippet undefined and/or illegal in C#? If it's legal, what is the relationship between this code and the excerpt from the spec above? If it's illegal, why does it work? Is there some subtle loophole that permits it, or is the fact that it works attributable only to mere luck (so that one shouldn't ever rely on the functionality of such seemingly harmless-looking code)?
I would read the standard in such a way that
using( var m = new Mutable() )
{
m = new Mutable();
}
is forbidden - with reason that seem obious.
Why for the struct Mutable it is not allowed beats me. Because for a class the code is legal and compiles fine...(object type i know..)
Also I do not see a reason why changing the contents of the value type does endanger the RA. Someone care to explain?
Maybe someone doing the syntx checking just misread the standard ;-)
Mario
I suspect the reason it compiles and runs is that SetField(int) is a function call, not an assignment or ref or out parameter call. The compiler has no way of knowing (in general) whether SetField(int) is going to mutate the variable or not.
This appears completely legal according to the spec.
And consider the alternatives. Static analysis to determine whether a given function call is going to mutate a value is clearly cost prohibitive in the C# compiler. The spec is designed to avoid that situation in all cases.
The other alternative would be for C# to not allow any method calls on value type variables declared in a using statement. That might not be a bad idea, since implementing IDisposable on a struct is just asking for trouble anyway. But when the C# language was first developed, I think they had high hopes for using structs in lots of interesting ways (as the GetEnumerator() example that you originally used demonstrates).
To sum it up
struct Mutable : IDisposable
{
public int Field;
public void SetField( int value ) { Field = value; }
public void Dispose() { }
}
class Program
{
protected static readonly Mutable xxx = new Mutable();
static void Main( string[] args )
{
//not allowed by compiler
//xxx.Field = 10;
xxx.SetField( 10 );
//prints out 0 !!!! <--- I do think that this is pretty bad
System.Console.Out.WriteLine( xxx.Field );
using ( var m = new Mutable() )
{
// This results in a compiler error.
//m.Field = 10;
m.SetField( 10 );
//This prints out 10 !!!
System.Console.Out.WriteLine( m.Field );
}
System.Console.In.ReadLine();
}
So in contrast to what I wrote above, I would recommend to NOT use a function to modify a struct within a using block. This seems wo work, but may stop to work in the future.
Mario
This behavior is undefined. In The C# Programming language at the end of the C# 4.0 spec section 7.6.4 (Member Access) Peter Sestoft states:
The two bulleted points stating "if the field is readonly...then
the result is a value" have a slightly surprising effect when the
field has a struct type, and that struct type has a mutable field (not
a recommended combination--see other annotations on this point).
He provides an example. I created my own example which displays more detail below.
Then, he goes on to say:
Somewhat strangely, if instead s were a local variable of struct type
declared in a using statement, which also has the effect of making s
immutable, then s.SetX() updates s.x as expected.
Here we see one of the authors acknowledge that this behavior is inconsistent. Per section 7.6.4, readonly fields are treated as values and do not change (copies change). Because section 8.13 tells us using statements treat resources as read-only:
the resource variable is read-only in the embedded statement,
resources in using statements should behave like readonly fields. Per the rules of 7.6.4 we should be dealing with a value not a variable. But surprisingly, the original value of the resource does change as demonstrated in this example:
//Sections relate to C# 4.0 spec
class Test
{
readonly S readonlyS = new S();
static void Main()
{
Test test = new Test();
test.readonlyS.SetX();//valid we are incrementing the value of a copy of readonlyS. This is per the rules defined in 7.6.4
Console.WriteLine(test.readonlyS.x);//outputs 0 because readonlyS is a value not a variable
//test.readonlyS.x = 0;//invalid
using (S s = new S())
{
s.SetX();//valid, changes the original value.
Console.WriteLine(s.x);//Surprisingly...outputs 2. Although S is supposed to be a readonly field...the behavior diverges.
//s.x = 0;//invalid
}
}
}
struct S : IDisposable
{
public int x;
public void SetX()
{
x = 2;
}
public void Dispose()
{
}
}
The situation is bizarre. Bottom line, avoid creating readonly mutable fields.