TypeScript static members vs namespace with class name - class

In TypeScript, I have been separating non-instance variables out of my classes and into a namespace with the same name as the class. For example:
class Person
{
age: number;
constructor(age: number)
{
this.age = age;
}
}
namespace Person
{
export let numberOfFingers: number = 10;
}
export default Person;
as opposed to this:
class Person
{
static numberOfFingers: number = 10;
age: number;
constructor(age: number)
{
this.age = age;
}
}
export default Person;
Is there any benefit to either of these methods?

As far as typechecking and code generation is concerned, both methods produce exactly the same results. I can offer two not very strong arguments in favor of static members:
it's the most obvious thing to do, it does not require knowledge of advanced parts of the language (declaration merging) to understand the code
if you ever need to have a function that creates and returns class definition (as described for example here, to simulate static generic member or to add a mixin), then namespaces will not work - you can't have namespace inside a function.

Related

do instances point to their own classes (to access methods)?

How can the compiler know what method is an object calling?
lets say for example:
class Person
{
string name;
int age;
void walk()
{
// do something with name and age
}
}
so I already know that it actually translate to a method which takes the instance itself as the first parameter, but how can the object itself access it?
do all objects of class person point somewhere where all the class methods are, and maybe even static variables (and methods)?

Expected default behavior for Grails RESTful mapping to Nested Resources

I have my Grails Domain classes annotated with #Resource with the uri specifications in UrlMappings where I declare the resource nesting. But even though according to https://docs.grails.org/latest/guide/theWebLayer.html#restfulMappings it seems that just declaring this the right way, I should have the correct behavior that I wanted, which is that a URL pattern such as /nesting/1/nested will list the nested domain that belonged to the nesting domain with ID 1, the observed behavior is that it just lists out all nested domain objects.
So for that, my workaround is to have a controller implemented that overrides the listResources to filter the nested domain by the nesting domain. But what's weird to me is why I even have to do that at all. The documentation said it defaults to the index action but said index action seems to just behave as if it's the index() of nested (without taking nesting into account).
My domain entities are WeightSensor:
#Resource(formats = ['json', 'xml'])
class WeightSensor extends Sensor<WeightData>
{
Set<WeightData> data
static constraints = {
}
}
its superclass Sensor
#Resource(formats = ['json', 'xml'])
class Sensor<T extends SensorData>
{
Set<T> data
static hasMany = [data: SensorData]
String name
static constraints = {
name unique: true
}
}
and WeightData
class WeightData extends SensorData
{
Float weight
static constraints = {
weight nullable: false
}
}
and its superclass SensorData
class SensorData
{
#BindingFormat('yyyy-MM-dd HH:mm:ss.S') // 2019-07-11 22:00:28.909
Date timestamp
static belongsTo = [sensor: Sensor]
static constraints = {
timestamp nullable: false
}
}
In my UrlMappings I have the following:
"/sensor/weight"(resources: 'weightSensor') {
"/data"(resources: "weightData")
}
My WeightDataController extends from a SensorDataController:
class WeightDataController extends SensorDataController<WeightSensor, WeightData>
{
#SuppressWarnings("GroovyUnusedDeclaration")
static responseFormats = ['json', 'xml']
WeightDataController()
{
super(WeightData, WeightSensor, "weightSensorId")
}
}
And SensorDataController in turn extends RestfulController, and overrides the listAllResources method as below.
import grails.rest.RestfulController
class SensorDataController<S extends Sensor, T extends SensorData> extends RestfulController<T>
{
String idProperty
Class<S> sensorType
#SuppressWarnings("GroovyUnusedDeclaration")
static responseFormats = ['json', 'xml']
protected SensorDataController(Class<T> dataType, Class<S> sensorType, String idProperty)
{
super(dataType)
this.idProperty = idProperty
this.sensorType = sensorType
}
#Override
protected List<T> listAllResources(Map params)
{
Long sensorId = params.get(idProperty) as Long
if (sensorId)
{
resource.withCriteria() {
eq 'sensor.id', sensorId
maxResults params.max ?: 10
firstResult params.offset ?: 0
} as List<T>
}
else
{
super.listAllResources(params)
}
}
}
Note because in order for me to have my WeightDataController class be used, I needed to remove the #Resource on top of WeightData domain entity above, another nice little gem of wisdom I had to discover with trial and error.
I can probably blame this on the fact that the documentation for nested resources seems a bit open to interpretation. But when we see in the documentation a URL like GET books/${bookId}/authors, doesn't that look like it should return the list of Author objects that belongs to the Book instance IDed by bookId?
I know that I'm not alone as I did find this online of someone asking the same question I have - https://gist.github.com/mnellemann/7cfff1c721ef32f0be6c63574795f795 but no one answered them either. I also came across another SO post nested RESTful resources that was abandoned 5 years ago as well.
But 3 people having the same question and no one responding to our questions (I asked mine on the Grails Slack community) usefully because there is a work-around is not acceptable. At the risk of having my question taken down for a slew of different reasons, I question the usefulness of even having the grails nested resource URL mapping in the first place because I could have done everything manually myself without having to "declare" such a nesting in UrlMappings.
In closing, what I'm trying to find out is whether or not there's more "configuration" I need to do to get Grails nested Resources to behave in the way that I expected, which is how the documentation painted, correctly. Because just doing what was described doesn't get me that.

Class Design - Object Oriented Programming Question

This was asked during an interview.
There are different manufacturers of buses. Each bus has got different models and each model has only 2 variants. So different manufacturers have different models with only 2 variants. The interviewer asked me to design a standalone program with just classes. She mentioned that I should not think about databases and I didn't have to code them. For example, it could be a console based program with inputs and outputs.
The manufacturers, models and variants information should be held in memory (hard-coded values were fine for this standalone program). She wanted to observe the classes and my problem solving approach.
She told me to focus on implementing three APIs or methods for this system.
The first one was to get information about a particular bus. Input would be manufacturer name, model name and variant name. Given these three values, the information about a particular bus such as its price, model, year, etc should be shown to the client.
The second API would be to compare two buses and the output would be to list the features side by side, probably in a tabular format. Input would be the same as the one for the first API i.e. manufacturer name, model name and variant name for both the buses.
The third one would be to search the buses by price (>= price) and get the list of buses which satisfy the condition.
She also added that the APIs should be scalable and I should design the solution with this condition on my mind.
This is how I designed the classes:
class Manufacturer {
private String name;
private Set<Model> models;
// some more properties related to manufacturer
}
class Model {
private String name;
private Integer year;
private Set<Variant> variants;
// some more properties related to model
}
class Variant {
private String name;
private BigDecimal price;
// some more properties related to variant
}
class Bus {
private String manufacturerName;
private String modelName;
private String variantName;
private Integer year;
private BigDecimal price;
// some more additional properties as required by client
}
class BusService {
// The first method
public Bus getBusInformation(String manufacturerName, String modelName, String variantName) throws Exception {
Manufacturer manufacturer = findManufacturer(manufacturerName);
//if(manufacturer == null) throw a valid exception
Model model = findModel(manufacturer);
// if(model == null) throw a valid exception
Variant variant = findVariant(model);
// if(variant == null) throw a valid exception
return createBusInformation(manufacturer, model, variant);
}
}
She stressed that there were only 2 variants and there wouldn't be any more variants and it should be scalable. After going through the classes, she said she understood my approach and I didn't have to implement the other APIs/methods. I realized that she wasn't impressed with the way I designed them.
It would be helpful to understand the mistake I made so that I could learn from it.
I interpreted your 3 requirements a bit differently (and I may be wrong). But it sounds like the overall desire is to be able to perform different searches against all Models, correct?
Also, sounds to me that as all Variants are Models. I suspect different variants would have different options, but nothing to confirm that. If so, a variant is just a subclass of a particular model. However, if variants end up having the same set of properties, then variant isn't anything more than an additional descriptor to the model.
Anyway, going on my suspicions, I'd have made Model the center focus, and gone with:
(base class)
abstract class Model {
private Manufacturer manufacturer;
private String name;
private String variant;
private Integer year;
private BigDecimal price;
// some more properties related to model
}
(manufacturer variants)
abstract class AlphaModel {
AlphaModel() {
this.manufacturer = new Manufacturer() { name = "Alpha" }
}
// some more properties related to this manufacturer
}
abstract class BetaModel {
BetaModel() {
this.manufacturer = new Manufacturer() { name = "Beta" }
}
// some more properties related to this manufacturer
}
(model variants)
abstract class AlphaBus : AlphaModel {
AlphaBus() {
this.name = "Super Bus";
}
// some more properties related to this model
}
abstract class BetaTruck : BetaModel {
BetaTruck() {
this.name = "Big Truck";
}
// some more properties related to this model
}
(actual instances)
class AlphaBusX : AlphaBus {
AlphaBusX() {
this.variant = "X Edition";
}
// some more properties exclusive to this variant
}
class AlphaBusY : AlphaBus {
AlphaBusY() {
this.variant = "Y Edition";
}
// some more properties exclusive to this variant
}
class BetaTruckF1 : BetaTruck {
BetaTruckF1() {
this.variant = "Model F1";
}
// some more properties exclusive to this variant
}
class BetaTruckF2 : BetaTruck {
BetaTruckF2() {
this.variant = "Model F2";
}
// some more properties exclusive to this variant
}
Then finally:
var data = new Set<Model> {
new AlphaBusX(),
new AlphaBusY(),
new BetaTruckF1(),
new BetaTruckF2()
}
API #1:
var result = data.First(x => x.manufacturer.name = <manufactuer>
&& x.name = <model>
&& x.variant = <variant>);
API #2:
var result1 = API#1(<manufacturer1>, <model1>, <variant1>);
var result2 = API#1(<manufacturer2>, <model2>, <variant2>);
API #3:
var result = data.Where(x => x.price >= <price>);
I would say your representation of the Bus class is severely limited, Variant, Model, Manufacturer should be hard links to the classes and not strings. Then a get for the name of each.
E.G from the perspective of Bus bus1 this.variant.GetName() or from the outside world. bus1.GetVariant().name
By limiting your bus to strings of it's held pieces, you're forced to do a lookup even when inside the bus class, which performs much slower at scale than a simple memory reference.
In terms of your API (while I don't have an example), your one way to get bus info is limited. If the makeup of the bus changes (variant changes, new component classes are introduced), it requires a decent rewrite of that function, and if other functions are written similarly then all of those two.
It would require some thought but a generic approach to this that can dynamically grab the info based on the input makes it easier to add/remove component pieces later on. This will be the are your interviewer was focusing on most in terms of advanced technical&language skills. Implementing generics, delegates, etc. here in the right way can make future upkeep of your API a lot easier. (Sorry I don't have an example)
I wouldn't say your approach here is necessarily bad though, the string member variables are probably the only major issue.

Limit autocompletion of macro function when used as a static extension to multiple types

When using a static macro function, meant to be used as a static extension, how can I limit types of variables that will get this function on an autocompletion list? Caveat: I know I can use ExprOf<T> but I need this for multiple types to check inside my macro if expr unifies with a specific abstract.
Besides leveraging the type system to perform that unification by itself, if possible, you might be able to use a temporary abstract exclusively for this "filtering".
// exclusively for static extension x autocomplete
private abstract PseudoType(Dynamic)
from ActualType1
from ActualType2
from ActualType3 {}
[...]
public static macro function myMacro(value:ExprOf<PseudoType>}
{
// ExprOf doesn't do anything other than help with autocomplete
// do actual unification here
// return the appropriate result
}
[EDIT] here's an example (live on Try Haxe/alt.):
Macro.hx:
import haxe.macro.Expr;
private abstract PseudoType(Dynamic)
from String
from Int
from { val:Float } {}
class Macro {
public static macro function magic(value:ExprOf<PseudoType>)
{
return macro Std.string($value);
}
}
Test.hx:
using Macro;
class Test {
static function main()
{
trace("Haxe is great!".magic());
trace(42.magic());
trace({ val : 3.14 }.magic());
}
}

Methods in a class. Should you set properties and have the method use properties or pass arguments?

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.