I read it from vala tutorial
for readonly: vala
public int b { get; private set; }
in Genie:
prop readonly b: int
for writeonly:
Vala:
public int b { private get; set; }
Genie: [this line: syntax error]
prop writeonly b: int
How to declare an one-line writeonly property in Genie?
maybe something like?
prop XXX b: int
We can write a FOUR lines writeonly property:
class Wonly
_b: int
prop b: int
set
_b = value
init
var w = new Wonly
// print w.b // ERROR!! writeonly!!
w.b = 456 // OK
but How to write an one-line writeonly property?
I will do my best to answer your question here, however some aspects of your question are not clear. Maybe it would be help to give a bit more context, explaining better what you are planning to achieve and a little bit more of code for contextualization.
That said, I will assume you are asking about the syntax for class properties in Genie.
Properties are ways of hiding the implementation details from the users of the class you developed. According to Vala's tutorial this move is also called the information hiding principle in computer science.
In Vala, a propertie would be defined within a in the following way:
static int current_year = 2525;
class Person : Object {
private int year_of_birth = 2493;
public int age {
get { return current_year - year_of_birth; }
set { year_of_birth = current_year - value; }
}
}
In Genie, it would look like this:
class Foo : Object
prop name : string
prop readonly count : int
[Description(nick="output property", blurb="This is the output property of the Foo class")]
prop output : string
get
return "output"
set
_name = value
Now for the write only properties. It is a bit of a controversial matter based on this and this questions at SO. It seems to be useful only when you are not planning to read what you write. But as you can see on the questions above, most of the answers suggest the creation of methods instead of using write only properties.
That takes us to the syntax you are pointing to:
public int b { private get; set; }
You state that this is the syntax to a write only property in Vala, and it seems to be true. This is because, by setting the get as private you prevent the user to read the value. You can make the get or set as private in Vala by leaving it out of the set block as well, ie, in Vala you could simply remove the private get part.
Now this is where I am unsure, but I suggest you try it out in your code. Based on Vala's ability to set private getters or setters by removing them from the set block, I suspect that the same applies to Genie.
I removed the setting of the get from the following code and it compiled:
[indent=4]
class Foo : Object
prop name : string
prop readonly count : int
[Description(nick="output property", blurb="This is the output property of the Foo class")]
prop output : string
set
_name = value
init
var foo = new Foo()
Maybe that is what you are looking for, but I am not sure it would work in real code. If it does not, perhaps you would be better off with methods instead.
Related
I've got a class that contains multiple potential sources of value (of same Type ofc) and property that returns value of some source based on provided sources (in order of importance, including internal value). I'd simply call it Provider, but property can be set also (and this actually sets some source value based on the same logic), so it looks incorrect.
I'd rather call it Two-Way Provider or Contractor (which is cumbersome), but it feels like I've got some pattern here, that has a specific or comprehensive name. More of "near-the-truth" variants: Dispenser, Conductor, Supply, Agent, Contributor. Something as simple as Node, but more specific.
tl;dr: Name must reflect all or most of these statements:
class contains multiple external value sources that can be set "outside" (Exposer???)
class contains "default" internal value (that can be "overriden" by source values) (Container?)
class (property) always provide some value (Provider?)
that (class's) property can be set (Receiver?)
that value, which can be get or set, comes either from external value source (if any), either from internal value (Resolver?)
looks logical next to the Type of value that class (property) presents (example: FloatProvider)
public class FloatProvider //Needs proper name
{
public float internalValue = 1.0f; // these may be renamed
public Foo fooSource = null; // to make more sense
public Bar barSource = null; // in terms of the class
public float Value
{
get => GetValue();
set => SetValue(value);
}
public float GetValue()
{
if (fooSource!=null) return fooSource.value;
else if (barSource!=null) return barSource.value;
else return internalValue;
}
public void SetValue(float value)
{
if (fooSource!=null) fooSource.value = value;
else if (barSource!=null) barSource.value = value;
else internalValue = value;
}
public FloatProvider(float internalValue, Foo fooSource, Bar barSource)
{
this.internalValue = internalValue;
this.fooSource = fooSource;
this.barSource = barSource;
}
}
public class Foo
{
public float value = 10.0f;
}
public class Bar
{
public float value = 0.1f;
}
After days of head scratching and eventual epiphanies I think the Hub is the most appropriate term. But in my case I'd rather call the class by its purpose (FloatExt or something).
This question already has answers here:
Should I initialize variable within constructor or outside constructor [duplicate]
(11 answers)
Closed 6 years ago.
What is the difference between below 2 ways of assigning values for variables of a class.
Class A{
Private Variable v = someValue;
}
vs
Class A{
private Variable v;
//constructor
public A(){
this.v = someValue;
}
}
Can someone please explain?
There is no real difference from a code execution point of view.
As a previous answer says, I prefer declaring the variable outside of the constructor; for example:
public class A {
private int aValue = 100;
}
Instead of
public class A {
private int aValue;
public A() {
this.aValue = 100;
}
}
The reason being that if you have multiple constructors, you do not have to keep writing this.aValue = 100; and you are unable to "forget" to initialize the variable in a constructor.
As others have said however, there are times when it is better to initialize the variable in the constructor.
If it will change based on values passed to it via the constructor, obviously initialize it there.
If the variable you are initializing may throw an error and you need to use try / catch - it is clearly better to initialize it in the constructor
If you are working on a team that uses a specific coding standard and they require you to initialize your variables in the constructor, you should do so.
Given freedom and none of the above, I still declare it at the top - makes it much easier to find all of your variables in one place (in my experience).
See this duplicate answer: https://stackoverflow.com/a/3919225/1274820
What is the difference between below 2 ways of assigning values for
variables of a class.
Generally nothing, but ...
class constructor is an entry point when creating a new instance, so all assignments should be done there for readability and maintainability.
When you want create a new instance you start reading a source code at the constructor. Here is an example. All informations about new instance are in one proper place.
public class C {
private int aValue;
private int bValue;
private int cValue;
private int dValue;
public C(int a, int b) {
this.aValue = a;
this.bValue = b;
this.cValue = a * b;
this.dValue = 1000;
}
}
If you look at the MSIL of this class:
namespace Demo
{
public class MyClass
{
private string str = "hello world";
private int b;
public MyClass(int b)
{
this.b = b;
}
}
}
.method public hidebysig specialname rtspecialname
instance void .ctor(int32 b) cil managed
{
// Code size 25 (0x19)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldstr "hello world"
IL_0006: stfld string Demo.MyClass::str <---- RIGHT HERE
IL_000b: ldarg.0
IL_000c: call instance void [mscorlib]System.Object::.ctor()
IL_0011: ldarg.0
IL_0012: ldarg.1
IL_0013: stfld int32 Demo.MyClass::b
IL_0018: ret
} // end of method MyClass::.ctor
You can see that the constructor is "injected" with the assignment of this.str = "hello world".
So once your code is compiled, there is no difference what so ever. Yet, there are quite a few good reasons why you should not do it (user1274820's answer has some them)
Lets say i have a class to calculate tax. Which is the best practice to design the calcTax method. Option 1 or Option 2. The object pertains to a person and that is why we are storing age and income. I can see the pros and cons of each but just wanted to see if there is a best practice or if one of the two options has a code smell.
Option 1:
class CalcTax
{
private int Age;
private double Income;
public void Update(int age, double inc)
{
Age = age;
Income = inc;
}
public double calcTax()
{
return Age * Income * 0.25;
}
}
CalcTax obj = new CalcTax();
obj.update(5,500)
obj.CalcTax();
Option 2:
class CalcTax
{
public double calcTax(int age, int inc)
{
return age * inc* 0.25;
}
}
CalcTax obj = new CalcTax();
obj.calcTax(10,100);
Could go either way. Depends on what the object is supposed to represent.
If it there is one object for one person (I'm assuming Age and Income relate to a person), and that object is going to be doing a variety of things beyond the one calculation you show, then the fundamental attributes of that person (Age, Income, etc.) should be class attributes. These would likely be set as parameters to new() or perhaps set shortly after the instance was created.
If, however, this is just a calculator object, to be used to process requests for a variety of people, then there is no need to have Age and Income as class attributes at all. You could delete them your Option 2 example entirely, and just have them in the parameters to calcTax().
It probably ends there, with one of those options best matching your project. But if you're creating more of a library function that other programmers will be using in different ways in different projects, you could straddle the fence a bit...
Take Age and Income as parameters to new() and save them as class attributes. Then, make the parameters to calcTax() optional, and default to the class attributes if none are provided. That way, your developers can take whichever approach suits their needs best, and you've got a single codebase to support them both.
As the first comment says, the choice is yours. Try to think about what role your class will play. Is it just a collection of common math functions that you may want to call. If so, then methods with passable parameters are great.
However, if you're generating a tax class that will be specific to a certain context, then maybe something like the below would be best for you. The example below requires the Age and Income and offers up the CalculatedTax as a read-only property.
public class Tax
{
public Tax(int Age, int Income) //constructor, class can not be instantiated without these values
{
this.Age = Age;
this.Income = Income;
}
public int Age { get; set; }
public int Income { get; set; }
public double CalculatedTax //read only property
{
get { return double.Parse((Age * Income).ToString()) * 0.25f; }
}
}
Tax tax = new Tax(5, 1000);
double calculatedTax = tax.CalculatedTax; //1250
One benefit to the above example is that Age and Income are required to generate the CalculatedTax value. By forcing these parameters to be entered in the constructor you make sure they exist, otherwise (for this example) if these were your only three properties, what would be the point of making a class if you weren't going to include one of the required parameters.
I am creating a game in Unity3d.
Somewhere I have hints appearing in the bottom of the HUD (Something like "press A for Action"). I want my game to support more languages and I don't want these hints to be hard-coded in the script.
What is the most elegant way to solve this task? I am thinking about txt file, where I will have all my hints in all languages. But I am not sure, if it is a good idea.
Thanks in advance.
A common way that is used is to have an XML-file for each language. The XML-file should contain every phrase you use in your game with a unique ID.
In your code, you can then get the correct phrase out of the current language's XML, using the correct ID.
If you don't know about XML files, read this tutorial about using XML files in Unity: http://xeophin.net/en/blog/2010/05/13/reading-strings-out-xml-file-using-c-unity-3d
However if you are willing to spend some money on your game, you should check this out: http://u3d.as/content/rodrigo-barros/my-menu/32E
I haven't tried that yet but it seems good.
Hardcoding is not that bad if you do it correctly.
For example create an abstract class with all the messages that you want to have and language autodetection:
public abstract class Lang {
static Lang currentLang;
public static Lang Get {
get {
if(currentLang == null)
switch(Application.systemLanguage) {
case SystemLanguage.Polish:
currentLang=new LangPL();
break;
default:
case SystemLanguage.English:
currentLang=new LangEN();
break;
}
return currentLang;
}
}
public abstract string MenuTime {get;}
public abstract string MenuPoints {get;}
public abstract string YouWon {get;}
public abstract string YouLost {get;}
public abstract string Point(int p);
}
And then implement each language as a separate class:
public class LangPL:Lang {
public override string MenuTime {get {return "CZAS";}}
public override string MenuPoints {get {return "WYNIK";}}
public override string YouWon {get {return "Gratuluję, wygrałeś!";}}
public override string YouLost{get {return "Może następnym razem...";}}
public override string Point(int p) {
if(p == 1)
return "1 punkt";
return p+" punktów";
}
}
public class LangEN:Lang {
public override string MenuTime {get {return "TIME";}}
public override string MenuPoints {get {return "SCORE";}}
public override string YouWon {get {return "You won!";}}
public override string YouLost{get {return "Maybe next time...";}}
public override string Point(int p) {
if(p == 1)
return "1 point";
return p+" points";
}
}
Usage is a simple:
GUILayout.Label(Lang.Get.YouWon);
GUILayout.Label(Lang.Get.Point(5));
This way you have most control, and can easily support complex translations. Also this approach helps to trim down on errors - if you forget or misstype a text anywhere it throws a syntax error.
You can try to create a Javascript script or a C# script for each language and then depending of the language choosen, you call the specific script.
e.g
public class English : MonoBehaviour{
public string jump = "Press 'space' to jump";
//etc
}
public class French : MonoBehaviour{
public string jump = "Appuyer sur 'espace' pour sauter";
//etc
}
In your function for GUIText
public GameController gameController;
public GUIText text;
private string languageSelected;// obtain from the user input on language selection (better if registered in the gameController)
void Awake(){
languageSelected = System.Activator.CreateInstance(Type.GetType(gameController.languageSelected));
// where languageSelected will be e.g English
text.text = languageSelected.jump;
}
I strongly advise against embedding text into your code. It will slow down the localization process (having to look through code to find text is not the quickest and best way to approach localization).
Go with separate files. It's easier to maintain and translators don't have to access the code.
Have a look at l2 localization. It's a pretty handy Unity plugin that allows you to manage translations of your game.
All your localized strings in a single Google Spreadsheet. Once set up, all you need to do is fill it out to see the results in the game.
I am a game translator myself and happen to be managing a small team of game translators called Level Up Translation. We posted a beginner's guide for localization in Unity in our blog a couple of months ago. Feel free to check it out!
For example, you can save language file for france.txt in format:
hello=Bonjour
goodbye=Au Revoir
And than, read file and convert it to dictionary:
string[] lines = File.ReadAllLines("france.txt");
var dict = lines.Select(l => l.Split('=')).ToDictionary(a => a[0], a => a[1]);
Now you can read from dictionary by key:
string hello = dict["hello"];
what happens if you implement an automatic property
public string Foobar { get; set; }
and then code the corresponding variable
private string foobar = string.Empty;
Will the automatic property use this variable or does the compiler generate
an additional variable?
No, the automatic property will not use your variable. It would be just like any other field called foobar.
The name smilarity does not influence the compiler in any way.
The compiler will generate a field behind the scenes but you do not have access to the backing field of the automatic property in any way.
This post shows how things work at the IL (Intermediate Langauge, Assembly of C#) level.
The compiler won't use that variable, no. To use your variable you will have to write
private string foobar = string.Empty;
public string Foobar
{
get { return foobar; }
set { foobar = value; }
}
If you have Resharper, you can set up templates to do this. Resharper will also generate a getter from an unused private variable for you.
Why would it? Backing field doesn't have to be (and often isn't) named this way.