Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tiny js world oop #378

Merged
merged 3 commits into from
Sep 26, 2022
Merged

tiny js world oop #378

merged 3 commits into from
Sep 26, 2022

Conversation

bmukha
Copy link
Contributor

@bmukha bmukha commented Aug 31, 2022

tiny js world oop

Demo |
Code base

The code is submitted in a dedicated feature branch.

Only code files are submitted.

Please, review.

@github-actions
Copy link

Hey!

Congratulations on your PR! 😎😎😎

Let's do some self-checks to fix most common issues and to make some improvements to the code before reviewers put their hands on the code.

Go through the requirements/most common mistakes listed/linked below and fix the code as appropriate.

If you have any questions to requirements/common mistakes feel free asking them here or in Students' chat.

When you genuinely believe you are done put a comment stating that you have completed self-checks and fixed code accordingly.

Also, be aware, that if you would silently ignore this recommendation, a mentor can think that you are still working on fixes. And your PR will not be reviewed. 😒

A Tiny JS World -- OOP exercise check list

Relates to A Tiny JS World OOP exercise.

Check-list - definition of done

Minimal requirements to meet:

  • Implement a base class to inherit from
  • Employ default parameters
  • Each species is represented with its own class
  • No need to specify species at instantiation
  • Classes for species that do not have hands by natural design, do not consequently have hands or any equivalent property and do not inherit such properties from any base classes
  • All inhabitants are stored in a container (array or object)
  • JS native features are intensively employed (const, let, Array.map|join|forEach|..., etc)
  • Object methods like keys, values, entries as well as for...in shouldn't be used as these do not guarantee any particular order of keys/values
  • Properties used to form an object presentation string must be explicitly listed/specified; Use Array.map and Array.join to build a presentation string from the list.
  • A parent class shouldn't know anything about its children's props. Child classes must have good reasons to assign or refer to any parent's props. There are no such reasons in this task. Method overloading is to the rescue when building an inhabitant's presentation string.
  • OOP, SOLID and DRY principles are intensively employed

Optional level up (not required to implement):

  • Friends list is a list of objects refs rather than names (strings)
  • Cat-woman class is built employing composition rather than inheritance only

Bonus:

  • toString magic method; when implemented print(inhabitant) does the job as .toString is called implicitly
  • this.constructor.name; when used for output then no need to store species property

Helpful resources:

Universal recommendations:

  • Give variables and functions meaningful names. Avoid generic names like item, element, key, object, array or their variations. Exception: helper functions that are specifically and intentionally designed to be multipurpose.
  • Function names should start with a verb as they denote actions; variables are normally nouns; boolean variables/functions start with is, does, has etc; variable containing multiple entities and functions returning lists contain entity name in plural form.
  • Have consistent code style and formatting. Employ Prettier to do all dirty work for you.
  • Use common sense or seek for an advice whenever requirements look ambiguous or unclear.

Also take a note of the requirements above and follow them in all your future projects.

By the way, you may proceed to the next task before this one is reviewed and merged.

Sincerely yours,
Submissions Kottachecker 😺

@stale
Copy link

stale bot commented Sep 14, 2022

This issue has been automatically marked as stale because there were no activity during last 14 days. It will be closed in 7 days if no further activity occurs. Thank you for your contributions.

А. Чому так?
Найбільш розповсюджена причина: Студент не реагує на коментарі змінами коду і не задає запитань через брак часу або зміну життєвих пріоритетів. Покинуті піари відволікають менторів. Коли у студента з'явиться час, він/вона зможе перевідкрити той самий піар і продовжити роботу.

Б. Що робити, якщо в піарі нема оновлень, оскільки не зрозуміло, що треба зробити?
Варіант 1. Задати питання в самому PR.
Варіант 2. Задати питання в студентському чаті.

В. А якщо я все зробив(ла) і це ментор не рев'юває мої зміни?

  1. Переконайся, що ти відреагував(ла) на всі коментарі або кодом, або запитаннями, або відповідями. Напиши в PR і в чаті, що чесно вважаєш, що все зроблено і попроси повторне рев'ю. Якщо щось не зрозуміло, задай запитання.
  2. Реагуй на коментарі як менторів, так і інших учасників, включаючи ботів.
  3. Не ігноруй прохання типу * "Let's do some self-checks ..." * "Go through the checklist below..." * "mark fulfilled requirements..." * "if you would silently ignore this recommendation, a mentor may think that you are still working on fixes"
    навіть якщо вони написані ботом. Боти помічники і ментори покладаються на те, що прохання і пропозиції бота дотримуються.
    Не лінись піти по лінках в коментарях, погуглити термінологію та скористатись Google Translate.
  4. Можливо, у менторів склалися інші пріоритети через роботу, сімейні обставини і т.п. В такому разі, якщо ти зробив(ла) рекомендоване вище, то волай в чаті, що PR позначений stale, наче, все зроблено, а ментори чомусь не реагують - рятуйте!

Г. Хіба недостатньо того, що я додав(ла) коміт із змінами?
Часто буває так, що бачиш новий коміт, ідеш перевіряти, змін багато, доводиться перечитувати весь код. А потім з'ясовується, що одна невеличка зміна "відкладена на потім" чи з'являється ще один коміт і знов треба перечитувати все. Любіть нас, спілкуйтеся з нами - і ми відповімо повною взаємністю.

Традиційна пропозиція: задай питання по вищенаписаному в студентському чаті.

@stale stale bot added the 💤 Stale label Sep 14, 2022
@bmukha
Copy link
Contributor Author

bmukha commented Sep 15, 2022

I went through the self-check list, please, review.

@stale stale bot removed the 💤 Stale label Sep 15, 2022
@OleksiyRudenko OleksiyRudenko added the self-check-done Student confirmed that self-checks against requirements/common-mistakes are done label Sep 20, 2022
@OleksiyRudenko OleksiyRudenko self-assigned this Sep 20, 2022
Copy link
Member

@OleksiyRudenko OleksiyRudenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bmukha very well done.
A few improvements and it gonna be perfect if not ideal.

.map((prop) =>
Array.isArray(this[prop]) ? this[prop].join(', ') : this[prop]
)
.filter((value) => Boolean(value))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may want to filter values before converting them

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit confused about this one. In the previous version of this task, I deliberately rewrote that piece this way after your suggestions. And it really simplified my code because I can get rid of all the falsy values with one filter (because I convert possible empty arrays (still truthy values) into empty strings (falsy values) beforehand. Here are the links to our discussion:
Your suggestion
My reply
So, unless I'm missing something, I guess it is better to stick to this realisation. What do you think?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I see. Makes sense.
I was thinking of rather null or undefined to denote no friends situation.
Empty array is a valid approach. Keep this fragment as it is.

}

props() {
return ['specie', 'name', 'gender', 'legs', 'hands', 'saying', 'friends']
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every class should handle the properties it owns immediately. hands is not Character's own property.
Method overloading and explicit call to inherited version of the method are to the rescue.
Study what super can do. Original project docs offer 3 relevant articles. There is an answer there.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kinda thought that preserving the order of props in the resulting string across all entities is a key requirement of this task. Am I wrong? Because I just can't see the easy way to achieve this goal using super. Should I handle inherited props using super, concatenate own properties to the end of the string and call it a day or I must come up with some kind of solution to put them in the correct places in the string? Another approach I can think of - is to make separate props array for each class. This way I can preserve desired order of props for every class, and I don't need to use the super keyword at all, I can handle everything by calling a slightly modified inherited method from the very first class. Which approach should I take?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I handle inherited props using super, concatenate own properties to the end of the string and call it a day or I must come up with some kind of solution to put them in the correct places in the string?

Let's put aside the solution where we may want insert child's props between parents' props. Let's only append or prepend child's props. For the sake of simplicity

const selina = new CatWomen('Selina', []);

[beethoven, grizabella, clyde, bonnie, selina].forEach((character) =>
print(character.props())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A method/function name should start with a verb as they denote actions.

*/

class Character {
constructor(specie, name, gender, saying, friends, legs) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You will benefit from setting default values (here and/or other classes' constructor definitions).
Also consider objects as arguments and object destructuring (which also allows to assign default values to missing props) in function props. This will give you greater flexibility in property management.

@bmukha
Copy link
Contributor Author

bmukha commented Sep 23, 2022

I made the changes you requested. Please, take a look.

Copy link
Member

@OleksiyRudenko OleksiyRudenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bmukha nearly there. Let's polish it

Comment on lines 11 to 16
specie: this.specie,
name: this.name,
gender: this.gender,
legs: this.legs = 2,
saying: this.saying,
friends: this.friends = [],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the moment of instantiation this refers to not what you think it does.
{species} will extract property species from an object passed as a parameter.
In destructuring you only need to list properties you want to extract, providing default values where needed.
There is a pattern for "renaming" when destructuring, but it is not the case here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@OleksiyRudenko Updated again, please, review.

Copy link
Member

@OleksiyRudenko OleksiyRudenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bmukha great job!

@OleksiyRudenko OleksiyRudenko merged commit 9d02429 into kottans:main Sep 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
self-check-done Student confirmed that self-checks against requirements/common-mistakes are done task-TJSW-OOP
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants